Skip to content

refactor(core): replace split session wake state with durable doorbell - #67630

Open
jlongster wants to merge 4 commits into
devfrom
feat/session-durable-doorbell
Open

jlongster wants to merge 4 commits into
devfrom
feat/session-durable-doorbell

Conversation

@jlongster

@jlongster jlongster commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

Issue for this PR

Follow-up to #63416. Design: https://share.opncd.ai/eg6KEfnCzKqf

Type of change

  • Bug fix
  • New feature
  • Refactor / code improvement
  • Documentation

What does this PR do?

"Does session S owe a drain?" was split across four places: the coordinator's in-memory pendingWake, the job outbox, session_inbox.wake_on_restart, and time_suspended plus restart's wakes/defer/suspended sets. The Tear model of subagent reports, stops, cancels and crash restarts found states where those disagreed.

This PR stores the answer in one nullable column, session_v2.doorbell ("steer" | "input"). Together with time_suspended it gives each session one of four states:

time_suspended doorbell state
NULL NULL idle
NULL set ringing (owes a drain nobody has claimed)
set NULL draining
set set draining, plus one coalesced wake

Work moves between the two columns inside existing SQLite transactions, and no wake scope lives in memory:

  • Admission rings. SessionInbox.admit({ wake }) rings in the InboxEnqueued commit, and steer/admitCompaction do the same. A reconciled duplicate never rings again, so replaying the outbox can't revive a stopped parent. SessionEvent.InboxEnqueued is unchanged.
  • Start claims. Execution.Started's commit calls claimAndTake. An unforced start that finds the doorbell already silenced rolls back with nothing published.
  • The loop takes. After each drain the coordinator clears the doorbell. That clear runs in a transaction serialized with interrupt.
  • Settlement checks again. It peeks without clearing, using recheck/interruptEpoch, so the successor's own claim moves the bell. Teardown leaves the doorbell alone.
  • Stop silences. interrupt silences the doorbell in the same transaction as the coordinator interrupt. With { resume: true } it leaves a "steer" ring and pokes when no active execution picked that ring up.
  • Wake vs. poke. execution.wake(id, scope) means ring and then poke. execution.poke(id) only checks the doorbell, for callers whose admission already rang it.
  • Revert and archive. RevertEvent.Committed and Archived clear the doorbell. A staged revert only mutes it, so revert.clear plus a poke hears reports that arrived while the session was reverted.
  • Restart runs in four phases:
    1. A recursive CTE abandons subtrees under a deleted root, and agent() children (claimed or ringing) whose script died along with their whole subtree. It clears claims and doorbells and deletes their running Job rows. Settled reports still reach an abandoned parent's inbox, but without waking it. Unsettled cancelled children are cleared on the child only.
    2. The outbox is replayed through SessionInbox directly, with no Session.Service dependency.
    3. Claims resume under the budget. Budget exhaustion commits both release and silence.
    4. Every unclaimed ringing session is poked, inside Effect.ensuring.

Deleted: pendingWake, session_inbox.wake_on_restart (the migration backfills it into doorbell = 'steer'), SessionInbox.retireWakes, Job.completeBackground's wakeParent transfer transaction, store.release's wakeThroughSeq, the one-level releaseOrphanedChildClaims, and restart's in-memory wakes set.

