Repository navigation
fix: enable finalization replay independently of listen admission - #24204
Conversation
Arm the existing listen singleton replay pass with its own kill switch and worker binding while retaining inline live and stale-conversation admission. Exercise silent worker loss, active leases, committed fanout and rollback.
Render the registry after the Helm mirror and use a scalar flag declaration so the documented production value is true rather than an inline map.
Keep the new public boolean in the deployment secret-boundary catalog.
Pusher consumes finalizations but does not run the main.py reconciliation loop. Permit only the five new replay settings on prod listen and reject copying those declarations to pusher or widening the exception to admission.
Only ordinary finalization jobs may bypass the cloud_tasks dispatch-mode gate on listen. Quiet checks and merge jobs retain their existing ownership and are skipped without claim, dispatch or backoff writes on inline hosts.
Use equality-based kind exclusion so an unhashable legacy value cannot abort the replay page before the existing claim fences handle its job.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
All reported issues were addressed across 13 files
Reply with feedback, questions, or to request a fix.
View guided diff | Turn on auto-fix | Re-trigger cubic
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 726f9dac23
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
Update the owning listen/pusher lifecycle guide with the worker binding, ordinary-job scope, quiet/merge exclusions, attempt and page fences, rollout and replay-only rollback. Clarify the generated flag catalog's default and disable behavior and keep the test's lifecycle import at module scope.
Require valid task bindings before replay in every admission mode. Hold after five replay generations without lease progress, preserving the latest task generation and conversation while counting transport exhaustion once. Accepted leases restore recovery; worker-loss exhaustion keeps the existing shared dead-letter transition. Cover real transactions and emulator deletion. Failure-Class: FC-durable-terminal-projection
Preserve the existing admission mode and presence contract while requiring valid static bindings for replay in every mode. Cover malformed nonempty binding compatibility and use a valid synthetic service account in the API lifecycle fixture. Document the replay-only validation boundary. Failure-Class: FC-durable-terminal-projection
The quiet-wake cases isolate dispatch from infrastructure. Supply the new binding seam explicitly so they continue to exercise quiet outcomes, while the real binding tests retain fail-closed coverage in every mode.
|
Review handoff at Accepted nonblocking limits:
Final read-only aggregate refresh at 02:30:25Z: 420 queued/leased jobs, 157 due entries, 12 at least 300 seconds overdue. At that snapshot, the due-page upper bound was 157; the aged default page is 500 unless explicitly overridden. Exact selection/requeues after cursor, kind and ownership fences remain unknown, and deployment-time counts can change. The old job's specific status remains unproven: the refreshed aggregate still shows one leased job created over 30 hours ago and zero queued jobs that old. This does not establish that current lease's age, record identity, due marker, cursor position, eligibility or disposition. Missing markers remain unselected and future markers wait. This PR does not widen selection or repair that record; the lead owns the separate decision. |
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_ENABLEDdefaults to true and gates only replay selection and its outcomes. The listen chart and production runtime manifest add the existingconversation-finalizationqueue, backend-sync handler, sync-tasks invoker and five-attempt setting.LISTEN_FINALIZATION_DISPATCH_MODEremains 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). 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_attemptscap: 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.