Query-optimizer search is inherently recursive: explore a group, derive plans, recurse into each input. The naive implementation is plain depth-first recursion. gporca doesn’t do that — it flattens the recursion into a task network, driven by a ready queue and a single reference counter.
This post takes apart the most subtle piece: the m_ulpRefs reference-count gate.
1. m_ulpRefs is not a lifetime counter
CJob::m_ulpRefs has three sources that must be read together:
| Source | When it changes | Meaning |
|---|---|---|
| ① Execution ref | +1 in PreExecute, −1 in EjrPostExecute | This job is being executed by the scheduler |
| ② Queue ref | +1 in CJobQueue::EjqrAdd | It is the queue’s main job; the “right to work” is held by it |
| ③ Child dependencies | +N when a parent spawns children; −1 as each child completes | N spawned tasks haven’t finished |
So:
refs(J) = ①running? 1 : 0 + ②queue main and running? 1 : 0 + ③unfinished children
While running, refs ≥ 1 (≥ 2 for a main job); while suspended, refs equals exactly the number of unfinished children.
2. The decision point: EjrPostExecute
The scheduler’s whole “brain” is one function:
ULONG_PTR ulRefs = pj->UlpDecrRefs(); // returns the value BEFORE decrementing
if (fCompleted) { assert(1 == ulRefs); return EjrCompleted; }
if (1 == ulRefs) return EjrRunnable; // now zero: no other dependencies
return EjrSuspended; // ulRefs-1 dependencies still pending
The semantics of return m_ulpRefs-- is the key: ulRefs == 1 means “I am the last holder” — after the decrement it’s zero, no outstanding dependencies.
That single idiom both releases the execution reference and tests for zero, shrinking the race window. It’s exactly the “the thread that decrements to zero destroys the object” idiom from Release().
3. Three outcomes
| Result | Condition | Follow-up |
|---|---|---|
EjrCompleted | State machine reached a terminal state, and this is the last holder | Settle, notify parent, recycle |
EjrRunnable | Not complete, but no dependencies left (self-loop event) | Put straight back on the ready queue |
EjrSuspended | Children still running | Do nothing; wait to be woken |
4. What if the same work is triggered twice?
CJobQueue gives you single-flight deduplication:
- For a given group / optimization context, only one job actually works (the main job);
- Others queue up and are released when the main job finishes.
That’s why “the same group scheduled from multiple paths” neither duplicates work nor corrupts state.
5. The state machine is the bookmark
Each job action returns an event. Returning a self-loop event means “I spawned children and am suspending”; the next entry resumes from the point recorded in the state machine — internal cursors (m_ulChildIndex, m_pgexprLastScheduled) keep “continue where I left off.”
CJobStateMachine’s record is, literally, the call stack flattened onto heap objects.
6. How this compares to common patterns
| Conventional | gporca |
|---|---|
| Recursive DFS calling functions | One job per recursion level; parents don’t block; they suspend |
| Call stack as bookmark | State machine as bookmark |
join() blocking the thread | Refcount reaches zero → parent goes back to the queue |
| Locks for dedup | CJobQueue: winner is main, losers suspend |
| Recursion depth limits, hard to interrupt | Every job boundary is an abort/timeout checkpoint (GPOS_CHECK_ABORT, FTimedOut) |
7. Why bother
- Interruptibility: check timeouts or cancellation at any point instead of waiting for the whole recursion;
- Parallelism: the ready queue is designed for multiple workers to grab tasks;
- Boundedness: every job boundary is a natural cancellation point, so search stays under control.
The price is harder debugging: a bug can look like “suspended forever,” visible only as a stalled task count in the trace. Understanding the three sources of refs is what lets you read those assert(0 < refs) checks.
8. Summary
One sentence: refs is the gate, the state machine is the bookmark, the job queue is the dedup table. Together they turn a run-to-completion recursive search into a pausable, resumable, parallelizable, interruptible task network.
Next: the DP cell in the memo — why one optimal plan per group isn’t enough, and why the key is (group, required properties, stage).
Related
- Reading gporca (Part 3): The Key of a DP Cell — (Group, Required Properties, Stage)
- Reading gporca (Part 1): Only ~11K of Its 400K Lines Are Actually Framework
- Porting a 1999 Cascades Optimizer to Modern C++: The COLUMBIA Story
Get the next essay
New essays on products, business and tech — plus what the experiment's numbers actually say.