Fixes these Tear-reproduced bugs:

  1. A stop racing a report's acknowledgement revived the parent, whether it was still stopping or had already settled. This happened at one level and two levels down, and under an agent() child (Carbon feat: model config persistence #3).
  2. interrupt({ resume: true }) followed by a crash before the successor claimed stranded the steer (Carbon feat: add configuration persistence for model selections #4).
  3. A cancel persisted before the child released its claim, followed by a crash, revived the cancelled child and produced a duplicate report (Carbon #1a).
  4. A coalesced drain that failed left its wake mark, so restart revived the failed child, which reported again (Carbon Roadmap & Existing Issues #2).
  5. Orphan cleanup only went one level deep, so a subtree under a deleted root resumed (Carbon #1b, plus a new orphan-subtree case).
  6. A dead Code Mode agent() child, or its grandchild, was revived on restart (Carbon #1c, plus a new grandchild case).

Decision: when a Code Mode agent() child is in flight at restart, its whole subtree is abandoned. Grandchildren are not resumed, and their running Job rows are dropped. This matches the Tear model.

How did you verify your code works?

  • Tear (/tmp/opencode/tear-subagent-wake, OC_TEAR_TARGET set to this branch). The host's completeBackground fault injection now reads the parent from the outbox row instead of wakeParent. I confirmed it still fires by checking for its crash after ack…, stop P after ack, crash before P claims and crash after cancel … persisted log lines in trace.ts runs. As a control, the same host still reproduces bug 1 on the pre-PR core.
    • --runs 40 --seed 1: 40/40, 424 steps
    • --runs 150 --seed 7 --novelty: 150/150, 1599 steps
    • --runs 200 --seed 11 --novelty --weight Break=3 --weight Fix=3: 200/200, 2214 steps
    • --runs 100 --seed 42 --novelty: 100/100, 983 steps
    • Total: 490 runs, 5220 steps, 0 failures.
    • Along the way Tear found one counterexample class: a settled report to an abandoned agent() parent was dropped. The fix is above: only running Job rows are deleted, and settled reports are delivered without waking anyone.
  • New tests in session-execution.test.ts (SessionDoorbell describe), one per bug: stop after ack with the parent still stopping and with it settled, resume-interrupt crash point, cancelled child with a rung doorbell, failed coalesced drain, two-level orphan subtree, dead agent() subtree with a quiet settled report. subagent-idle-e2e now also checks that the doorbell is durable in the acknowledgement crash image.
  • Checks: bun script/migration.ts --check passes. bun run typecheck:tsc passes in packages/core and packages/server. oxlint is clean on the changed files.
  • Targeted tests: session-execution, session-run-coordinator, session-move, session-revert, session-projector, subagent-report, subagent-completion, job, session-prompt, session-shell, session-owned, automation, automation-event, tool-subagent, tool-shell, v1-migration, session-store, session-background, session-runner-recorded, session-wait, and server session-diff all pass. Three subagent-idle-e2e tests fail identically on origin/dev without this change: "a slow script stays in the foreground with the flag off", "reports immediately with running background work…", and "nested subagents report one level at a time".

Screenshots / recordings

N/A

Checklist

  • I have tested my changes locally
  • I have not included unrelated changes in this PR

Added by the opencode bot (AI-generated).

Related: #66398

@opencodejr opencodejr Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The design holds up: a single durable doorbell, moved inside the existing commits, replaces four sources of truth that could disagree. I found no regressions. I ran the targeted core suites (session-execution including the new SessionDoorbell cases, run-coordinator, subagent-report/completion, job, revert, move, v1-migration, tool-subagent, subagent-idle-e2e, prompt, shell, owned, automation, runner-recorded): all pass, and typecheck:tsc is clean in packages/core. I did not reproduce the original Tear failures on the base.

Public API: unchanged. wake/poke, store.abandonSubtrees and the session_v2.doorbell column are internal, and the migration backfills wake_on_restart.

One gap worth closing in this PR: automation.ts still calls execution.wake. It does so in the startup rewake sweep (~L775) and in the "re-wake in case the first wake was lost" timer path (~L589). Before this change those were harmless in-memory nudges. Now wake rings the durable doorbell again, so a session the user stopped while an automation prompt was still pending in its inbox gets revived on the next boot. That is the replay-revives-a-stopped-session case this PR closes for the outbox. The prompt's admission already rang the doorbell, and wakes can no longer be lost, so these should be poke.

Related: #66398

@opencodejr opencodejr Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My earlier point is addressed: the startup rewake sweep in automation.ts now pokes instead of re-ringing, with a test. The other follow-ups look sound: interrupt now silences the doorbell even when idle or already stopping, and a start that a stop overtook takes nothing. The new and changed tests pass and typecheck:tsc is clean in packages/core.

Public API: unchanged.

One new question, inline: abandonSubtrees now treats every agent() child as dead after a restart, not only those that were in flight.

Comment thread packages/core/src/session/store.ts Outdated
SELECT s.id FROM ${SessionTable} AS s
WHERE s.id NOT IN (SELECT value FROM json_each(${keep}))
AND ((s.parent_id IS NOT NULL AND s.parent_id NOT IN (SELECT id FROM ${SessionTable}))
OR (json_extract(s.metadata, ${marker}) = s.id

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This now roots the dead tree at every agent() child, idle or not, instead of only ones that were claimed or ringing. Users can open such a child and keep working in it directly. If that work started a background subagent, a restart now drops the grandchild's running Job row and abandons its subtree, and its report arrives without waking anyone. The base only released the agent() child's own claim, and the previous revision only matched in-flight children. Is abandoning a long-finished agent() child's later subagents intended? If not, keep the root condition limited to children that were in flight, i.e. claimed or ringing.

@jlongster
jlongster force-pushed the feat/session-durable-doorbell branch from 2242cd5 to 91eaca1 Compare December 2, 2026 02:39

@opencodejr opencodejr Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My earlier point about abandonSubtrees treating every agent() child as dead is addressed. With #67411's closed-worker model now in the base, finished agent() children are closed and read-only. The base's restart cleanup already closes unclosed workers this process doesn't hold open, and runs first. Open workers are passed in keep. So the case I raised, a user continuing to work in a finished agent() child, no longer applies.

The other changes in this commit look sound:

  • interrupt always silences the doorbell.
  • A start that a stop overtook takes nothing.
  • There is a new migration test for the wake_on_restart backfill.

The closest core suites (12 files, including codemode-agents-e2e and shell-restart) pass, and typecheck:tsc is clean in packages/core.

Public API: unchanged.

- interrupt always silences the doorbell (idle, stopping or running) and
  always reaches the coordinator, which bumps interruptEpoch first
- a start overtaken by an interrupt takes nothing: unforced starts roll
  back as Silenced, forced ones only claim; joiners get the interrupt exit
- abandonSubtrees seeds every agent() child (unless a running follow-up
  Job owns it), excludes keep inside the CTE, and writes in SQL
- automation rewake pokes instead of ringing over a user stop
- migration test for the wake_on_restart -> doorbell backfill

- abandonSubtrees treats every Code Mode worker not held open as dead,
  matching #67411's closed-worker model (its restart sweep runs first)
@jlongster
jlongster force-pushed the feat/session-durable-doorbell branch from 0febdfc to 3783557 Compare December 2, 2026 20:04

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant