Skip to content

fix: retry OMP main wakes that never enter a model turn - #337

Merged
dnth merged 6 commits into
mainfrom
fm/fm-primary-wake-stall-fix
Nov 27, 2026
Merged

dnth merged 6 commits into
mainfrom
fm/fm-primary-wake-stall-fix

Conversation

@dnth

@dnth dnth commented Nov 27, 2026 •

Copy link
Copy Markdown
Owner

Summary

The OMP primary watch core suppressed every main-bound close behind an open episode whose one hand-off had been recorded as consumed at before_agent_start but never entered a model turn. On 27 Nov 2026 that held 34 close notifications for 90 minutes. This adds a fourth bypass keyed on model entry instead of consumption.

 mainFallbackHandOff: SentWake { wakeId, close, sentAtMs, consumed, enteredAtMs }

 notifyWake(tracked)     -> handOff = sent; enteredAtMs = null
 wakeEnteredTurn(id)     -> enteredAtMs = now    // only when id === handOff.wakeId
 deliverMainWake
   staleInFlight         // accepted, unconsumed past bound
   decisionBypass        // needs-decision wake
   idleEpisode           // terminal agent_end, no turn since
+  unenteredBound        // consumed, never entered, past bound
                          -> sendWake(followUp, triggerTurn: true)
                          -> ledger: consumed by=unentered-bound (original wake id and close)

FM_WATCH_MAIN_WAKE_INFLIGHT_BOUND_MS (default 120000) paces both wall-clock retries, driven by the next main-bound close, never a timer. The ordinary send shape is unchanged: deliverAs: "nextTurn".

The CI step also repaired two unrelated test fixtures that flaked under the 9-way serial shard load (details under Evidence). Both repairs are test-only: tests/fm-remote-secondmate-lifecycle-e2e.test.sh and tests/fm-pi-watch-extension.test.sh.

Evidence

AC1 - regression fails at base, passes at target (test_native_omp_unentered_handoff_forces_turn_after_bound): a check close is sent while main streams, before_agent_start consumes it 2 ms later, its message_start never fires, only a non-terminal agent_end follows, then a later close arrives past the bound.

base 078d185d, fix core replaced with the pre-fix file:
  Error: timeout waiting for forced follow-up after the unentered bound
  not ok - OMP unentered hand-off bound: expected exit 0, got 1

target (test unchanged since 281d3024; the CI commits touch no test in this file):
  ok - OMP forces a turn for a consumed hand-off that never entered its model turn

Commands: env -u FM_TASK_ID bash tests/fm-omp-primary.test.sh with the test file at the PR head (the env var is unset only because this worker runs inside an fm-spawn task session). Logs: data/fm-primary-wake-stall-fix/artifacts/{prefix-test-failure,postfix-test-pass}.log.

AC2 - one forced send per interval, entry keeps suppression, ledger names the bypass. The same test asserts the forced followUp+triggerTurn send, that a close landing inside the renewed bound is suppressed behind=episode (not by the old in-flight guard), that a late message_start from the older delivery does not credit the newer hand-off, and that after the latest hand-off enters its own turn the next close stays behind=episode. Ledger rows assert the original wake= and close= tokens with no extra fields:

consumed  wake=<stranded wake id>  close=<stranded close>  by=unentered-bound  after_ms=...

AC3 - knock-rate replay of the live ledger (read-only, state/extensions/omp-primary-watch/main-wake-deliveries.log; bound 120000 ms, no live override in .env or config/):

Ledger window (UTC) Episode suppressions Forced sends this rule would make
24 Nov 05:44 to 27 Nov 09:44 228 3
Candidate Hand-off age Verdict Evidence
26 Nov 14:18:36 187.6 s legitimate busy wait 37 messages, 17 assistant, in the 120 s before it; last entry 14:18:34
27 Nov 06:40:05 386.7 s stranded (the incident) no messages in the 120 s before it; last entry 06:34:36, next model activity 08:03:49
27 Nov 08:23:34 168.7 s legitimate busy wait 5 messages, 2 assistant, in the 120 s before it; last entry 08:23:32

So 2 of 3 forced sends would have landed on a legitimate busy wait (a knock: an extra turn-forcing follow-up while main was already streaming) and 1 would have caught the actual stall at 06:40, two minutes after the stranded hand-off, instead of 90. The estimate is bounded, not certain: a model message inside the bound interval is evidence of an active run, not proof that the staged wake would have entered it. Replay scripts: data/fm-primary-wake-stall-fix/artifacts/knock-rate-replay.py and busy-wait-evidence.py.

AC4 - send shape and existing tests. deliverMainWake still calls sendWake with the caller's forceTurn; only the new bypass sets it for ordinary closes. bash tests/fm-omp-primary.test.sh on the PR head: all native tests pass, exit 0 (the optional SDK silent-wake check skips without FM_OMP_PACKAGE_DIR). CI on head dcd76055: 20 of 20 checks pass. bin/fm-lint.sh and bin/fm-doc-audience-check.sh pass.

CI flake repairs, both confirmed by a local green run at the repaired head before CI confirmed them:

  • tests/fm-remote-secondmate-lifecycle-e2e.test.sh: the fake SSH incremented a shared ssh.count file with cat plus printf, so two concurrent calls produced 1\n1 and a bash arithmetic error that contaminated an otherwise valid alive response. It now appends to an ambiguous-attempt log and asserts exactly one attempt through wc -l. Full file: exit 0 locally, 700 s.
  • tests/fm-pi-watch-extension.test.sh: two OpenCode fixture arms raced the 250 ms ready timer before their TERM trap was installed, so the retirement signal could kill the fixture and leave no retired marker. They now print an explicit failure line after installing the trap. The ready-timeout path still runs in test_opencode_hung_successor_falls_back_to_typed_wake. Full file: exit 0 locally, 22 s.

Review findings

Pipeline review round 1 raised six findings; firstmate directed a fix round and approved the result. Disposition at head dcd76055:

Finding Disposition Evidence
latest-handoff-entry-identity (error) fixed entry is per delivery: SentWake.enteredAtMs (bin/fm-primary-watch-core.ts:124), only set when the delivery id matches the tracked hand-off (:1832), and the bound reads it off that record (:1063); the test exercises a late entry by the older wake
retirement-ledger-close-correlation fixed retirement uses the stranded wake's own wake and close, with no stranded_close/reason (bin/fm-primary-watch-core.ts:1141)
premature-bound-reset fixed retirement no longer moves the clock; notifyWake sets the hand-off at the accepted attempt (bin/fm-primary-watch-core.ts:878)
unrequired-episode-mirror-fields fixed the two mirror fields are gone from persistEpisodeState; the guide no longer claims them
unrequired-successor-ledger-doc-change fixed the stray next is removed from the mid-turn ledger example
renewed-bound-regression-coverage (auto-fix) fixed the test now consumes the forced hand-off without entering it and asserts the third close is suppressed behind=episode inside the renewed bound

Remaining, accepted by firstmate on 27 Nov 2026 as bounded costs rather than stalls:

  • rejected-send-masks-accepted-entry: a rejected send leaves a never-delivered wake in the hand-off slot, so a late cleanup retry can force one extra turn and skip a retirement line.
  • same-millisecond-turn-masks-expired-inflight: a turn_start in the exact millisecond of a send counts as post-send evidence, so the in-flight marker can outlive its bound and the new bypass stays excluded while it is set.

Merge Danger

Door: two-way. Reverting restores the previous suppression behavior; no data or queue format changes.

Blast Radius: one. Only the OMP primary watcher's main-fallback delivery changes, and only after a new session loads the extension. Worst case is an extra turn-forcing follow-up per two minutes while a hand-off is stranded; durable queue rows are untouched, and waiting/fleet work in this home is unaffected until the next session start.

Pipeline

Updates from git push no-mistakes

✅ **Intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

⚠️ **Review** - 6 issues (1 error, 5 warnings)
  • 🚨 bin/fm-primary-watch-core.ts:1859 - AC2 requires the bound to use entry evidence for the "last hand-off." Line 1859 instead stamps every watcher message_start before resolving its delivery ID. If OMP stages wake A, the bound forces wake B, and A enters late after B is sent, A's entry satisfies B's timestamp check. Once turn_start clears B's in-flight marker, B can fail to enter and the next close past B's bound is still suppressed behind the episode. This is reachable when staged wakes overlap during a long OMP run. Bind entry and retirement to the tracked delivery ID at bin/fm-primary-watch-core.ts:930–931 (send reset), :1083–1086 (entry predicate), and :1092 (retirement lookup). Exercise the late older entry with real delivery metadata at tests/fm-omp-primary.test.sh:2880–2884 and :2937. The current behavior also contradicts the guide's own-message guarantee at docs/omp-supervision-branch.md:79 and :130–131.
  • ⚠️ bin/fm-primary-watch-core.ts:1097 - Every model-entry bypass writes the retired wake's ID and elapsed time alongside the newer triggering close's token and reason. An operator following the documented lookup by close at docs/omp-supervision-branch.md:85 and :89 sees a consumption event for the triggering close before its send. The intent only requires recording the stranded hand-off's retirement. Use its original token in the existing close field and remove the added stranded_close and triggering reason fields at bin/fm-primary-watch-core.ts:1098 and :1101, along with their inputs at :1140. The assertion at tests/fm-omp-primary.test.sh:2921 checks the label without checking this correlation.
  • ⚠️ bin/fm-primary-watch-core.ts:1093 - The retirement helper advances the hand-off clock before the replacement is sent, even though sendWake establishes that clock at bin/fm-primary-watch-core.ts:930–931. If a staged watcher failure notice opened the episode without a readable queue baseline, a later close can reach retirement and then return at :1164–1168 without sending anything. That close spends another bound interval despite no new hand-off. The intent requires pacing actual send attempts. Remove the extra clock reset from retirement and let sendWake establish the next interval.
  • ⚠️ bin/fm-primary-watch-core.ts:662 - The new episode-mirror timestamps add a diagnostic representation beyond the required retirement ledger. On an ordinary wake entry, the adapter acknowledges first and bin/fm-primary-watch-core.ts:1859 updates the entry timestamp afterward without persisting it. An operator reading the mirror during that model call can therefore see zero until the next boundary. Remove both added mirror fields at :662–663 and the corresponding claim at docs/omp-supervision-branch.md:81. The existing sent and turn ledger events already carry the timing.
  • ⚠️ tests/fm-omp-primary.test.sh:2925 - The within-interval assertion leaves the forced hand-off in flight, so the old in-flight guard suppresses the third close even if someone deletes the new age comparison at bin/fm-primary-watch-core.ts:1082. This gap occurs on every run of the fixture and leaves AC2's pacing guarantee unproved for the incident path. Stage and consume the forced hand-off without entering it, then assert that the identified third close is suppressed behind the episode before the renewed deadline. The verification claim at docs/verification/runtime-backends.md:817 should match that observable contract.
  • ⚠️ docs/verification/runtime-backends.md:805 - The added next in the unrelated mid-turn ledger example makes the documented event sequence wrong for every successor trace. The existing executable oracle at tests/fm-omp-primary.test.sh:3737 expects granted,sent:successor. No wake-stall requirement needs this change. Remove the added word so operators can match the example to the ledger.

🔧 Fix applied.
6 issues (1 error, 5 warnings) still open:

  • 🚨 bin/fm-primary-watch-core.ts:1859 - AC2 requires the bound to use entry evidence for the "last hand-off." Line 1859 instead stamps every watcher message_start before resolving its delivery ID. If OMP stages wake A, the bound forces wake B, and A enters late after B is sent, A's entry satisfies B's timestamp check. Once turn_start clears B's in-flight marker, B can fail to enter and the next close past B's bound is still suppressed behind the episode. This is reachable when staged wakes overlap during a long OMP run. Bind entry and retirement to the tracked delivery ID at bin/fm-primary-watch-core.ts:930–931 (send reset), :1083–1086 (entry predicate), and :1092 (retirement lookup). Exercise the late older entry with real delivery metadata at tests/fm-omp-primary.test.sh:2880–2884 and :2937. The current behavior also contradicts the guide's own-message guarantee at docs/omp-supervision-branch.md:79 and :130–131.
  • ⚠️ bin/fm-primary-watch-core.ts:1097 - Every model-entry bypass writes the retired wake's ID and elapsed time alongside the newer triggering close's token and reason. An operator following the documented lookup by close at docs/omp-supervision-branch.md:85 and :89 sees a consumption event for the triggering close before its send. The intent only requires recording the stranded hand-off's retirement. Use its original token in the existing close field and remove the added stranded_close and triggering reason fields at bin/fm-primary-watch-core.ts:1098 and :1101, along with their inputs at :1140. The assertion at tests/fm-omp-primary.test.sh:2921 checks the label without checking this correlation.
  • ⚠️ bin/fm-primary-watch-core.ts:1093 - The retirement helper advances the hand-off clock before the replacement is sent, even though sendWake establishes that clock at bin/fm-primary-watch-core.ts:930–931. If a staged watcher failure notice opened the episode without a readable queue baseline, a later close can reach retirement and then return at :1164–1168 without sending anything. That close spends another bound interval despite no new hand-off. The intent requires pacing actual send attempts. Remove the extra clock reset from retirement and let sendWake establish the next interval.
  • ⚠️ bin/fm-primary-watch-core.ts:662 - The new episode-mirror timestamps add a diagnostic representation beyond the required retirement ledger. On an ordinary wake entry, the adapter acknowledges first and bin/fm-primary-watch-core.ts:1859 updates the entry timestamp afterward without persisting it. An operator reading the mirror during that model call can therefore see zero until the next boundary. Remove both added mirror fields at :662–663 and the corresponding claim at docs/omp-supervision-branch.md:81. The existing sent and turn ledger events already carry the timing.
  • ⚠️ bin/fm-primary-watch-core.ts:881 - AC2 says, “A hand-off that did enter a turn keeps today's suppression.” Round 1 assigns the new hand-off before OMP accepts it at bin/fm-primary-watch-core.ts:880–882, but the rejection paths at :889–894 and :936–943 leave that rejected delivery in the hand-off slot. If OMP rejects a decision-owned send while an earlier wake is in its handling turn, and the existing cleanup retry at :1234–1239 runs after the configured bound, :1073–1077 and :1105–1106 force the retry based on a delivery that never happened. The ledger also omits the required retirement at :1152–1156 because that rejected delivery was never consumed. This requires a send rejection and a retry or later close that reaches the bound before another send is accepted. Remove rejected sends from model-entry eligibility at the shared send boundary, preserving the previous accepted delivery and the pacing of actual attempts. The accepted-send fixture at tests/fm-omp-primary.test.sh:2858–2861 cannot catch this path.
  • ⚠️ bin/fm-primary-watch-core.ts:1075 - AC2 requires an expired open episode whose last hand-off “has no entered-turn evidence” to force a send. Round 1 left a sibling gap at bin/fm-primary-watch-core.ts:1075, which excludes every in-flight hand-off. If OMP starts a model call just before the watcher sends, both events can receive the same millisecond timestamp at :878 and :1925. If OMP queues that wake without emitting another consumption or turn event, :1059 treats the earlier call as post-send evidence indefinitely, :1075 prevents the new bypass, and every later ordinary close takes the suppression branch at :1114–1122. This is rare and requires a same-millisecond send during a run that leaves the marker outstanding. At the shared bound check, keep unrelated turn timing from exempting an outstanding delivery without entry evidence, and keep the ledger reason tied to the actual retirement path. The guarantee at docs/omp-supervision-branch.md:130–131 and the fixture at tests/fm-omp-primary.test.sh:2920–2930 cover the consumed case only.
✅ **Test** - passed

✅ No issues found.

  • Live validation: ✅ go - 4 of 4 scenarios driven live against the product
Scenario Result Live Evidence
A registered check fires while local OMP streams a synthetic reply. The ordinary wake uses nextTurn, and the next close after the bound forces followUp with triggerTurn after the first wake is staged… ✅ pass live Live OMP base stall reproduction and Live OMP target trace and delivery ledger, closes A and B
A registered check fires again inside the renewed interval after the forced wake is consumed. Local OMP receives no additional wake. ✅ pass live Live OMP target trace and delivery ledger, closes B and C
An older wake enters late in the local OMP session. The newer unentered wake still expires and the following check forces delivery. ✅ pass live Live OMP target trace and delivery ledger, late entry for A and forced close D
The latest forced wake enters its own local OMP model call. A registered check after the bound stays coalesced while that synthetic call is still streaming. ✅ pass live Live OMP target trace and delivery ledger, native message_start for D, loopback request 3, and suppressed close E
  • test_native_omp_unentered_handoff_forces_turn_after_bound against separately exported base 078d185d and target 62655fb5, with the generated ledger captured for each
  • bash tests/fm-omp-primary.test.sh in an isolated home, exit 0. The optional SDK silent-wake check skipped because FM_OMP_PACKAGE_DIR was unset.
  • omp --mode rpc --no-ui on both revisions with a disposable Firstmate home, a loopback streaming provider, and a watcher check registered via bin/fm-check-register.sh wake-probe. Captured native send options, lifecycle events, the delivery ledger, and the durable queue. Both OMP processes exited 0.
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

dnth added 6 commits November 27, 2026 17:44
- A main-bound close consumed by before_agent_start but never entering its own
  model turn, followed by a non-terminal agent_end, leaves the episode open with
  no escape hatch and suppresses every later close.
- The new test fails today at the forced-follow-up wait: the core logs
  suppressed behind=episode instead of forcing a turn past the bound.
A staged hidden next-turn send raises before_agent_start immediately, which the
core recorded as consumption and used to clear the in-flight marker. When no
message_start for the wake and no terminal agent_end followed, the episode
stayed open with every escape hatch disarmed and suppressed all 34 later
main-bound closes for 90 minutes on 27 Nov.

- Record the last tracked main hand-off time and the last observed model entry
  (the wake's own custom message_start) per generation.
- Add a fourth deliverMainWake bypass: an open episode whose hand-off is older
  than FM_WATCH_MAIN_WAKE_INFLIGHT_BOUND_MS with no entered-turn evidence forces
  the existing followUp+triggerTurn send, one per interval like the in-flight
  bound.
- Ledger the retirement as consumed by=unentered-bound with the stranded close.

The ordinary send shape is unchanged (deliverAs nextTurn).
@dnth
dnth merged commit 8b9673b into main Nov 27, 2026
21 checks passed
@dnth
dnth deleted the fm/fm-primary-wake-stall-fix branch November 27, 2026 11:27
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