Repository navigation
fix: stop exhausted finalization jobs replaying after silent worker loss - #24175
Merged
Merged
Conversation
Failure-Class: FC-durable-terminal-projection
Remove the new preflight, recovery and lock-release deadlines. Let exhausted jobs without a valid owner binding reach the shared job-only terminal write, and cover malformed bindings without conversation or attention writes. Failure-Class: FC-durable-terminal-projection
Git-on-my-level
added a commit
that referenced
this pull request
Oct 31, 2026
… 5xx re-escalation, WQ31) (#24194) ## Summary Firestore read lever config — guard flag-off: 7 levers 100 -> 0 (`singleton_loops`, `usage_month_cache`, `backfill_task_reads`, `historical_scan_memo`, `ledger_purge_coalesce`, `queue_age_sample_budget`, `usage_month_total`). Complete 20-key literal, delta vs main only in those 7 keys; `finjob_candidate_queries` stays 5 (its own gate). The `usage_month_total` Cloud Run-only override in `prod.overlay.yaml` goes 100 -> 0 with this flag-off — umt is itself guard-flagged; #23739 (4f7e485) set the precedent of flagging umt to 0 and removing the wanted-line CR term while keeping `FSR_USAGE_MONTH_TOTAL_EPOCH` recorded. Reason: backend-sync 5xx guard re-escalation fired per the armed WQ30 plan. verify graded the flagged levers UNSAFE on 5 consecutive ticks (17Z-21Z 2026-10-31: rate 0.0035-0.0036, 1550-1600 err/h excl audio-merge, vs ref 0.0014). The 17:15Z run disposed the first raise as exogenous (route attribution: /v2/sync-jobs/run + audio-merge retry noise under 2x WoW traffic) and armed re-escalation: "flag off next run if verify still FAIL post-fix-serve with 2h train-quiet tail, or on any lever-specific why". The lead's fix train (14d7e31 carrying #24161, #24164, #24175) went live 15:18Z on backend / backend-sync / backend-integration (lead bus post); no train since (5h+ quiet tail); verify still FAILs with a FLAT rate and unchanged error counts. No lever-specific why (finjob at 5% carries the same service-scope why). Per the runbook judgment rule, flag-off is the discriminating experiment: if the 5xx rate persists at levers 0, the cohort is exonerated (cause exogenous) and re-enables at 5%; if it drops, the cohort is implicated. ## Product invariants affected - INV-FSR-LEVERS — replace-mode literal rule respected; all 20 keys present; absent keys remain off by default; KNOWN_LEVERS unchanged. - INV-MEM-4 — required by the `backend/deploy/runtime_env.yaml` generated-manifest lock; the change is the rendered FIRESTORE_READ_LEVERS literal only. - INV-DATA-1 — lever-off restores legacy un-memoized paths (safe defaults, all previously serving pre-ramp). Failure-Class: none ## Verification - `set_levers.py` REPLACE-mode with the complete 20-key umt:0 literal (6 keys 100 -> 0 in base/charts/pins); `prod.overlay.yaml` hand-patched umt 100 -> 0 plus the same 6 keys (4 sites, set_levers does not match its inline literal form); `compose_runtime_env.py` + `render_feature_flag_registry.py` re-run. - Contract-pinned expected dict in `test_render_backend_runtime_env.py` updated per #24134/#23739 convention (6 keys 100 -> 0; the `wanted` CR-override term removed while umt is off, epoch assertion unchanged). - Diff audit: 43 changed-literal sites, every `+` side equals the new 20-key literal exactly; zero residual sites with any flagged lever > 0; `finjob_candidate_queries` = 5 everywhere. - Contract tests: `test_render_backend_runtime_env.py` 91 passed + `test_verify_pusher_config_references.py` 28 passed (lane venv). - Full CI: on this head. ## Lead-owned ship plan URGENT: deploy needed listen -> pusher -> Cloud Run (FIRESTORE_READ_LEVERS train order). Bus handoff posted to the lead; ride the next train rather than batching. <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/BasedHardware/omi/pull/24194?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="View guided diff" src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a> <a href="https://www.cubic.dev/action/auto-fix/pr/BasedHardware/omi/24194?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F24194&source=description" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"><img alt="Turn on auto-fix" src="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"></picture></a> <!-- End of auto-generated description by cubic. -->
Git-on-my-level
added a commit
that referenced
this pull request
Nov 1, 2026
…4204) Listen already owns the fleet-singleton finalization reconciliation pass, but its inline live-admission mode returned before replay. Jobs left behind by a killed worker therefore could not reach the replay attempt cap added in #24175. This change lets that existing pass use an explicitly configured worker binding independently of live admission. No new loop or callback is added. `LISTEN_FINALIZATION_REPLAY_ENABLED` defaults to true and gates only replay selection and its outcomes. The listen chart and production runtime manifest add the existing `conversation-finalization` queue, backend-sync handler, sync-tasks invoker and five-attempt setting. `LISTEN_FINALIZATION_DISPATCH_MODE` remains absent/inline on listen. Stale in-progress admission retains its original dispatch-mode check. On inline hosts, quiet-check and conversation-merge candidates are skipped without claim, dispatch or backoff writes; their existing cloud_tasks admission remains unchanged. All hosts now require syntactically valid task bindings before replay selection, including cloud_tasks hosts: project/region/queue resource components, an absolute HTTP(S) handler URL, and a service-account invoker. This is local syntax validation, not a queue/IAM/health probe. Missing, whitespace-only and malformed nonempty values fail closed. Live admission retains its existing mode-and-nonempty-presence contract; strict syntax validation is replay-only and does not tighten another listen path. BYOK reclaim and backlog publishing remain outside that switch. The deployment-setting catalog classifies the boolean as public configuration. The co-host env guard explains these five settings as prod-listen-only because pusher never starts main.py's singleton replay loop; mutation tests reject copying them to pusher and keep live admission outside the exception. Chosen host: GKE backend-listen. It already runs the Redis-coordinated startup/periodic pass; enabling only its replay stage avoids adding another scheduler. Moving this to Cloud Run would first require explaining its absent lease-attempt telemetry and proving lifecycle/CPU availability for background work. That is unresolved and unnecessary for this bounded change. Runtime prerequisites checked with GCP **ro-prod**, read-only, no user document payloads: backend-listen-runtime has unconditional project-level roles/cloudtasks.enqueuer and roles/cloudtasks.viewer, plus unconditional roles/iam.serviceAccountUser on sync-tasks-invoker. The chart uses that runtime identity without key overrides. The production runtime manifest already supplies SYNC_TASKS_PROJECT=based-hardware and SYNC_TASKS_LOCATION=us-central1 on listen. Read-only gcloud comparison of the actual backend-sync revision receiving 100% traffic (OMI_BACKEND_RELEASE_SHA=0a31a3edc88657a699c872661d5c6bffee1e9c4f) confirms the same queue, project, location, handler, invoker and maxAttempts=5 binding. Its source retains the completed-fanout short circuit. Direct queue describe is denied to ro-prod, so the lead verified it read-only using prod-operator (bus attestation 0e4532): RUNNING in us-central1, maxBurstSize=100, maxConcurrentDispatches=16, maxDispatchesPerSecond=500; maxAttempts=5, minBackoff=0.1s, maxBackoff=3600s, maxDoublings=16. No IAM change is needed or proposed; no queue/IAM writes were attempted. Burst and cost: 264 nonterminal jobs in the incident snapshot is not a replay count. At 23:42Z, Firestore aggregation queries returned 132 queued/leased, 20 due replay entries, zero entries overdue by 300 seconds, and one leased job created over 30 hours earlier. The replay cursor already exists. The first pass selects only reconcile_after_at <= the frozen cursor cutoff, after the saved boundary; without reading that cursor or job payloads the exact selected/requeued count is not established. At that snapshot the page upper bound was 20, not 132 or 264; actual deployment-time counts must be refreshed. Existing default page limit is 100, raised to 500 only when the oldest due entry is >=300 seconds overdue, with LISTEN_FINALIZATION_RECONCILE_LIMIT clamped to 1..2000. The attested queue separately caps execution at 16 concurrent tasks and dispatch at 500/s with a 100-token burst. Future quiet windows and missing reconcile_after_at fields are excluded by the indexed query; selected quiet/merge entries are skipped on inline listen without mutation. The old job's actual eligibility remains unproven from aggregates. Lead ruling 80042b explicitly requires counts only, skipping counts that need new indexes, and accepts shipping with the page bound; the lead will read actual outcomes at rollout. Each successful platform-key replay uses the existing transactional claim to mint one generation and enqueue one named task containing routing data only. A successful small task is one create plus one delivery, approximately $0.0000008 in Cloud Tasks list-price operations after the free tier; retries add delivery operations ([Google pricing](https://cloud.google.com/tasks/pricing)). This excludes Firestore reads/writes, Cloud Run execution and any unfinished derived-output provider work; those depend on the job and cannot be priced per redispatch from aggregate evidence. Replay itself does no STT/LLM work. Exhausted jobs retire before enqueue. The existing worker cap still bounds silent-loss attempts. Transport failure is bounded independently of the worker-attempt cap. Each minted replay generation records the accepted lease epoch and a counter; any accepted lease advances the epoch and resets that counter on subsequent replay. After five replay generations without an accepted lease, the next due claim deletes only reconcile_after_at and stamps replay_dispatch_suspended_at. It counts dispatch_exhausted once, leaves the job nonterminal, preserves its current generation and any already accepted task, and changes no conversation content or worker-attempt budget. A delayed current task can still claim, restore its lease marker, and resume normal recovery. This operational hold requires investigation if no task can reach a worker; it is neither completion nor dead-letter. It bounds repeated failed enqueue and pre-claim HTTP failure even when worker_claim_count stays zero. The existing worker-loss cap still uses the shared dead-letter semantics. The five new generations mean at most five extra accepted tasks per gap between leases; five successful create+single-delivery pairs are about $0.000004 in paid Cloud Tasks operations, excluding API retries, delivery retries and other services. With the attested five-delivery-attempt queue policy, those five tasks can have up to 25 delivery attempts. The original admission task predates and is outside this replay counter. No new query, index, repair write or selection widening is introduced. Safety: real replay claim logic first rejects active leases and fresh queued dispatches, respects sync-revision waiting, and keeps BYOK ownership. Only an expired platform-key obligation reaches the existing `max(attempt_count, worker_claim_count - 1) >= max_attempts` cap: with maxAttempts=5, six accepted worker claims that die without reporting failure exhaust the conservative silent-loss budget. Replay and enqueue failure do not themselves consume worker claims. A live lease's ownership, expiry, generation and worker budget are unchanged; existing scan backoff may advance only reconcile_after_at/updated_at. Committed fanout cannot dead-letter or execute its effects again: the existing worker completes the job using its lease fence and the fanout CAS returns completed. Terminal, revision, deletion and cutover fences remain unchanged. Dead-lettering uses #24175's shared mark_finalization_dead_letter semantics: transcript, audio references, photos and committed effects are retained; only existing terminal/retry/title metadata changes. This lane has made no production data writes. Kill switch: set LISTEN_FINALIZATION_REPLAY_ENABLED=false in prod listen chart values and matching runtime_env/prod.overlay.yaml, regenerate runtime_env.yaml/feature registry, and have the lead roll listen. Re-enable with true. It restores listen's previous replay-off behavior while retaining BYOK reclaim and metrics; it does not cancel already dispatched tasks. The flag is registered as an ops_kill switch. Deploy target/order: lead merges, then a backend-listen image+Helm rollout with this binding and flag together. The backend-sync worker/queue binding already exists; no Cloud Run, pusher, flag cohort or queue change is required. FIRESTORE_READ_LEVERS is unchanged, so the AVO runbook's mandatory listen -> pusher -> Cloud Run -> desktop order for lever changes does not apply. If bundled with such a lever change, preserve that train order. Live proof after rollout: verify serving listener release SHA/digest and successful singleton lease admissions. Growth in listen_finalization_replay_outcomes_total{outcome="skipped"} proves stage entry but may consist entirely of excluded quiet/merge entries; an ordinary-job claim/disposition canary requires requeued or retired growth on backend-listen-metrics. Check errors and enqueue_failed separately; dispatch_exhausted means a nonterminal transport hold needing lead investigation, not a recovered conversation. Confirm a fresh summary timestamp and oldest nonterminal age converging only for eligible jobs; inspect aggregate page counts if INFO is ingested. An unchanged oldest age is not by itself failure when its job lacks a due marker or still has a live lease. Quiet/merge recovery ownership remains unchanged and outside this fix. No deployment or production acceptance is claimed by this PR. Validation at final source: **710 targeted backend/test.sh tests across twelve files**, through omi-heavy + nice -n 19, TZ=UTC, BACKEND_PYTEST_WORKERS=1. The exact CI hermetic API harness passed **180 tests with 3 existing skips**. The frozen d60a1d4 runtime passed the full listen/pusher gauntlet, **13/13 emulator concurrency cases**, real hold/index-deletion and delayed-claim/reset emulator contracts, and **355 default offline pre-deploy checks** (the broader earlier P2 offline selection passed 530). Final 41692cf differs from d60 only by one explicit valid-binding setup line in a unit test; all runtime, deployment and harness inputs are byte-identical, independently verified with Git. The expanded shard includes that quiet-wake file (62 passed). Repository all-checks preflight is enforced again by the final push hook. Intermediate 5638623 CI exposed two fixture assumptions: the API lifecycle test used a non-service-account invoker, and quiet reconciliation tests mocked dispatch mode without the new valid-binding seam. Completed CI logs match both local failures. The API fixture now uses a GCP-shaped synthetic invoker and the quiet tests declare their infrastructure seam. The follow-up also preserves the original live-admission mode/presence contract: strict syntax validation applies to replay only, with two explicit malformed-nonempty compatibility cases. No new skips, runtime gate relaxation, guard/threshold change or blind CI retry. Final-head CI and lead round2 delta acceptance remain required; PR stays held. Strict transaction cases cover dead-worker requeue then shared dead-letter, live leases, committed fanout, repeated failed enqueue/pre-claim delivery, one-shot hold counting, delayed task claim/reset, missing/malformed replay binding and kill switch in both modes, unchanged inline stale admission, and quiet/merge exclusion. Prior4f00084c9aa reached terminal CLEAN CI after one lead-authorized unchanged wall-budget retry (733s exceeded720s despite all tests passing; runtime-identical predecessor525s); that history is not final-head CI acceptance. Failure-Class: FC-durable-terminal-projection Product invariant: INV-CUTOVER-1. Existing replay account-deletion/cutover and generation fences are retained; no admission flag or enforcement default changes. Product invariants affected: INV-MEM-4. The runtime-env change adds only the replay worker binding and switch; it does not change memory storage, retrieval, privacy fences or projection authority. Lead owns review acceptance, merge and production deployment. Grok review not required by lane brief. No workflow changes, notifications, firmware changes, audio deletion, production writes or IAM changes. Line-Count-Exception: backend/database/conversation_finalization_jobs.py | 3108 -> 3138 | Keep the bounded transport counter and hold inside the existing lease-fenced replay transaction so its guards and due-marker write remain atomic; extracting that transaction would broaden this release-safety change.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
A worker killed after its lease commits can leave the durable failure count frozen. Reconciliation then mints new Cloud Tasks generations indefinitely, resetting each task's retry header.
This change checks
max(attempt_count, worker_claim_count - 1) >= max_attemptstransactionally on stale platform-key replay, before minting another generation. Exhausted jobs use the shared dead-letter write and post-commit effects, with the closed codedurable_attempts_exhausted. Healthy replays do not increment worker claims. Live leases, fresh dispatches, BYOK ownership, committed fanout, account deletion/cutover and conversation revision fences remain respected. The existing durable-attempt-cap kill switch controls both paths.Worker preflight, error recovery and lock release retain their existing waiting behavior. Replay exhaustion bounds repeated silent worker loss through the durable claim budget, without charging healthy reads for executor queue delay. An exhausted job with a missing, empty or non-string account binding uses the shared writer to close the job without a conversation write.
Dead-lettering keeps the transcript, audio references, photos and existing structured output. It closes the bound row as visible/completed, adds only the existing terminal/minimum-title/retry metadata, and stops automatic derived-output/integration attempts for that job. It does not undo already committed effects.
The production wait's exact cause is still unproven. Both sites are direct document reads, and the same job read already succeeds before claim. The pinned SDK has 60-second GetDocument retry/timeout defaults, but the shared executor queue has no application deadline. Cutover IO occurs only when enforcement is on. These facts allow executor starvation or RPC/worker failures; they do not establish a row-specific cause or prove a request ran for the entire lease.
Validation of the narrowed diff:
BACKEND_PYTEST_WORKERS=1 BACKEND_UNIT_TEST_FILE_LIST=/Volumes/Ephemeral/scratch/ladderfix/targeted-tests.txt bash backend/test.sh, throughomi-heavy run -- nice -n 19: 481 passed across six files. The strict-Firestore replay file has 27 passing cases, including eight regressions for missing, empty and non-string owner or conversation bindings. They prove job terminality, unchanged generation, no conversation/attention write and no subsequent replay. Timeout-specific tests were removed with the deadlines.npm run test:listen-pusher-stack:emulator -- --state-dir /Volumes/Ephemeral/scratch/ladderfix2/listen-e2e, through the same wrapper: full hermetic gauntlet passed, then 13/13 emulator concurrency tests passed.OMI_PR_BODY_FILE=/Volumes/Ephemeral/scratch/ladderfix2/pr-body.md make preflight, withBACKEND_PYTEST_WORKERS=1through the same wrapper: 38/38 checks passed. These are local synthetic checks; no production runtime outcome is claimed.Why a shared primitive: replay and worker terminality call the same transaction write, preserving attention items, terminal projection, minimum title and retry eligibility; they also share the post-commit metrics/index effects.
Failure-Class: FC-durable-terminal-projection
Product invariant: INV-CUTOVER-1. Replay checks account-deletion and account-cutover admission inside its terminal transaction; the cutover enforcement flag retains its existing default and behavior.
Lead owns final review acceptance, merge and production deployment. Backend/backend-listen train required; no production access or writes performed by this lane. No workflows or runtime flag values changed.
Line-Count-Exception: backend/database/conversation_finalization_jobs.py | 3014 -> 3108 | Share the existing terminal transaction and retain account admission fences on exhausted replay; transaction guards remain adjacent to the owning state machine.
Line-Count-Exception: backend/services/conversation_finalization.py | 673 -> 688 | Reuse one post-commit dead-letter effect path for worker and replay outcomes.