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:

SourceWhen it changesMeaning
① Execution ref+1 in PreExecute, −1 in EjrPostExecuteThis job is being executed by the scheduler
② Queue ref+1 in CJobQueue::EjqrAddIt 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 completesN 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

ResultConditionFollow-up
EjrCompletedState machine reached a terminal state, and this is the last holderSettle, notify parent, recycle
EjrRunnableNot complete, but no dependencies left (self-loop event)Put straight back on the ready queue
EjrSuspendedChildren still runningDo 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

Conventionalgporca
Recursive DFS calling functionsOne job per recursion level; parents don’t block; they suspend
Call stack as bookmarkState machine as bookmark
join() blocking the threadRefcount reaches zero → parent goes back to the queue
Locks for dedupCJobQueue: winner is main, losers suspend
Recursion depth limits, hard to interruptEvery job boundary is an abort/timeout checkpoint (GPOS_CHECK_ABORT, FTimedOut)

7. Why bother

  1. Interruptibility: check timeouts or cancellation at any point instead of waiting for the whole recursion;
  2. Parallelism: the ready queue is designed for multiple workers to grab tasks;
  3. 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).

Get the next essay

New essays on products, business and tech — plus what the experiment's numbers actually say.