Skip to content

fix(gateway): handle interrupted background command delivery - #502

Merged
nixuuu merged 1 commit into
devfrom
fix/unhandled-fiber-interrupt
Nov 10, 2026
Merged

nixuuu merged 1 commit into
devfrom
fix/unhandled-fiber-interrupt

Conversation

@nixuuu

@nixuuu nixuuu commented Nov 10, 2026

Copy link
Copy Markdown
Member

Change

Stopping the gateway while a worker command ACK is being persisted could produce an unhandled All fibers interrupted without error rejection. Callers detach coreDeliver(), but its catch covered only sending the command: bot dispatch checks, commandDone() and result reconciliation could reject outside it when ManagedRuntime.dispose() interrupted their SQL fibers. This is a product shutdown bug.

Observe the entire background delivery through the managed runtime's runPromiseExit(). Pure interruption ends quietly; other failures produce a bounded diagnostic without command contents. An ACK that did not commit leaves the command in the outbox for reconnect. Add a PostgreSQL row-lock regression that forces interruption during ACK persistence, checks unhandledRejection, verifies the pending outbox entry and restarts the gateway to confirm delivery recovers. Document the shutdown behavior.

Verification

Read attempt 1 of CI run 42820024558. Its stack has no application frame identifying the original command. The regression deterministically produces the same error on the original code; the original three files did not reproduce the flake naturally.

Completed sequential runs, one file per process, using bun run check:tmp tests/integration/<file>.test.ts:

File Before After
command-shutdown (forced ACK interruption) 0/30 passed; 30/30 failed with the matching interruption 30/30 passed
bots-harness 30/30 passed 30/30 passed
branch-names 30/30 passed 30/30 passed
composer-choices 30/30 passed 30/30 passed

Every completed invocation passed the temp-directory cleanup check. One baseline bot invocation ended with exit 143 and was rerun; the table counts completed invocations only.

Also passed: bun install, bun run typecheck, bun run lint, bun run format:check. The implementation and regression received a self-review. Full unfiltered tests, gen:check and the web build were not run locally under the workspace verification limits; CI covers those gates.

No specific recent introducing PR was established; #496 is context only.

Related: #496

@nixuuu
nixuuu merged commit a567093 into dev Nov 10, 2026
9 checks passed
@nixuuu
nixuuu deleted the fix/unhandled-fiber-interrupt branch November 10, 2026 14:05
nixuuu added a commit that referenced this pull request Nov 10, 2026
Linked bots can stay missing in web/desktop even when both computers
show connected. `ListBots` served only the in-memory peer-read cache
while a home was online, so a cold/evicted cache or an A gateway restart
returned no remote bots despite a committed bot mirror. The background
read eventually completed, but the web bot store ignored
`linkedReadCompleted("ListBots")`. Since #458 disabled polling when the
gateway advertises pushed bots, that incomplete list could persist until
another bot change or client reload.

Use the committed mirror while the online read cache is loading or
stale, and continue refreshing the authoritative home list in the
background. Bot mirror commits also mark the home's list cache due and
announce a list invalidation. The web bot store now handles that
invalidation. Mobile already handles it through `OverviewInvalidation`
in its shared query bus, so its implementation remains unchanged.
Existing dimmed/read-only rows and gateway rejection of offline writes
remain in place. Updating A restarts its gateway and client
subscription, restores the persisted mirror immediately and refreshes
from B automatically; no manual resync, database repair or re-pairing is
required.

The original cold-cache behavior comes from #348; #458 turned a
transient incomplete web list into persistent missing rows. History does
not implicate #502 (worker command delivery), #507 (connection
recovery), #500 (workspace/config sharing) or #475 (row badge
rendering). A plain warm-cache B restart did not fail in the baseline.
The cold-cache and A-restart cases reproduce a failure path matching the
report; the maintainer's live stack and databases were not inspected or
changed.

Extract the unchanged feed-negotiation helper from `routed-overview.ts`
to keep the file and watch function within the repository's size limits.
Update the Polish bot and linked-computer documentation.

## Verification

- RED, before the production fix: `TMPDIR=/var/tmp bun run check:tmp
tests/integration/linked-bots-resync.test.ts` — 2 failed, 2 passed. The
cold online-cache read and first list after A restarted omitted B's bots
despite their persisted mirror. Temp cleanup passed.
- GREEN: **30/30 sequential complete-file runs passed**, one test
process at a time using the same `check:tmp` command. Each final-file
run passed all five integration scenarios (150 scenario passes in total)
and left nothing in its private temp directory.
- Coverage: two real gateways, separate PostgreSQL databases and an
actual mTLS link; active and archived bots with last-message previews;
same-version B restart and restart with advertised app version changing
from nightly.119 to nightly.121; A's one ongoing overview watch and
fresh API reads; read-only/offline write rejection; A gateway restart
with its database retained; deletion, archive/unarchive and message
changes made while B was away, then convergence after a fresh B runtime.
Version coverage changes the handshake version on the current
implementation; it does not run historical release binaries. The client
is exercised at the public API/feed boundary; no UI test suite was
added.
- Related suites, run sequentially one file at a time through
`check:tmp`: `linked-reads` (4 passed), `linked-list-retention` (1
passed), `linked-agents` (16 passed). All three temp cleanup checks
passed.
- `bun install`, `bun run typecheck`, `bun run lint`, `bun run
format:check`: passed. Implementation and regression coverage received a
self-review. Full unfiltered tests, `gen:check`, a web build and
browser/device checks were not run locally under the workspace
verification limits; CI covers the broader automated checks.

Copy audit (`docs/copy.md` §8): no UI text added or changed.

Fixes: #458
Related: #348
nixuuu added a commit that referenced this pull request Nov 10, 2026
## Change

Sending a prompt as a turn ends can leave it accepted without ever
reaching the harness, or attach an unrelated Codex wake-up's summary to
the user's turn. Recover undelivered steers as their own queued turns
and bind Codex turn IDs using the response to the corresponding
`turn/start` RPC.

Two defects reproduce on the original code:

1. Gateway fallback only found `dropped` steers. A successful steer RPC
followed by `turnFinished` without a matching `userMessage.clientId`
remained `pending`/`accepted` indefinitely unless the worker separately
sent a rejection or `steer_dropped`. The same loss occurs when a short
subagent-report wake-up ends around the user's send. Queue pumping now
recovers these inputs idempotently, and the startup/periodic sweep also
finds them in already idle threads after a gateway restart. Late ACKs
cannot reverse recovery; confirmed steers remain delivered.
2. The Codex adapter assigned the next unknown `turn/started` to the
oldest pending platform input. A provider-started turn could consume
that slot before the actual `turn/start` response; its old-work summary
and completion then appeared under the user's turn ID. Only the RPC
response now establishes that mapping. Notifications wait per thread
until admission resolves, preserving order and independent provider
turns, including when admission fails. Runtime draining still waits for
buffered events to be journaled.

Existing UI delivery states now advance honestly: RPC acceptance still
waits for the user-message echo; confirmed echoes get “Steered into this
turn”; an unconsumed input publishes `queued`, `queuedTurnId` and the
existing fallback reason, then appears as its own turn. No UI
components, copy, contracts or database schemas changed.

Add concise JSON diagnostics for committed send decisions
(`message_decision`: new turn/steer/queue and a categorical reason),
steer acceptance/consumption/requeue/release, and turn start/end with
the persisted trigger (`user`, `agent_bus`, `background_task`, etc.).
Codex warns once per old turn about late model/lifecycle events while
allowing normal background-command output. These diagnostics contain
identifiers and states, without prompts, responses, paths, secrets or
provider error text.

The maintainer-provided logs around 2026-11-10 19:34 UTC confirm
repeated governor saturation (`active=5 queued=0 dropped=0`) but contain
no turn-level evidence identifying the incident's path. This counter
does not identify five subagents. Requests to an existing Codex
app-server use its established RPC transport; they do not reserve
process slots. A fixture test confirms new input still runs with all
harness slots occupied. New harness launches can encounter
back-pressure, and preparatory short operations can queue. The new
diagnostics are intended to resolve that uncertainty on recurrence. The
new wire sequences are scripted adversarial sequences, not a recording
of the incident.

## Verification

- Before the fix: turn-end integration reproduction had 1 pass / 3
failures (unconsumed steer with ACK before/after completion, overlapping
child-report wake-up). Both new adapter tests failed on the original
implementation: the prompt mapped to `wake-2`, and a rejected input
incorrectly acquired a provider turn.
- After the fix: one final `TMPDIR=/var/tmp bun run check:tmp`
invocation ran 83 tests across 10 files sequentially:
prompt-after-turn-end, Codex turn-boundaries and recorded mapping,
models-steer, steer-attachments, background-task-notes,
agent-bus-notify, queue-dispatch, worker-restart, durable-threads. All
passed; nothing remained in the private temp directory. Assertions
inspect the harness's actual input and echoed answer, delivered/queued
snapshot states, retry idempotence, restart recovery, structured
logging, late-event identity and background output.
- Passed `bun install --frozen-lockfile`, `bun run typecheck`, `bun run
lint`, `bun run format` and `bun run format:check`. Self-review
completed.
- Rebased cleanly onto latest `dev` (the intervening change affects
navigation), then repeated typecheck, lint, format check and the two new
regression files on the final head: 8 passed.
- Full unfiltered tests, the web build, browser/E2E and live inference
were not run under the task's resource/verification limits. No contract
changes required `gen:check`. No UI tests were added.

Copy audit (§8): no new or changed user-facing strings. Existing
acceptance, steered and queue-reason text is reused; only the gateway
state transition changed.

History inspection found these assumptions in the original
steering/adapter implementations; neither #393 nor #502 introduced them.
Those PRs are context only.

Related: #393
Related: #502
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant