Repository navigation
fix(bin): unblock exits, rotate mates, and detect quota stalls - #8370
taimurrabuske wants to merge 17 commits into
Conversation
…d quota circuit breaker
…inal quota guards
…AGY idle detection
[Medium impact] The PR changes worker lifecycle and recovery across the configured Firstmate home. The PR still needs fixes for legacy tasks stopping the watcher and fresh-session relaunches blocking Herdr recovery. Reviews (4) · Last reviewed commit: "no-mistakes: apply CI fixes" · Reviewed by Greptile |
| breaker_gen=$(printf '%s\n' "$sweep_line" | sed -n 's/.*\[quota-breaker-epoch=[0-9][0-9]* generation=\([^]]*\)\].*/\1/p') | ||
| breaker_payload=$(printf '%s\n' "${sweep_line#quota-breaker }" | sed 's/ \[quota-breaker-epoch=[0-9][0-9]* generation=[^]]*\]$//') | ||
| fm_wake_append check quota-breaker "check: quota-breaker: $breaker_payload" || exit 1 | ||
| [ -n "$breaker_id" ] && [ -n "$breaker_class" ] && [ -n "$breaker_epoch" ] && [ -n "$breaker_gen" ] || exit 1 |
There was a problem hiding this comment.
A stalled legacy task without spawn_gen makes the watcher exit here. The breaker accepts the missing field and emits generation=, but this check requires a nonempty value after saving the wake. The watcher exits before acknowledging the pending report or running the remaining checks. Every replacement watcher repeats the failure.
Handle legacy records before publishing, or allow their empty generation consistently through acknowledgement.
| herdr_state=$(fm_backend_herdr_pane_agent_state "$FM_BACKEND_HERDR_SESSION" "$FM_BACKEND_HERDR_PANE" 2>/dev/null) \ | ||
| || herdr_state=unknown | ||
| case "$herdr_state" in | ||
| no-agent|dead) return 0 ;; | ||
| live|stale-agent) ;; | ||
| *) die "task $ID's herdr agent registration could not be verified for --fresh-session; refusing before stopping anything" ;; |
There was a problem hiding this comment.
Fresh relaunch blocks Herdr recovery
relaunch --fresh-session now refuses a Pi task when its Herdr server is stopped. fm_backend_herdr_pane_agent_state returns unknown, so this gate exits before the existing recovery path can restart the recorded server and check the restored pane. Ordinary relaunch already supports this case.
Use the existing absence recheck first, then inspect any restored registration before deciding whether it is unreadable.
|
Speaking as Kun's firstmate: thank you @taimurrabuske. I read the full diff against latest Three things are waiting on you:
Please resolve each thread once it's fixed or answered. After that, I'll look at queueing the full suite. The "Full suite" check without the label isn't something you need to act on. contract-class: new-default. Rotation and the breaker are opt-in, but three parts change every home's unconfigured path. VISION: One captain aligns (stalls become firstmate wakes, not captain noise) · Authority mixed (rotation and breaker are explicit grants; exit/agy/preflight change defaults) · Scripts aligns · Restart does not align until P1 #1 is fixed · Delegation aligns in purpose, P1 #2 open · Vendor aligns (agy re-verified on 1.5.6) · Scope cannot tell (three features in one PR). |
Intent
have we unbloated and sped up task execution in FM?
let's fix the 3
one-time publish!
Context: a throughput audit found three Firstmate-side problems:
The captain granted one-time upstream contribution consent for this task: github.com/kunchenguid/firstmate.
What Changed
Risk Assessment
Testing
Validated control settling, AGY lifecycle behavior, quota preflight and breaker wakes, mate rotation, and end-to-end restart/rotate flows; all targeted checks passed with reviewer-visible logs captured.
Evidence: Control lifecycle tests
Source: Control lifecycle tests
Evidence: AGY harness tests
Source: AGY harness tests
Evidence: Quota breaker tests
Source: Quota breaker tests
Evidence: Quota preflight tests
Source: Quota preflight tests
Evidence: Secondmate rotation tests
Source: Secondmate rotation tests
Evidence: Secondmate restart end-to-end tests
Source: Secondmate restart end-to-end tests
Evidence: Spawn quota preflight end-to-end evidence
Source: Spawn quota preflight end-to-end evidence
Pipeline
Updates from git push no-mistakes
✅ **intent** - passed
✅ No issues found.
✅ **Rebase** - passed
✅ No issues found.
bin/fm-control.sh:774- Anunknownbusy verdict is treated as settled for agy. If agy'sesc to cancelmarker has scrolled out during a live turn, the classifier returns unknown; this path then sends Ctrl+U and/quitinto the still-running turn. Require a provenidleverdict before clearing an unknown composer; keep unknown as unresolved and refuse or continue polling.bin/fm-quota-breaker.sh:86- The breaker counts Z.AI 1302 errors across the entire captured tail, while other hard signatures use the bottom 15 rows and the contract says stale refusals must not trip it. Four old errors plus one current error can falsely trigger a relaunch of a recovered worker. Count rate-limit refusals within the same recent bottom window.bin/fm-quota-preflight.sh:64- Provider lookup never examines the top-levelcrew-dispatch.json.default; it only evaluates.defaultfields nested inside each rule. A valid default profile such as Pi withprovider: zaitherefore has no provider resolved, and Pi has no single-provider fallback, so an exhausted candidate receives no preflight notice. Include top-level default profiles in the lookup.🔧 Fix: Hardened agy settling and corrected quota detection
1 error still open:
bin/fm-control.sh:1240---fresh-sessionaccepts any absolute Herdr session reference as archivable, thenarchive_fresh_sessionsilently succeeds when the path is missing and moves directories as if they were session files. A deleted or malformed reference therefore stops the old agent instead of refusing before the stop, contradicting the fail-closed fresh-session contract. Require a readable regular file during preflight and do not silently skip it during archiving.🔧 Fix: Validated fresh-session references before relaunch stopping
2 warnings still open:
bin/fm-secondmate-rotate.sh:232- Rotation launch failures are ignored: the detached child can fail before exec, yet the script records the rotation and reports it started. An invalid restart command can therefore suppress retries for the full window while no restart occurred. Propagate launch failure or record/report it distinctly.bin/fm-quota-preflight.sh:64- Preflight selects the first profile matching only harness and model across all rules/defaults, while spawn supplies no selected provider or quota scope. Valid profiles can share those fields but differ by effort, rule, provider, or scope, causing false exhausted notices or missed warnings and potentially wrong same-group failover. Use the actual dispatch profile's provider and scope.🔧 Fix: Hardened rotation launches and disambiguated quota preflight
3 issues (1 error, 2 warnings) still open:
bin/fm-control.sh:776- The agy settle path treats every non-busy verdict, includingunknown, as settled. An ambiguous agy pane therefore receives Ctrl+U, is coerced tocleared, and then/quitis submitted despite no idle proof. Require anidle*verdict before clearing.bin/fm-control.sh:558- Because agy now declaresC-uas its composer clear key,send_interrupt_keyssends it immediately after Escape, beforesettle_composerproves the turn is idle. This can modify the composer while cancellation is still in progress; defer agy's clear until the idle-settled path.bin/fm-quota-preflight.sh:83- An ambiguous profile lookup is followed by a harness-family fallback, so the helper can guess after finding multiple provider/scope pairs. For example, two valid claude profiles with the same harness/model/effort but providers claude and zai leave the lookup empty, then resolve to claude and may emit a false exhaustion notice. Preserve unresolved ambiguity and only use the family fallback when no conflicting profiles match.🔧 Fix: Preserved ambiguity in quota provider resolution
2 warnings still open:
bin/fm-quota-breaker.sh:123- The breaker scans metadata and residual pane text without verifying the endpoint is still alive. A worker that exits after printing a 1308/1310 error can leave that text visible, causing a later sweep to emit a quota-breaker wake and potentially relaunch an already-dead or completed task. This conflicts with the required behavior of detecting hard refusals “in a live worker”; check agent liveness before classifying.bin/fm-quota-preflight.sh:107- Preflight joins schema-6 quota rows using only quota_lane(harness, model), while fm-spawn invokes it before resolving the selected worker account. Claude therefore falls back to the default account, and account-pinned Pi/Claude launches cannot reliably inspect the account they will actually use; an exhausted selected account can be missed or the wrong account can produce a false warning. This undermines the required “quota pre-flight before spawn ... when a candidate is exhausted_now” behavior; pass the resolved account identity or run preflight after account selection.🔧 Fix: Scoped quota checks to live workers and selected accounts
3 warnings still open:
bin/fm-secondmate-rotate.sh:233- Rotation checks only the cached busy record, not endpoint liveness. A dead or shell-only mate with a staleidlerecord and an oversized transcript can be queued for persist/restart, violating the live-idle guard and potentially sending the persist request to a non-agent endpoint. Requirefm_backend_agent_stateto bealivebefore classifying or launching rotation.bin/fm-secondmate-rotate.sh:164- Herdr session references may be bare IDs, butpi_bound_sessionrejects non-absolute references and then falls back to the newest transcript. If multiple sessions exist, rotation can measure the wrong conversation and rotate too early or fail to rotate a bloated mate. Resolve the bound ID to its exact transcript or remainunmeasuredrather than guessing.bin/fm-quota-breaker.sh:130- The terminal-task guard examines onlytail -n 1, not the last non-empty status line. A terminal status followed by a blank line therefore bypasses the guard; residual quota text can then produce a breaker wake for a completed or failed task. Filter blank lines before matching terminal states.🔧 Fix: Hardened live rotation, bound sessions, and terminal quota guards
2 warnings still open:
bin/fm-quota-breaker.sh:138- The breaker treatsunverifiedas live, butfm_backend_agent_statedefines it as having no recovery-grade liveness classifier. A dead shell with residual quota text can therefore trigger a false relaunch wake. Requirealiveor a backend-specific positive liveness proof.bin/fm-secondmate-rotate.sh:164- A single filename match returns before checking other transcripts whose first JSON line may carry the same bound session ID. Withchat_<ref>.jsonlplus another file declaringid=<ref>, rotation measures an ambiguous session instead of remaining unmeasured. Combine both match sources before requiring uniqueness.🔧 Fix: Require verified liveness and reject ambiguous bound sessions
5 warnings still open:
bin/fm-secondmate-rotate.sh:190- Rotation derives Pi and Claude transcript roots only from the parent environment, not the mate's configured account pin. A per-secondmate account can therefore be measured as unmeasured or against another account's newest session, causing missed or incorrect rotations. Resolve the mate's effective account root using the shared account selector before locating transcripts.bin/fm-spawn.sh:3588- When a quota-breaker selects a different candidate and relaunches it, spawn still passes the original dispatch record's provider and quota scope to preflight. The preflight can consequently report the old candidate's exhaustion or miss the replacement candidate's exhaustion. Derive provider/scope from the actual relaunch profile instead of unconditionally using the stale dispatch record.bin/fm-quota-preflight.sh:64- A configured Claude account ofordinaryintentionally launches with CLAUDE_CONFIG_DIR unset, but preflight converts it to$HOME/.claudeand then invokes quota-axi with that environment at line 112. This can inspect a different Claude profile/keychain identity than the worker being launched. Preserve the ordinary-account unset semantics.bin/fm-secondmate-rotate.sh:266- The rotation-window check and record write are not atomic. Two concurrent scans can both observe an elapsed window, both launch--rotate, and issue duplicate persist/relaunch operations despite the documented at-most-once-per-window invariant. Claim a per-mate lock or atomic marker before launching.bin/fm-quota-breaker.sh:148- Breaker deduplication is also a read-then-write sequence without locking. Concurrent scans can both report the same class and incarnation, producing duplicate wake notifications within the realert window. Serialize or atomically claim the per-task breaker record before emitting the report.🔧 Fix: Scoped accounts and serialized rotation and quota recovery
2 issues (1 error, 1 warning) still open:
bin/fm-spawn.sh:3588- The preflight tries to read provider/quota_scope from dispatch-resolution.json, but that record stores only harness/model/effort. When two profiles share harness/model with different providers, preflight resolves the candidate as ambiguous and stays silent, so an exhausted selected candidate launches without the required quota warning. Persist the selected provider and quota_scope or pass them from the authoritative dispatch result. This contradicts the required “quota pre-flight before spawn (using quota-axi when a candidate is exhausted_now)” criterion.bin/fm-busy-lib.sh:1018- AGY is classified idle when any of its last 12 nonblank lines contains? for shortcuts, without proving that the text is the actual status footer. A worker outputting that phrase can therefore be treated as idle, allowing exit clearing/quit or session rotation during an active turn. Anchor the match to the verified footer position/shape and otherwise retainunknown.🔧 Fix: Warned on ambiguous quota profiles and anchored AGY idle detection
2 issues (1 error, 1 warning) still open:
bin/fm-quota-breaker.sh:172- The quota-breaker wake contains only task/class/harness/model; it carries no matched rule/default group, and dispatch-resolution.json persists only the selected profile. Therefore the firstmate cannot reliably enforce the required “next same-group candidate ... never crossing groups” after a wake, especially after context loss. Persist or propagate the authoritative group identity before relying on this relaunch path.bin/fm-quota-breaker.sh:143- The breaker emits whenever a merely alive worker has a matching refusal anywhere in the bottom 15 rows. A worker can recover and continue working while the old error remains in that window, causing a false quota wake and potentially an unnecessary relaunch. Require current stalled/idle evidence or validate that no active turn followed the refusal before reporting.🔧 Fix: Added brief-aware quota wakes and stale-refusal suppression
2 warnings still open:
bin/fm-quota-breaker.sh:180- The scan captures a refusal before reading the worker's spawn generation. If the worker is relaunched between capture and lines 188-194, the old pane output is recorded against the new generation and wakes firstmate to relaunch a healthy replacement. Re-read and compare the incarnation before publishing the breaker record.bin/fm-secondmate-rotate.sh:206- For a Herdr Pi mate, any failed or unreadable session-registration lookup returns 1 and falls back to the newest transcript. With multiple sessions, an unrelated high-token transcript can trigger rotation of the live mate, while the fresh-session path likewise cannot archive the bound session. Treat unreadable Herdr identity as unmeasured rather than selecting an arbitrary newest session.🔧 Fix: Guarded breaker generation races and unreadable Herdr sessions
1 warning still open:
bin/fm-quota-breaker.sh:202- The final generation check is not serialized with spawn publication. A relaunch can update the metadata after line 202 but before lines 217-228, causing a stale refusal captured from the old incarnation to be recorded and emitted against a healthy replacement. Hold the shared task metadata lock across the generation check and record publication, as fm-spawn.sh does.🔧 **Test** - 1 issue found → auto-fixed ✅
tests/fm-secondmate-restart.test.sh:794- The restart suite aborts in T13 because its fixture does not produce the result directory within the 2-second polling window, so the full suite never reaches --rotate. The --rotate scenario passes through the same public interface when run directly.bash tests/fm-control.test.shbash tests/fm-control-relaunch.test.shbash tests/fm-agy-harness.test.shbash tests/fm-secondmate-rotate.test.shbash tests/fm-quota-preflight.test.shbash tests/fm-quota-breaker.test.shbash tests/fm-secondmate-restart.test.shFocused --rotate execution through the public restart interface🔧 Fix: Synchronize restart fixture before removing unpublished result
✅ Re-checked - no issues remain.
bash tests/fm-control.test.shbash tests/fm-agy-harness.test.shbash tests/fm-quota-breaker.test.shbash tests/fm-quota-preflight.test.shbash tests/fm-secondmate-rotate.test.shbash tests/fm-secondmate-restart.test.shFixture-drivenfm-spawn.shlaunch with an exhausted Z.AI snapshot, confirming the advisory preflight notice and persisted profile.✅ **Document** - passed
✅ No issues found.
✅ **Lint** - passed
✅ No issues found.
✅ **Push** - passed
✅ No issues found.