Lanes + Queues (Implementation): sessionKey / session & global two-level queuing
This page turns concurrency control into a replicable state machine: per-session in-order task starts, global limits, and in-process reset. A single session starts its tasks serially in enqueue order while multiple sessions run in parallel: sessionKey defines message ownership for routing; lanes/queues define scheduling. When it’s wrong, you get cross-talk, disorder, and context corruption. sessionKey ownership is addressing, not authorization — who may read a session is decided elsewhere (see the multi-device guide).
From source (pinned revision 9741e91): src/process/command-queue.ts, src/agents/pi-embedded-runner/run.ts, src/gateway/server-lanes.ts. The default enqueue path is two-level (run.ts L243–L260): the outer session lane (one per session, default maxConcurrent=1) queues first, then the task queues again on the chosen global lane; in the pinned source params.enqueue can replace both levels, so the conclusions here are scoped to the default path. Different global lanes (Main/Cron/Subagent, say) have independent caps — there is no single cross-lane budget — and different sessions run concurrently while the chosen global lane has headroom. How the routing key decides ownership is covered in routing + concurrency; this page focuses on the queue’s own state branches and diagnostics.
Entry points (concept):
Code entry points (optional)
src/process/command-queue.tssrc/agents/pi-embedded-runner/run.ts(the two-level default enqueue path;lanes.tsis a reading entry only — this page’s conclusions do not depend on it)src/gateway/server-lanes.ts
Core data structures (keep them explicit)
LaneState:queue,activeTaskIds,maxConcurrent,draining,generationQueueEntry:enqueuedAt,warnAfterMs,onWait(warn-only, no cancel)
Critical flow (enqueue → drain → finalize)
- drain immediately on enqueue (don’t wait for the next event).
drainingprevents re-entrant pumps.- pump on failures too (avoid starving the queue).
Branch semantics: five states that are easy to misread
Each row below is read from the pinned command-queue.ts; use it to decide “I saw X → what does it actually prove”:
| Branch | Exact semantics | Diagnostic boundary |
|---|---|---|
queue.push / queue.shift / activeCount < maxConcurrent | Entries join the queue tail in arrival order; the pump starts tasks FIFO only while active count is below the cap. What is guaranteed is the start order — completion order, external delivery order, and side-effect completion order are all different and not covered | First verify the actual sessionKey, the normalized lane, and the global lane; then compare queued/active counts with enqueue/dequeue logs. Observations locate the layer; they are not an authorization proof |
warnAfterMs (default 2s) / lane wait exceeded | When a task is dequeued, the time already waited is checked: at or past the threshold a warn is logged, and the onWait callback fires if provided — warning only | The warning is not a timeout-cancel; the task still runs. By itself it doesn’t prove a model failure either, only a long queue wait |
gatewayDraining vs lane.draining | The former is gateway-level draining (before restart): new enqueues are rejected with GatewayDrainingError; the latter is the per-lane pump re-entrancy guard — the queue keeps making progress | These are two different states; don’t collapse them into one “stopped” state. When new tasks are rejected, first identify which level rejected them |
completeTask generation check | A task carries the generation it started with: same-generation completion (success or failure) frees the active slot and pumps; an old-generation completion neither frees new-generation active nor pumps. If the old task later returns or throws, its original Promise still resolves/rejects — what is ignored is the active bookkeeping and the pump, not the Promise settlement | “Promise settled” is not “side effects stopped” — there is no evidence that an old-generation task’s external side effects were cancelled with it |
clear vs reset | clearCommandLane only rejects queued-but-not-started entries (with Command lane cleared); it never touches active tasks. resetAllLanes clears active, bumps the generation, preserves queued, and resumes draining — built for SIGUSR1 in-process restarts | clear never terminates active tasks; reset is in-process recovery, proves nothing about persistence across an OS process exit — don’t promise “tasks survive restarts” on this basis |
reset/generation (the key to “no dead lane after an in-process restart”)
The lanes map is in-memory (Map in src/process/command-queue.ts); resetAllLanes is documented in-source for SIGUSR1 in-process restarts (L230–245): interrupted tasks’ finally blocks may not run, so it bumps each lane’s generation, clears activeTaskIds, and drains preserved backlog. An old-generation completion detected by the mismatch check is ignored for active bookkeeping and pumping — stale callbacks don’t write into new state; if the old task later returns or throws, its original Promise still resolves/rejects. Reset itself does not settle or cancel the task, nor guarantee that a suspended task eventually completes or that its external side effects stop.
This says nothing about recovery after the OS process exits — an in-memory queue cannot survive that, and this function is not evidence either way about any separately persisted component. Don’t promise “unfinished tasks survive restarts” on this basis.
Distinct from clear: clearCommandLane makes queued-but-not-started entries fail with a Command lane cleared error; resetAllLanes preserves queued entries and re-drains them.
Failure modes and troubleshooting
Troubleshoot as “check where → observe what → what it proves → next step”, with per-branch semantics in the table above:
- Suspected out-of-order task starts in one session: check the queue logs (enqueue/dequeue and lane names) — first verify the actual sessionKey normalizes to one lane,
maxConcurrentwasn’t raised, and no reset (generation bump) happened meanwhile. Observed start order only proves that lane’s scheduling; it proves nothing about channel message arrival order, and even less about access control. - Dead lanes: verify failure paths still pump and
drainingisn’t stuck. - New tasks rejected: first distinguish
GatewayDrainingError(gateway draining, new enqueues rejected) from other pre-enqueue validation failures — the two call for completely different follow-ups. - Probe lane log spam: treat probe failures as expected and keep them quiet.
Acceptance checks
Reader-executable scenarios to verify — these are not measurements run by this site; they are scenarios you can verify against the pinned source behavior in your own environment:
- Same-lane serial starts: on the default path, same normalized session lane,
maxConcurrent=1, same generation — send several messages to one session and check the queue logs: task start order matches enqueue order (watch starts, not the arrival order of channel replies). - Same global lane under its cap: tasks from two sessions run concurrently while they share one global lane with headroom; set that lane’s cap to 1 with the first task still running and retry — the other session’s task should be observed waiting. Waiting there is not a fault. Different global lanes have independent caps and don’t share this budget.
- No deadlock after reset: after a SIGUSR1 in-process restart, previously queued tasks keep draining; if an interrupted old task later returns or throws, its original Promise still resolves/rejects — reset itself does not settle or cancel the task, nor guarantee eventual completion or that its external side effects stopped.
- clear only clears the queue: run clear on a lane with queued entries — queued items should fail immediately with
Command lane clearedwhile a running task is not terminated.