Skip to content

fix(batch,sync): explicit backlog state machine with owners, deadlines and attempt budgets - #24893

Closed
Git-on-my-level wants to merge 19 commits into
mainfrom
lane/backlog-state-machine
Closed

Git-on-my-level wants to merge 19 commits into
mainfrom
lane/backlog-state-machine

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Nov 8, 2026 •

Copy link
Copy Markdown
Member

Requested by David

Product invariants affected

none

Failure class (fixes)

Failure-Class: FC-state-deadline-without-reader-exit

Every automatically entered batch and sync backlog state must have a deadline, a counter and an exit its readers consume. Five places broke that. Each fix below has a fake-clock test that walks the whole ladder down to its terminal state.

Why

The 2026-11-07 backlog root-cause review (four independent lanes; workspace data/run-2026-11-07-backlog-hypotheses/aggregate.md) found that backlogs recur because several state machines hand off to each other and no state owns its exit:

  • the retry cap only observed outside the CAPTURE_COVERAGE_MODE serve cohort;
  • a running sync lease expiry reset dispatch_attempt to 0;
  • a held/dead-letter re-drive kept attempt at the cap, so the first failure re-quarantined it;
  • nightly re-drive and projection re-arm had no terminal stop;
  • a record_pending row whose conversation exists but never finishes retried forever.

Change

Owner, deadline, counter and exit for each state: backend/docs/runbooks/backlog-state-machine.md. Six bug classes, one commit each (class 6 is split into its counter and its terminal stop), each behind its own kill switch in config/policy/kill_switches.py and config/feature-flags.yaml. Switches are parsed literally: true is on, anything else is off, and unset means the default below. They are read per decision and never re-read through the capture-coverage serve-mode parser. Defaults follow lead2's rule (64b2fa): ON only where a class just cuts wasted work or retries, OFF where it changes custody, settle or expiry semantics. No production default is flipped by this PR beyond these code defaults.

Class User-facing symptom Kill switch Default Risk
1. Retry cap only observed A unit that crashes its worker retries forever and its recording never gets a transcript; the backlog grows CAPTURE_RETRY_CAP_ENFORCED OFF Enforcing quarantines rows (batch) or fails sync jobs: a custody change. Alert omi-backlog-retry-cap-quarantine-rate
2. Sync lease expiry reset the attempt budget A sync upload whose worker keeps crashing is redriven without bound; the uid's lane stays blocked SYNC_DISPATCH_ATTEMPT_CARRY_ENABLED ON Low: only stops the reset and counts crashes. Finalizing at the cap also needs class 1 on. Alert omi-backlog-sync-running-cap-rate
3. Requeue kept attempt at the cap A re-driven held recording fails again on its first error and goes straight back to held BATCH_HELD_REDRIVE_BUDGET_ENABLED OFF A fresh budget moves held rows back into processing: a custody change. Alert omi-backlog-held-exhausted-rate
4. record_pending with a never-finished conversation The recording sits in processing for weeks; drain re-reads it every hour RECORD_PENDING_BARRIER_DEAD_LETTER_ENABLED OFF Parking stops admission retries: a custody change. Alert omi-backlog-record-dead-letter-rate
5. Unrestorable assignment holds had no deadline A held result whose target conversation stays discarded never projects, and nothing flags it BATCH_ASSIGNMENT_HOLD_ESCALATION_ENABLED OFF Writes a deadline and an escalation marker only (see disagreements). Alert omi-backlog-assignment-hold-escalated
6a. Nightly re-drive loop not counted Held recordings loop nightly with no visible count BATCH_HELD_REDRIVE_COUNTER_ENABLED ON Low: counting and an alert only, no state change. Alert omi-backlog-held-redrive-budget-spent
6b. Nightly re-drive had no terminal stop The same held recordings are re-driven forever BATCH_HELD_REDRIVE_TERMINAL_STOP_ENABLED OFF Parks a unit as retained held_exhausted and stops poll re-drive and projection re-arm: a state change. Alert omi-backlog-held-exhausted-rate

Five switches became seven: the shared class 3/6 switch is split into the class 3 budget reset, the class 6 counter and the class 6 terminal stop.

Ramp plans for the OFF classes

The switches are process env, so cohorts are deployments. Order for every OFF class (1, 3, 4, 5, 6b): dev, then backend-integration, then one prod service, then all prod. Owner: backlog-refactor thread. Dates: to be set by lead2.

Class Clean metric before each step
1 omi_capture_retry_cap_total{outcome="quarantine"} tracks the prior would_quarantine rate, with no rise in sync partial_failure and no runnable unit quarantined (sample held reasons)
3 Re-driven held units reach committed more often than they re-quarantine (omi_batch_held_expired_total and requeue counts), with no rise in worker failures
4 record_barrier_dead_letter rate stable, and no parked row whose conversation later completed (sampled barrier_dead_letter rows)
5 assignment_hold_escalated rate bounded by the unrestorable assignment-hold stock, and restored targets still release
6b held_exhausted transitions match the held_redrive_budget_spent observations from the counter, with no growth in operator requeue backlog
  1. Retry cap enforcement where failure is proven (class 1, when switched on).
    • Batch: a lease expiry at BATCH_PIPELINE_MAX_ATTEMPTS (5) now quarantines (retained held, worker_failed). Explicit worker failures already took this transition.
    • Sync: a running owner whose running_expiries reaches SYNC_TASKS_MAX_ATTEMPTS is finalized by the existing fenced finalizer. running_expiries counts the times the job began and its lease expired with no run lock.
    • Deliberately unchanged: the sync dispatching-state cap stays on the CAPTURE_COVERAGE_MODE cohort. A passed dispatch retry deadline is queue delay, not failure. test_delivery_after_running_lease_survives_repeated_dispatch_redrives models a queue with no delivery for 2 h, and enforcing that count would fail the job (FC-queued-delivery-invalidated-by-redrive).
  2. Sync attempt budget survives lease expiry. redrive_job keeps the epoch bump that fences the dead worker, but carries dispatch_attempt, and counts running_expiries (reset when the next job is claimed). The reconciler, which already owns the fenced terminal handoff, now also caps a running owner on lease_expired. redrive_job itself still never refuses a running owner, so a terminal or missing job cannot strand it. Budget-deferral chains keep the reset, because budget_chain_exhausted owns them.
  3. Requeue grants a fresh budget. requeue_quarantined_in_transaction sets attempt=0 and records held_redrive_last_attempt and held_redrives.
  4. record_pending exit (class 4, default OFF). The admission pre-check raises RecordBarrierOpen, a ValueError with the same message plus the conversation it read. With the switch on, after 14 days a row whose conversation exists and is not completed re-drives weekly with barrier_redrives. After 4 re-drives it parks as a retained dead letter (barrier_dead_letter, rechecked daily without admission, still state=record_pending). Missing conversations keep fix(batch): add proof-gated exits for aged record-pending jobs #24703's seven-day cancel, and completed ones keep seal repair. Operator exit: requeue_barrier_dead_letter.
  5. C7 settled by fixture, then given a deadline. test_assignment_held_releases_automatically_only_when_target_restorable shows a restorable assignment hold releases automatically through the release scan's assignment leg. An unrestorable one (projection_state=persisted) never expires, because it still owes multipart follow-ups. It now gets assignment_hold_deadline_at (7 days) and then a retained escalation marker (assignment_hold_escalated_at, reason target_unrestorable). Nothing else changes, and a later restored target still releases it.
  6. Re-drive counter (6a, default on) and terminal stop (6b, default off). The counter counts held_redrives and held_expired_rearms and reports spent budgets. With the stop on, after held_redrives >= 3, nightly re-drive writes dead_letter_reason=held_exhausted: retained, not selected again, still requeueable by an operator through the OIDC requeue-quarantined path. held_exhausted counts as a retained dead letter in upload status and projection hold checks. Projection expiry re-arms are counted in held_expired_rearms and stop after 3.

Review wave 1: five blocking findings (fixed in ea462ae8ebe)

Every new test below was written first and run against the previous head 673c8e2fcb6. The pre-fix run had 8 failures and 3 passing controls; each finding had at least one failure.

# Finding Fix Test Failed before the fix?
1 Status poll (durable_status → redrive_in_transaction) redrove held_expired/held_exhausted, bypassing held_redrives and the attempt reset redrive_in_transaction(automatic=True) from the poll skips retained held dead letters; plain dead rows and operator redrive-dead unchanged test_client_poll_never_redrives_a_retained_held_dead_letter[held_expired, held_exhausted] (control: test_client_poll_still_redrives_a_plain_historical_dead_row) Yes, both cases: job went back to ready
2 Any budget deferral turned off crash accounting, so a lane could redrive forever running_expiries counts every crashed running lease, budget-deferred or not; an expiry while deferred_until is live is not a crash test_budget_deferred_owner_that_keeps_crashing_reaches_a_terminal_outcome (replaces the bare dispatch_attempt == 0 test); control test_expiry_during_a_live_budget_deferral_is_not_counted_as_a_crash Yes: lease_expired repeated, never terminal
3 Exhausted receipts unrecoverable after rollback With the class 6 stop off (BATCH_HELD_REDRIVE_TERMINAL_STOP_ENABLED=false, the default), a receipt marked held_rearm_exhausted_at regains the legacy re-arm test_rearm_exhausted_receipt_releases_after_budget_switch_off_and_target_restored (control: …_stays_spent_while_budget_switch_on) Yes: release() returned False
4 Parking wrote available_at ~10 years out; switch off stranded parked rows Parked rows are due daily: re-parked without admission while on, returned to the barrier ladder when off; existing due query, no new query shape test_parked_row_returns_to_the_ladder_after_the_switch_is_turned_off, test_parked_row_is_rechecked_without_admission_while_the_switch_is_on Yes, both: row was parked ~10 years out
5 Unrestorable persisted assignment holds had no deadline 7-day assignment_hold_deadline_at, then a retained assignment_hold_escalated_at marker; new kill switch BATCH_ASSIGNMENT_HOLD_ESCALATION_ENABLED, metric transition, alert omi-backlog-assignment-hold-escalated; a restored target still releases test_unrestorable_assignment_hold_escalates_after_its_deadline_and_keeps_its_obligation (control: test_assignment_hold_escalation_kill_switch_writes_nothing) Yes: no deadline field

Two existing projection tests that asserted an unrestorable persisted hold is byte-identical now expect exactly the new deadline stamp and nothing else. origin/main was merged into the branch in f59263ec588 (33 commits, including #24889). That merge regenerated the flag-registry doc and the monitoring exports; no code conflicts.

No transition deletes audio, results, custody tokens or privacy fences. New transitions are counted in omi_backlog_state_transitions_total{transition}, after commit only.

Tests

backend/tests/unit/test_backlog_state_machine.py has one or more tests per bug class, each also proving its kill switch restores the old transition:

Class Test
1 test_retry_cap_enforced_by_default_on_lease_expiry, test_retry_cap_serves_without_capture_coverage_cohort
Review 1 test_client_poll_never_redrives_a_retained_held_dead_letter, test_client_poll_still_redrives_a_plain_historical_dead_row
Review 2 test_budget_deferred_owner_that_keeps_crashing_reaches_a_terminal_outcome, test_expiry_during_a_live_budget_deferral_is_not_counted_as_a_crash
Review 3 test_rearm_exhausted_receipt_releases_after_budget_switch_off_and_target_restored, test_rearm_exhausted_receipt_stays_spent_while_budget_switch_on
Review 4 test_parked_row_returns_to_the_ladder_after_the_switch_is_turned_off, test_parked_row_is_rechecked_without_admission_while_the_switch_is_on
Review 5 test_unrestorable_assignment_hold_escalates_after_its_deadline_and_keeps_its_obligation, test_assignment_hold_escalation_kill_switch_writes_nothing
2 test_running_lease_expiry_keeps_the_attempt_budget, test_delayed_queue_dispatch_retries_are_not_terminalized_by_default, test_running_lease_expiry_at_the_cap_terminalizes_instead_of_redriving, test_running_owner_at_cap_with_terminal_job_is_not_stranded, test_running_cap_kill_switch_restores_unbounded_redrive
3 test_requeue_grants_a_fresh_attempt_budget, test_requeued_unit_survives_one_lease_expiry_with_a_fresh_budget
4 test_unfinished_conversation_redrives_weekly_then_dead_letters, test_parked_row_returns_to_the_ladder_after_the_switch_is_turned_off, test_parked_row_is_rechecked_without_admission_while_the_switch_is_on, test_record_dead_letter_kill_switch_keeps_the_hourly_ladder (false and unset), test_other_barrier_cohorts_keep_their_existing_owner, test_admission_precheck_reports_the_conversation_it_read
5 (C7) test_assignment_held_releases_automatically_only_when_target_restorable
6 test_automatic_redrive_stops_after_max_and_operator_can_still_requeue, test_malformed_redrive_counter_counts_as_spent, test_held_budget_switch_off_keeps_legacy_unbounded_nightly_redrive, test_nightly_tick_counts_exhausted_separately, test_projection_rearm_counts_and_stops_after_max

Existing legacy-behavior tests (test_capture_retry_hygiene.py, test_batch_held_dead_letter.py, and two in test_batch_pipeline_scheduler.py) now pin the rollback switch they describe; the enforcing default has its own tests (including test_enforced_cap_quarantines_at_cap_lease_expiry).

Local verification on m5-mbp (unit layer only), rebased on 2b237ab85be, one pytest process per file:

  • Final full run: 16 files, 784 passed, 0 failed. Files: test_backlog_state_machine (30), test_sync_backfill_uid_sequencer (132), test_batch_pipeline_scheduler (62), test_batch_pipeline_live (96), test_batch_pipeline_projection_release (85), test_batch_pipeline_admission (50), test_batch_pipeline_intake (45), test_batch_held_dead_letter (42), test_batch_projection_held_dead_letter (26), test_capture_retry_hygiene (18), test_sync_worker_execution (19), test_record_drain_barrier_backoff (14), and the alert contracts (test_monitoring_alert_rule_contract 75, test_monitoring_alert_backtest 28, test_monitoring_gmp_shadow 35, test_provision_monitoring_alerts 27).
  • Earlier targeted run: 75 files that touch the changed behavior, 72 passed. The three failures were addressed:
    • Two scheduler tests asserted the old non-enforcing cap. They now pin the rollback switch.
    • A sequencer test modelling a backlogged queue exposed a real hazard. That is why the dispatching-state cap stays cohort-gated.
    • An admission deadline test failed on timing at host load ~70. The same file passed (50/50) on rerun.
  • Not run locally: the full 2,690-file selector set (left to CI), and the Firestore-emulator integration tests (tests/integration/test_batch_pipeline_firestore.py, test_held_custody_conformance.py, test_recovery_*_conformance.py, test_batch_held_dead_letter_firestore.py). Not live-verified.

Merge of main (option C)

origin/main was merged in merge commits e938c7fb2b6 (brings #24884, 920bb5be) and 91669fdd52b (second merge). Conflict files resolved: backend/utils/batch_pipeline/live.py, backend/database/batch_pipeline_projection_release.py and backend/utils/batch_pipeline/held_dead_letter.py (in favor of this branch, with main's paths kept), plus backend/charts/monitoring/alert-rules.json, backend/charts/monitoring/gmp-query-migration-inventory.json, backend/docs/feature-flag-registry.md and config/feature-flags.yaml (additive, both sides kept).

origin/main is merged with a merge commit (no rebase, no squash). It brings #24884 (920bb5be: record barrier dead letter, assignment-hold expiry via _expire_assignment).

Conflicts resolved:

  • utils/batch_pipeline/live.py (in favor of this branch): main's record_barrier_aged dead letter stays. Class 4 owns present-but-unfinished rows only while RECORD_PENDING_BARRIER_DEAD_LETTER_ENABLED is on, and main's dead letter is skipped just for those rows.
  • database/batch_pipeline_projection_release.py (in favor of this branch): main's _expire_assignment is kept, with the class 6 counter and stop inside it.
  • utils/batch_pipeline/held_dead_letter.py: both imports kept.
  • Generated files (both sides kept, regenerated from sources): alert-rules.json, gmp-query-migration-inventory.json, feature-flag-registry.md.

BATCH_PIPELINE_PROJECTION_GHOST_SETTLE_ENABLED is unchanged (main's code default, False).

A second merge (91669fdd52b) brought main forward again. Its only conflict was config/feature-flags.yaml, which is additive, so both sides were kept: this branch's seven switches and main's BATCH_PIPELINE_PROJECTION_GHOST_SETTLE_WAKE_ENABLED.

Not caused by this PR: tests/unit/test_batch_pipeline_startup.py::test_load_pyannote_pair_missing_deps fails on origin/main itself. The test expects "requires the GPU image", but diarizer/batch_pipeline_startup.py:61 raises "requires the model runtime". This PR touches neither file.

With every new switch off, main's paths are byte-identical. tests/unit/test_backlog_main_paths_switches_off.py covers this:

  • test_main_record_dead_letter_runs_unchanged_with_class_4_off (false and unset)
  • test_class_4_on_owns_present_unfinished_rows_and_skips_main_dead_letter
  • test_class_4_on_leaves_main_dead_letter_for_rows_it_does_not_own (missing conversation, completed conversation, plain recheck refusal)
  • test_main_assignment_expiry_writes_exactly_mains_markers_with_switches_off (with and without the re-arm)
  • test_counter_on_adds_only_the_rearm_count_to_mains_expiry
  • test_stop_on_keeps_an_exhausted_receipts_budget_spent_on_mains_path
  • test_persisted_hold_never_expires_and_escalates_only_with_class_5_on

A mutation that never lets class 4 own a row fails test_class_4_on_owns_present_unfinished_rows_and_skips_main_dead_letter.

Rollout and verification after deploy

Deploying this PR serves only classes 2 and 6a (default on). Watch omi-backlog-sync-running-cap-rate (fires only if class 1 is also on) and omi-backlog-held-redrive-budget-spent for one day. The OFF classes ship dark and follow the ramp plans above. Rollback for any switch: set it to false, which is read per decision (no restart or migration). Fields written while a switch was on are inert when it is off.

For review: where my reading differs from the ruling

  • Class 4 overlap: main's own record dead letter (920bb5be) parks aged barrier rows as dead/record_barrier_aged under BATCH_HELD_DEAD_LETTER_ENABLED, which defaults on. The ruling classes parking as a custody change, default OFF. With class 4 off (default), main's path runs unchanged. I did not change main's default; lead2 to decide.
  • Class 5: the ruling's reason for OFF is "automatic release is a settle change". This switch does not release anything. It only stamps assignment_hold_deadline_at and the retained escalation marker (backend/database/batch_pipeline_projection_release.py, the persisted-unrestorable branch at ~L257). Automatic release of restorable holds is the pre-existing release-scan assignment leg (release_scan_pass, ~L523, gated by BATCH_PIPELINE_PROJECTION_HOLD_RECOVERY_ENABLED) and is unchanged here. I kept it OFF as ruled.
  • Class 2: agree it is ON. Its only terminal effect, finalizing a running job at the cap, also requires class 1 (running_cap reads CAPTURE_RETRY_CAP_ENFORCED, backend/utils/sync/retry_hygiene.py ~L51). With class 1 off the carried count is observed only (test_running_cap_only_observes_while_class_1_is_off).
  • Class 6: split cleanly. The counter and its alert are ON (6a), and the stop is its own OFF switch (6b), so the whole class did not need to be OFF.

🤖 Generated with Claude Code

Git-on-my-level and others added 2 commits November 8, 2026 05:45
…s and attempt budgets

Every non-terminal batch and sync backlog state now has one owner, one
deadline and one counter, and every automatic loop has a retained terminal
stop. Four safety kill switches (on unless set off) restore each old
transition:

- CAPTURE_RETRY_CAP_ENFORCED: retry caps end work for every uid instead
  of only the CAPTURE_COVERAGE_MODE serve cohort.
- SYNC_DISPATCH_ATTEMPT_CARRY_ENABLED: a running sync lease expiry keeps
  counting dispatch_attempt; the reconciler finalizes at the cap.
- BATCH_HELD_REDRIVE_BUDGET_ENABLED: held/dead-letter requeue grants a
  fresh attempt budget and counts re-drives; automatic re-drive stops at
  3 (dead/held_exhausted, operator-requeueable); projection expiry
  re-arms stop at 3.
- RECORD_PENDING_BARRIER_DEAD_LETTER_ENABLED: record_pending rows whose
  conversation exists but never completed re-drive weekly after 14 days
  and park as a retained dead letter after 4 re-drives.

Nothing deletes audio, results, custody tokens or privacy fences.

Failure-Class: FC-state-deadline-without-reader-exit

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ert contracts

- Sync: the dispatching-state cap stays on the CAPTURE_COVERAGE_MODE cohort.
  A passed dispatch retry deadline is queue delay, not failure; enforcing it
  by default would fail runnable jobs behind a backlogged queue. Running
  lease expiries (the job began and died) are counted in running_expiries,
  reset at claim, and capped by default.
- held_exhausted counts as a retained dead letter in upload status and
  projection hold checks.
- Legacy scheduler tests pin CAPTURE_RETRY_CAP_ENFORCED=false; the
  enforcing default has its own tests.
- Alerts: shorten one UID to Grafana's 40-character limit, declare the two
  source-backed metrics, regenerate the GMP query inventory.

Failure-Class: FC-state-deadline-without-reader-exit

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Git-on-my-level Git-on-my-level self-assigned this Nov 8, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-08T12:45:30.488510Z e9fa9e1 New commits
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 673c8e2fcb

ℹ️ 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".

Comment thread backend/utils/batch_pipeline/live.py Outdated
Comment on lines +677 to +678
elif step == 'dead_letter':
delay = RECORD_BARRIER_PARK_SECONDS

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Make parked records reachable when the kill switch is disabled

If an operator disables RECORD_PENDING_BARRIER_DEAD_LETTER_ENABLED after records have been parked, those records retain an available_at ten years in the future. drain_recordings() selects only due rows and its claim also checks available_at, so it never reaches the switch check for these records. Consequently, the documented rollback does not restore hourly retries for affected recordings; each requires a separate manual requeue. Provide a bounded recovery path for already-parked rows when disabling this behavior.

Useful? React with 👍 / 👎.

Comment on lines +1 to +5
# Backlog state machine (batch and sync)

Code: `config/backlog_state_machine.py`, `utils/backlog_metrics.py`.
Tests: `tests/unit/test_backlog_state_machine.py`.
Alerts: `charts/monitoring/alerts/backlog-state-machine.json`.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Add the required pipeline change note

This commit changes audio/transcription lifecycle behavior, including automatic quarantine, held-work re-drives, and permanent barrier parking, but its changed-file list contains no note under backend/docs/listen_pusher_pipeline/changes/. backend/AGENTS.md explicitly requires a note there for audio, transcription, or conversation lifecycle changes. Add a dated note covering the changed transitions, default-on switches, rollout, and verification evidence; the separate runbook does not satisfy that required location.

AGENTS.md reference: backend/AGENTS.md:L164-L164

Useful? React with 👍 / 👎.

return 'finalize_deferred'
if registry.finish_expired_job(uid, owner['active_job_id'], epoch, 'dispatch_retry_cap_reached', now=current):
if owner.get('active_state') != 'dispatching':
from utils.backlog_metrics import record_transition

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Keep the new imports at module scope

The new function-local imports violate the explicit import convention in backend/AGENTS.md: all imports must be at module scope, never inside functions. This occurs here for record_transition, in running_cap() for get_sync_tasks_max_attempts, and in the changed retained-dead-letter predicates for RETAINED_DEAD_REASONS. Move the newly added imports to module scope, restructuring shared dependencies if necessary to preserve the existing dependency closure.

AGENTS.md reference: backend/AGENTS.md:L168-L168

Useful? React with 👍 / 👎.

"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum(increase(omi_backlog_state_transitions_total{transition=\"sync_running_cap_reached\"}[30m])) or vector(0)",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Export the transition counter before alerting on sync caps

In the production sync path, this alert cannot observe the events it counts: backend/deploy/scheduler/jobs.yaml sends the sequencer sweep to backend-sync, but the keep regex in backend/deploy/cloud_run_gmp_sync.yaml rejects omi_backlog_state_transitions_total (verified against the actual regex). The in-cluster import allowlist in backend/charts/monitoring/prometheus-stackdriver-exporter/prod_sync_omi_cloud_run_metrics_exporter.yaml also omits this family. Consequently, running-cap terminalizations never reach this Prometheus query, and or vector(0) makes the missing telemetry appear healthy. Add the counter to both export stages, or use a supported telemetry source, and test the complete producer-to-alert path.

Useful? React with 👍 / 👎.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

5 issues found across 26 files

Confidence score: 3/5

  • metric-inventory.prod.json lists sync_running_cap_reached, but the exporters do not import its namespace, so this signal won't be available through the metric inventory. Add the missing exporter coverage.
  • batch_pipeline_projection.py and intake.py can raise TypeError when dead_letter_reason is a list or dict. Check that the persisted value is a string before set membership.
  • The product-tier thresholds in alert-rules.json are uncalibrated, despite the README requiring thresholds based on production distributions. Measure the production rate before setting them.
  • batch_pipeline_projection_release.py gives legacy rows with held_expired_release_attempts no credit for a prior re-arm, allowing three additional re-arms. Treat that legacy marker as at least one spent re-arm.

You’re at about 95% of the monthly reviewed-line limit. You may want to disable incremental reviews to conserve quota. Reviews will continue until that limit is exceeded. If you need help avoiding interruptions, please contact [email protected].

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="backend/charts/monitoring/metric-inventory.prod.json">

<violation number="1" location="backend/charts/monitoring/metric-inventory.prod.json:2313">
P2: This metric is never imported from the sync services that emit `sync_running_cap_reached`. The sync exporter prefix list has no `omi_backlog_` entry, and the main exporter does not cover backend-sync namespaces. Because the alert ends in `or vector(0)`, `omi-backlog-sync-running-cap-rate` will read 0 permanently and never fire. Add `'prometheus.googleapis.com/omi_backlog_state_transitions_total/'` to the sync exporter prefixes in `prod_sync_omi_cloud_run_metrics_exporter.yaml`, and check that the exporter contract test covers it.</violation>
</file>

<file name="backend/charts/monitoring/alert-rules.json">

<violation number="1" location="backend/charts/monitoring/alert-rules.json:32369">
P2: These product-tier thresholds are admittedly uncalibrated, and the README requires product-rule thresholds to come from measured production distributions. Either measure the production rate before merging, or lower the impact tier and state that the threshold is provisional. The synthetic `evaluated_bad`/`evaluated_good` notes are not production evidence.</violation>
</file>

<file name="backend/database/batch_pipeline_projection_release.py">

<violation number="1" location="backend/database/batch_pipeline_projection_release.py:117">
P2: Rows re-armed before this change have `held_expired_release_attempts` but no `held_expired_rearms`, so this returns 0 and they get three new re-arms. Treat that legacy marker as at least one spent re-arm.</violation>
</file>

<file name="backend/database/batch_pipeline_projection.py">

<violation number="1" location="backend/database/batch_pipeline_projection.py:887">
P2: `held_without_recovery` performs set membership on an unvalidated Firestore field. A list or dict `dead_letter_reason` raises `TypeError` instead of failing closed; require a string before membership.</violation>
</file>

<file name="backend/utils/batch_pipeline/intake.py">

<violation number="1" location="backend/utils/batch_pipeline/intake.py:165">
P2: `_terminally_held` performs set membership on an unvalidated persisted field. A malformed `dead_letter_reason` raises `TypeError` during intake status handling; require a string before membership.</violation>
</file>

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

"omi_audio_custody_failures_total",
"omi_audio_custody_last_risk_timestamp_seconds",
"omi_audio_custody_would_drop_total",
"omi_backlog_state_transitions_total",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: This metric is never imported from the sync services that emit sync_running_cap_reached. The sync exporter prefix list has no omi_backlog_ entry, and the main exporter does not cover backend-sync namespaces. Because the alert ends in or vector(0), omi-backlog-sync-running-cap-rate will read 0 permanently and never fire. Add 'prometheus.googleapis.com/omi_backlog_state_transitions_total/' to the sync exporter prefixes in prod_sync_omi_cloud_run_metrics_exporter.yaml, and check that the exporter contract test covers it.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/charts/monitoring/metric-inventory.prod.json, line 2313:

<comment>This metric is never imported from the sync services that emit `sync_running_cap_reached`. The sync exporter prefix list has no `omi_backlog_` entry, and the main exporter does not cover backend-sync namespaces. Because the alert ends in `or vector(0)`, `omi-backlog-sync-running-cap-rate` will read 0 permanently and never fire. Add `'prometheus.googleapis.com/omi_backlog_state_transitions_total/'` to the sync exporter prefixes in `prod_sync_omi_cloud_run_metrics_exporter.yaml`, and check that the exporter contract test covers it.</comment>

<file context>
@@ -2310,6 +2310,7 @@
     "omi_audio_custody_failures_total",
     "omi_audio_custody_last_risk_timestamp_seconds",
     "omi_audio_custody_would_drop_total",
+    "omi_backlog_state_transitions_total",
     "omi_batch_held_expired_observed_at_seconds",
     "omi_batch_held_expired_total",
</file context>

Comment thread backend/config/backlog_state_machine.py Resolved
"verification": "Read omi_backlog_state_transitions_total{transition=\"sync_running_cap_reached\"} and backend-sync-backfill worker crash and timeout logs.",
"safe_next_action": "Fix the worker crash cause first; the sync job is terminal failed and the client may re-upload. Rollback: SYNC_DISPATCH_ATTEMPT_CARRY_ENABLED=false.",
"runbook": "backend/docs/runbooks/backlog-state-machine.md",
"threshold": ">10 in 30m for 5m; initial agent threshold, not calibrated from production.",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: These product-tier thresholds are admittedly uncalibrated, and the README requires product-rule thresholds to come from measured production distributions. Either measure the production rate before merging, or lower the impact tier and state that the threshold is provisional. The synthetic evaluated_bad/evaluated_good notes are not production evidence.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/charts/monitoring/alert-rules.json, line 32369:

<comment>These product-tier thresholds are admittedly uncalibrated, and the README requires product-rule thresholds to come from measured production distributions. Either measure the production rate before merging, or lower the impact tier and state that the threshold is provisional. The synthetic `evaluated_bad`/`evaluated_good` notes are not production evidence.</comment>

<file context>
@@ -32128,5 +32128,537 @@
+      "verification": "Read omi_backlog_state_transitions_total{transition=\"sync_running_cap_reached\"} and backend-sync-backfill worker crash and timeout logs.",
+      "safe_next_action": "Fix the worker crash cause first; the sync job is terminal failed and the client may re-upload. Rollback: SYNC_DISPATCH_ATTEMPT_CARRY_ENABLED=false.",
+      "runbook": "backend/docs/runbooks/backlog-state-machine.md",
+      "threshold": ">10 in 30m for 5m; initial agent threshold, not calibrated from production.",
+      "evaluated_bad": "Synthetic: 11 running-cap terminations in 30m.",
+      "evaluated_good": "Synthetic: 10 in 30m."
</file context>

Comment thread backend/utils/batch_pipeline/intake.py Resolved
Comment thread backend/utils/batch_pipeline/live.py Resolved
Comment on lines +117 to +118
if 'held_expired_rearms' not in entry:
return 0

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Rows re-armed before this change have held_expired_release_attempts but no held_expired_rearms, so this returns 0 and they get three new re-arms. Treat that legacy marker as at least one spent re-arm.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/database/batch_pipeline_projection_release.py, line 117:

<comment>Rows re-armed before this change have `held_expired_release_attempts` but no `held_expired_rearms`, so this returns 0 and they get three new re-arms. Treat that legacy marker as at least one spent re-arm.</comment>

<file context>
@@ -110,12 +112,21 @@ def ghost_class(entry, job, binding, segment_id: str, now: float) -> str:
 
+def projection_rearms(entry: dict) -> int:
+    """Expiry re-arms already granted; malformed metadata counts as spent."""
+    if 'held_expired_rearms' not in entry:
+        return 0
+    count = entry['held_expired_rearms']
</file context>
Suggested change
if 'held_expired_rearms' not in entry:
return 0
if 'held_expired_rearms' not in entry:
return 1 if 'held_expired_release_attempts' in entry else 0

Comment thread backend/utils/batch_pipeline/live.py Resolved
retained_dead = job.get('state') == 'dead' and job.get('dead_letter_reason') == 'held_expired'
from config.backlog_state_machine import RETAINED_DEAD_REASONS

retained_dead = job.get('state') == 'dead' and job.get('dead_letter_reason') in RETAINED_DEAD_REASONS

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: held_without_recovery performs set membership on an unvalidated Firestore field. A list or dict dead_letter_reason raises TypeError instead of failing closed; require a string before membership.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/database/batch_pipeline_projection.py, line 887:

<comment>`held_without_recovery` performs set membership on an unvalidated Firestore field. A list or dict `dead_letter_reason` raises `TypeError` instead of failing closed; require a string before membership.</comment>

<file context>
@@ -882,7 +882,9 @@ def held_without_recovery(job: dict) -> bool:
-    retained_dead = job.get('state') == 'dead' and job.get('dead_letter_reason') == 'held_expired'
+    from config.backlog_state_machine import RETAINED_DEAD_REASONS
+
+    retained_dead = job.get('state') == 'dead' and job.get('dead_letter_reason') in RETAINED_DEAD_REASONS
     if (job.get('state') != 'quarantined' and not retained_dead) or job.get('result'):
         return False
</file context>
Suggested change
retained_dead = job.get('state') == 'dead' and job.get('dead_letter_reason') in RETAINED_DEAD_REASONS
reason = job.get('dead_letter_reason')
retained_dead = job.get('state') == 'dead' and isinstance(reason, str) and reason in RETAINED_DEAD_REASONS


return (job.get('state') == 'quarantined' and job.get('recovery_state') == 'failed_held') or (
job.get('state') == 'dead' and job.get('dead_letter_reason') == 'held_expired'
job.get('state') == 'dead' and job.get('dead_letter_reason') in RETAINED_DEAD_REASONS

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: _terminally_held performs set membership on an unvalidated persisted field. A malformed dead_letter_reason raises TypeError during intake status handling; require a string before membership.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/utils/batch_pipeline/intake.py, line 165:

<comment>`_terminally_held` performs set membership on an unvalidated persisted field. A malformed `dead_letter_reason` raises `TypeError` during intake status handling; require a string before membership.</comment>

<file context>
@@ -159,8 +159,10 @@ def _terminally_held(job: dict) -> bool:
+
     return (job.get('state') == 'quarantined' and job.get('recovery_state') == 'failed_held') or (
-        job.get('state') == 'dead' and job.get('dead_letter_reason') == 'held_expired'
+        job.get('state') == 'dead' and job.get('dead_letter_reason') in RETAINED_DEAD_REASONS
     )
 
</file context>
Suggested change
job.get('state') == 'dead' and job.get('dead_letter_reason') in RETAINED_DEAD_REASONS
job.get('state') == 'dead'
and isinstance(job.get('dead_letter_reason'), str)
and job.get('dead_letter_reason') in RETAINED_DEAD_REASONS

1. Status polls no longer redrive retained held dead letters
   (held_expired, held_exhausted): redrive_in_transaction(automatic=True)
   from durable_status skips them, so held_redrives and the attempt reset
   cannot be bypassed. Plain dead rows and operator redrive-dead unchanged.
2. Crashed running leases count toward running_expiries for budget-deferred
   owners too; an expiry while a deferred_until marker is live is not a
   crash. A deferring lane that keeps crashing now terminates.
3. With BATCH_HELD_REDRIVE_BUDGET_ENABLED=false, a receipt marked
   held_rearm_exhausted_at regains the legacy re-arm, so a restored target
   releases.
4. Parked record_pending dead letters come due daily instead of ~10 years
   out: re-parked without admission while the switch is on, returned to the
   barrier ladder when it is off. Uses the existing due query.
5. Unrestorable persisted assignment holds get a 7-day deadline and then a
   retained escalation marker (kill switch
   BATCH_ASSIGNMENT_HOLD_ESCALATION_ENABLED, metric, agent alert). Nothing
   is deleted; a restored target still releases.

Each fix has a test that failed on the previous head.

Failure-Class: FC-state-deadline-without-reader-exit
…chine

# Conflicts:
#	backend/docs/feature-flag-registry.md

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f59263ec58

ℹ️ 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".

Comment on lines +1021 to +1022
job.update(dead_letter_reason=HELD_EXHAUSTED_REASON, held_exhausted_at=now)
tx.put('jobs', job['segment_id'], job)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Restore nightly retries for exhausted rows when budgeting is disabled

If BATCH_HELD_REDRIVE_BUDGET_ENABLED is disabled after a unit reaches held_exhausted, the documented rollback does not restore its nightly retries. dead_held_candidates() still selects only dead_letter_reason == 'held_expired', and RecoveryStore.requeue_quarantined(..., dead_before=...) independently requires that same reason, regardless of the switch. Consequently, already-exhausted units without further client polling remain parked until individually requeued by an operator, unlike the bounded rollback recovery provided for parked recordings and exhausted projection receipts. Add a bounded recovery path that makes these feature-created rows eligible again when budgeting is disabled.

Useful? React with 👍 / 👎.

1. With BATCH_HELD_REDRIVE_BUDGET_ENABLED off, the nightly held pass pages
   units already parked as held_exhausted (same equality query shape,
   parameterized reason, own durable cursor) and the transactional fence
   accepts them, so rollback restores nightly recovery.
2. Replace the direct redrive_job rollback test with one that drives
   reconcile_uid at the running cap: switch off redrives with counters
   reset and no finalization; switch on finalizes. Checked against a
   mutation that ignores the switch.
3. A successful release clears the active assignment-hold deadline and
   escalation marker (kept in assignment_hold_escalation_history), so a
   later hold on the same unit gets a fresh deadline.

Failure-Class: FC-state-deadline-without-reader-exit
Class 1 (retry cap only observed outside the serve cohort).
CAPTURE_RETRY_CAP_ENFORCED now defaults off: enforcing quarantines rows or
fails sync jobs, a custody change (lead2 ruling 64b2fa). With it off the
batch lease-expiry and sync running caps keep the CAPTURE_COVERAGE_MODE
cohort decision; set true to enforce for every uid.

All backlog state-machine switches are now parsed literally and never
re-read through the capture-coverage serve-mode parser, which would turn an
unset default-off switch on.

Tests cover the switch on, off and unset: lease-expiry quarantine, the
cohort-free serving decision, the running cap finalizing only with class 1
on, and a table test of every switch default, explicit true/false and
serve-mode stability.

Failure-Class: FC-state-deadline-without-reader-exit
Class 2 (running sync lease expiry reset dispatch_attempt to 0).
SYNC_DISPATCH_ATTEMPT_CARRY_ENABLED stays on: it only stops the attempt
budget reset and counts crashed running leases, which cuts retries (lead2
ruling 64b2fa). Finalizing at the running cap also requires class 1
(CAPTURE_RETRY_CAP_ENFORCED, default off, read in
utils/sync/retry_hygiene.py running_cap); with class 1 off the carried count
is observed only.

Tests run the carry and the sweep with the switch explicitly true, unset
(default on) and false.

Failure-Class: FC-state-deadline-without-reader-exit
…switch (default ON)

Class 6, part 1 of 2 (counter and alert). Splits counting off the shared
BATCH_HELD_REDRIVE_BUDGET_ENABLED switch onto
BATCH_HELD_REDRIVE_COUNTER_ENABLED, default on (lead2 ruling 64b2fa: the
nightly loop counter and its alert are ON):

- every held requeue increments held_redrives;
- projection expiry re-arms increment held_expired_rearms;
- the nightly pass records held_redrive_budget_spent for units whose
  counter reached MAX_HELD_REDRIVES, with a new agent alert
  omi-backlog-held-redrive-budget-spent.

Counting only: no requeue refusal and no state change. The terminal stop
is a separate commit behind its own default-off switch.

Tests cover the counter switch true, unset and false for requeue counting,
the spent-budget observation, and projection re-arm counting crossed with
the stop switch.

Failure-Class: FC-state-deadline-without-reader-exit
Class 6, part 2 of 2 (terminal stop). Moves every state-changing part of
the re-drive stop off the shared BATCH_HELD_REDRIVE_BUDGET_ENABLED switch
onto BATCH_HELD_REDRIVE_TERMINAL_STOP_ENABLED, default off (lead2 ruling
64b2fa: the stop changes state):

- nightly re-drive parks a unit at MAX_HELD_REDRIVES as retained
  dead/held_exhausted (operator requeue still works);
- status polls skip retained held dead letters;
- projection expiry stops re-arming after MAX_PROJECTION_REARMS.

Off (default and rollback) keeps the unbounded loop, requeues units already
marked held_exhausted, and restores the legacy re-arm for receipts marked
held_rearm_exhausted_at. The stop needs the class 6 counter (default on) to
ever trigger. Alert omi-backlog-held-exhausted-rate now names this switch.

Tests cover the stop switch true, false and unset: poll redrive, nightly
exhaustion and its rollback, malformed counters, and projection re-arm
crossed with the counter.

Failure-Class: FC-state-deadline-without-reader-exit
Class 3 (requeue from held or dead-letter kept attempt at or above the cap,
so a re-drive re-quarantined on its first failure). After the class 6
split, BATCH_HELD_REDRIVE_BUDGET_ENABLED gates only the attempt reset
(attempt=0, prior value in held_redrive_last_attempt) and now defaults off
(lead2 ruling 64b2fa: a re-drive with a fresh budget moves held rows back
into processing, a custody change). Counting and the terminal stop have
their own class 6 switches.

Tests cover the switch true, unset and false: the requeue fields, and a
requeued unit that survives one lease expiry only with the reset on.

Failure-Class: FC-state-deadline-without-reader-exit
Class 4 (record_pending whose conversation exists but never finishes was
retried forever). RECORD_PENDING_BARRIER_DEAD_LETTER_ENABLED now defaults
off (lead2 ruling 64b2fa: parking changes custody). Off keeps the hourly
barrier ladder; rows parked while it was on return to the ladder at their
next daily recheck.

Tests cover the switch true (weekly re-drive, park, daily recheck without
admission), false and unset (hourly ladder), and on-then-off rollback.

Failure-Class: FC-state-deadline-without-reader-exit
Class 5 (unrestorable persisted assignment holds had no deadline).
BATCH_ASSIGNMENT_HOLD_ESCALATION_ENABLED now defaults off (lead2 ruling
64b2fa). The switch only stamps assignment_hold_deadline_at and the
retained escalation marker (database/batch_pipeline_projection_release.py,
the persisted-unrestorable branch); automatic release of restorable holds
is the pre-existing release-scan assignment leg, gated by
BATCH_PIPELINE_PROJECTION_HOLD_RECOVERY_ENABLED, and is unchanged.

Tests cover the switch true (deadline, escalation, release clears it,
re-hold gets a fresh deadline), false and unset (no writes), and the
existing persisted-hold release and expiry contracts with escalation on and
unset.

Failure-Class: FC-state-deadline-without-reader-exit
Brings #24884 (920bb5b: record barrier dead letter, assignment-hold expiry
via _expire_assignment) onto the backlog state machine.

Code conflicts, resolved in favor of this branch while main's paths run
unchanged with the backlog switches off:
- utils/batch_pipeline/live.py: keep main's record_barrier_aged dead letter
  and its robust age; class 4 (RECORD_PENDING_BARRIER_DEAD_LETTER_ENABLED,
  default off) owns present-but-unfinished rows only while on, and main's
  dead letter is skipped just for those rows. BARRIER_NOT_CLOSED now comes
  from config.record_audio (main).
- database/batch_pipeline_projection_release.py: take main's
  _expire_assignment; the class 6 counter and terminal stop move into it,
  and both call sites return expired_rearm_exhausted as well.
- utils/batch_pipeline/held_dead_letter.py: keep both imports.

Generated files (additive, both sides kept, regenerated from sources):
backend/charts/monitoring/alert-rules.json,
backend/charts/monitoring/gmp-query-migration-inventory.json,
backend/docs/feature-flag-registry.md.

BATCH_PIPELINE_PROJECTION_GHOST_SETTLE_ENABLED is unchanged (main's code
default). New test file tests/unit/test_backlog_main_paths_switches_off.py
proves main's two paths are byte-identical with every new switch off and
each new path runs only with its switch on.
…erge)

Main moved 40+ commits after the first merge (e938c7f). One conflict:
config/feature-flags.yaml, additive, both sides kept (this branch's seven
backlog switches and main's BATCH_PIPELINE_PROJECTION_GHOST_SETTLE_WAKE_ENABLED);
backend/docs/feature-flag-registry.md and the monitoring exports were
regenerated from sources. No code conflicts. Ghost settle default unchanged.
…-budget gaps

1. Class 4: only the worker that still holds the drain lease
   (available_at == lease, the same fence as main's expiry) may spend
   re-drive budget, so a slow admission re-claimed by another replica spends
   nothing.
2. Classes 3 and 6: a status-poll re-drive of a retained held dead letter
   (terminal stop off) gets the nightly path's switched accounting through
   one shared helper: the counter increments held_redrives and class 3
   resets attempt.
3. Class 6 counter: a committed projection expiry at or over the re-arm
   budget records projection_rearm_budget_spent whether or not the stop is
   on; omi-backlog-held-redrive-budget-spent now covers it.
4. Class 4 tests: the 14-day boundary is tested with the switch on, and the
   other-cohort tests run with it on.

Each test failed on 91669fd, or, for the boundary test, against a
mutation that removes the age guard.

Failure-Class: FC-state-deadline-without-reader-exit
…dget signal

1. Class 1: the running-job cap serves only when CAPTURE_RETRY_CAP_ENFORCED
   is on. The CAPTURE_COVERAGE_MODE serve mode or serve cohort no longer
   makes running_cap terminalize a crashed running owner while class 1 is
   off (main never capped running owners); it only observes.
2. Class 6 counter: status-poll re-drives of retained held dead letters
   report held_redrive_budget_spent through the same predicate as the
   nightly scan (held_redrive_budget_spent), recorded once per committed
   poll, so repeated polls cannot loop without the alert signal.

Both tests failed on 37d8b06.

Failure-Class: FC-state-deadline-without-reader-exit
redrive_in_transaction returns bool | Literal['spent'] (the poll path's
spent-budget signal from the class 6 counter fix); redrive_dead keeps its
bool contract. Fixes the two pyright errors the pre-push typecheck raised
on the previous commit; no behavior change.

Failure-Class: FC-state-deadline-without-reader-exit
… 4 anchor gaps

1. Class 2: a running-crash redrive still carries dispatch_attempt as the
   task identity, but stamps dispatch_attempt_base. The legacy (cohort)
   dispatching-deadline cap counts only attempts since that base, which is
   main's budget, so with class 1 off a crash plus a delayed replacement no
   longer fails the job in a capture serve cohort.
2. Class 4: a row only belongs to class 4 when its enqueued_at is a real
   finite number. A missing, null, boolean or non-finite anchor keeps main's
   record dead-letter deadline, so it settles instead of retrying at age zero.

Both tests failed on 9c2681f.

Failure-Class: FC-state-deadline-without-reader-exit
…rge)

One conflict: config/feature-flags.yaml, additive, both sides kept. The
flag-registry doc and the monitoring exports were regenerated from sources.
No code conflicts. Ghost settle and BATCH_HELD_DEAD_LETTER_ENABLED unchanged.
Git-on-my-level added a commit that referenced this pull request Nov 8, 2026
<!-- claude-projects-attribution: {"github_login":"Git-on-my-level"} -->
_Requested by **David**_

## Summary

Fixes a wedge on the projection release path. A restorable
quarantine_held row that reaches `MAX_RELEASE_ATTEMPTS=3` was never
released and never expired, so it stayed forever. Measured on
2026-11-08: about 44% of a 120-row assignment_held sample and about 15%
of a 400-row quarantine_held sample sat at the attempt cap with no
automatic exit.

The fix routes that branch through the existing one-time expiry CAS
(`_expire_assignment`). It saves the capped count, resets attempts to
zero once, and waits for the nightly redrive. It never releases in the
same pass.

**Dark by default.** Behind
`BATCH_PIPELINE_PROJECTION_RESTORABLE_CAP_EXPIRY_ENABLED`, default OFF.
With the switch OFF, behaviour is identical to origin/main.

## Safety

- Cap semantics unchanged: `MAX_RELEASE_ATTEMPTS` stays 3. The requeue
cap (PR #24893) is not touched.
- With the switch ON, ordinary transactions refuse any row carrying an
expiry stamp, including the other scan leg. Only the nightly redrive
(`dead_before` strictly after the marker) releases a marked row.
- Privacy fence: `projection_privacy_refusal` and any non-empty
`privacy_reason` on the summary or any part refuse release and expiry
before any write.
- Persisted multipart suffix rows and open operator intents are excluded
from expiry.
- Existing not-restorable expiry is unchanged origin behaviour, per the
contract (CONTRACT.md around line 282).
- Flag is registered in `kill_switches.py`, `flag_budget.json`,
`config/feature-flags.yaml`, and the generated registry doc.

## Verification

Failure-Class: none


- `test_batch_pipeline_projection_release.py`: 215 passed. Flag-budget
test: 24 passed. Unit policy: 82 passed. New cases each under 0.5 s.
- `make preflight`: 41 checks passed. Typecheck: 0 errors.
- Reviews (two fresh Luna reviews at `718cd64cf6`, GLM flash blocked by
a host timeout): both APPROVE, no findings.
- Earlier blocking findings, all fixed: a same-scan re-release through
the second leg (round 1), and a privacy-marked multipart hold reaching
the expiry CAS (round 2).

Not verified: CI, production behaviour, integration with newer
origin/main. No deploy: enabling the switch is a prod flag flip and
waits for David's morning gate.

🤖 Generated with [Claude Code](https://claude.com/claude-code)


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/24916?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/24916?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F24916&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 8, 2026
…mits (#24927)

<!-- claude-projects-attribution: {"github_login":"Git-on-my-level"} -->
_Requested by **David** · [project
thread](https://claude.ai/code/project/chan_01DkCywHd8HiN61t59mu7kXF?thread=cmsg_01DkCywHd8HiN61t59mu7kXFReBVorHLQv1x1Xmz4fgMU8)_

## What changed and why

This is a follow-up to #24896 (merged), per lead2's 812335 ruling,
option B.

On `/reprocess`, the processing persist wrote `discarded=False` for a
kept verdict before the router's restore registered the recording
obligation. A selected-app failure raised after that persist and skipped
the restore. The result was a visible, kept recording with no recording
obligation.

The fix keeps visibility behind the restore:
- `process_conversation` takes `restores_discarded` from the router. For
a discarded row being restored, the persist keeps `discarded=True`.
- The router runs `restore_discarded` (registers the obligation, then
commits the metadata). The response's `discarded` flag reflects the
restore result.

Only the restore writes visibility for a discarded row. A selected-app
failure now leaves the row hidden with no obligation, and a successful
reprocess registers exactly one obligation.

Out of scope, per lead2's ed3b20: P2 C (the admission-time discarded
fence in `batch_pipeline_intake` and the `replace_record` discard
clearing). It is tracked separately for #24893's owner.

Files: `backend/utils/conversations/process_conversation.py`,
`backend/routers/conversations.py`, and the new
`backend/tests/unit/test_reprocess_restore_visibility.py`.

## Product invariants affected

- INV-MEM-4
- INV-TASK-2

## How it was verified

Gates ran on the exact head `9e7d5432061` (on top of the #24896 merge
commit `2ca7a20228b`):
- Unit targets: 39 files, including the new test file.
`BACKEND_PYTEST_FILE_ISOLATION=1`. 39 of 39 passed.
- Typecheck (`backend/scripts/typecheck.sh`): 0 errors.
- Real-store lifecycle emulator (`npm run
test:listen-lifecycle:emulator`): PASS.
- `scripts/pr-preflight`: see the result line below.

## Tests

`tests/unit/test_reprocess_restore_visibility.py` runs the real
`/reprocess` route and the real `process_conversation` against the
strict store. Only the model, selected-app, Redis, dream-marker, and
app-output-write boundaries are stubbed.
- Selected-app failure after the persist: the row stays hidden, no
restore registration, no recording job. The test fails on the pre-fix
code (`discarded` read as `False`), so it catches the bug.
- Successful reprocess: exactly one restore registration, the row
becomes visible, and a `record_pending` job exists.

The existing reprocess and restore suites
(`test_reprocess_app_selection.py`,
`test_restore_recording_obligation.py`,
`test_discarded_fanout_replay.py`) still pass unchanged.

## UI evidence

UI-Evidence: none -- backend change only

## Failure class (fixes)

Failure-Class: FC-rule-discard-left-visible

The reprocess shortcut must persist a discard decision and its
visibility atomically. Here the persist made a discarded row visible
before the restore committed its obligation.

Line-Count-Exception: backend/routers/conversations.py | 2588 -> 2590 |
2-line restore-visibility change for the /reprocess fix (lead2 812335
option B); split deferred so the reviewed fix lands unchanged
Line-Count-Exception:
backend/utils/conversations/process_conversation.py | 3403 -> 3408 |
5-line restores_discarded kwarg and persist guard for the /reprocess fix
(lead2 812335 option B); split deferred so the reviewed fix lands
unchanged

🤖 Generated with [Claude Code](https://claude.com/claude-code)


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/24927?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>
<!-- End of auto-generated description by cubic. -->
Git-on-my-level added a commit that referenced this pull request Nov 8, 2026
…ing (#24938)

Published correction **20213fb59ddfc8faac2876f907c91d51a0433024**,
verified **2026-11-08T23:33:16Z**; PR OPEN/unmerged, zero review
requests. Review-desk FIX-FIRST findings are fixed: 55-minute per-series
observation history, no optional-summary freshness failure, and
same-replica summary freshness filtering. **All 14 requested
monitoring/store suites passed (535 tests, no skips)**, including 53
real Prometheus scenarios. Complete guarded push hooks passed.
**Exact-head CI is GREEN: 64 terminal checks, 0 pending/failed**. No
production action or lifecycle state change.

## Symptom and evidence

The N5 scope report measured held assignment age **881815s**,
quarantine-held age **1835094s**, and corrupt record-pending age
**~1.794e9s (~57 years)** during **2026-11-08T14:03–14:10Z**.
Held-content snapshot was **6859s stale at 14:08Z**, with oldest
published age **3678199s (42.6d)**. An approximately zero enqueue clock
poisons the held-age sample.

The aggregate Grafana dry-run measured **66 unprovisioned/changed
rules** at **2026-11-08T14:05–14:59Z**: **17 firing**, including five
real backlog pages and a false queue-blind page. Worker-plane sampler
cadence was **~514s**, exceeding the prior 120s freshness budget. BYOK
age was **219900s**, below 259200s but predicted to cross in ~11h if it
keeps aging. These are the reports' historical measurements, not fresh
production measurements in this lane.

Evidence: workspace `data/run-2026-11-08-retro-fixnow/out-n5-scope.md`
§§4–5 (source `0dc944b9e02`) and `out-grafana-dryrun.md` (rules at
`2958b7c1b369`, baseline `027a61e0e951`). Import preparation authorized
by lane-owner relay of lead2 ruling **699300, 2026-11-08T15:13Z**,
superseding the dry-run's proposed BYOK page disposition.

## Change

- Held-age sampling skips nonnumeric, boolean, nonfinite and nonpositive
leg clocks, walking oldest-first by snapshot cursor with `limit(1)` per
RPC. **Metrics sampler fix, not a lifecycle point fix**: no row writes,
transitions, admission or lifecycle decisions. P3 freeze respected;
drain/new-cohort sampling unchanged. Invalid prefixes require additional
read-only document reads.
- New `omi-oldest-age-gauge-flat-1h`: positive per-series
projection-obligation/vendor-held/summary-debt/demand-processing ages
with equal 1h maximum and minimum AND an observation at least 3300s old
in that window, using `time() - min_over_time(timestamp(age)[1h:1m]) >=
3300`. Summary ages also require the matching replica timestamp younger
than 300s. Positive total for 10m, noData OK. No absent/stale
summary-timestamp failure arm; enablement-aware producer-blindness is
separate runbook debt. Freshness companions named in verification.
- New `omi-held-content-snapshot-stale`: newest fleet snapshot timestamp
older than 3600s for 10m; missing snapshot Alerting. Both new rules are
active warning/tier agent/audience agent with `omi-tier-silent`.
- `omi-batch-queue-safety-blind`: freshness arm **120s → 900s**,
retaining 5m pending, page routing and other query arms. Producer
cadence and adapter freshness do not change.
- Five known backlog page rules land **paused**, with written
owner-approved unpause criteria below. Their tiers, thresholds and
pending windows remain unchanged; notably held-row-age stays page /
>21600s.
- `omi-finalization-byok-dwell-page` retains UID, >259200s/1h threshold
and source freshness; now active **warning/tier agent/audience agent**,
`omi-tier-silent`, sibling warning notification timings.
- Regenerated combined rules and GMP consumer-query inventory, metric
declarations, runbooks and offline contracts. Existing vendor-held
collector identity is expressed literally for the emitter scanner,
pinned equal to its frozen name; emitted identity/labels/behavior
unchanged. Corrected the older drain test's original-rule-only review
deadline assumption.

The reviewed lifecycle test inventory records BYOK's agent tier and
eleven explicit strict known-gap clauses while the borrowed backlog
pages are paused under ruling699300. The active-alert assertion is
unchanged: each gap remains genuinely red, real unpause produces strict
XPASS and forces debt-record removal, and an unreviewed pause still
fails. The pre-push fallback now selects pytest filenames, excluding
support modules/conftest that collect zero tests; the existing cap
regression covers both test-name forms and helper-only changes. Its cap
and full-CI requirement are unchanged. The separate fleet-verifier tests
now expect exactly the three intentional gated-pause errors; the runtime
verifier remains fail-closed. No state/exit/deadline or lifecycle
decision is changed.

## Day-1 page list

These are all active tier=page rules in the full import. Every row's
receiver is explicitly listed; a row is eligible to notify only if its
condition and pending window fire. **This is routing inventory, not a
claim that every row fires at import.** The 12 rows marked `new/changed
set` are the retained page guards in the dry-run's 66-rule set; other
rows were already in the baseline. Four new/changed page guards remain
unevaluable from GMP (N1 debt below). Agent-tier rules, including BYOK
and both N5 sampler rules, are muted.

| UID | Receiver | Meaning | Import set |
| --- | --- | --- | --- |
| `tz_parakeet_rps_zero` | Omi - Services Alerting (Telegram) | Parakeet
receiving zero traffic for 10+ minutes — possible ILB connectivity or
config issue | existing baseline |
| `tz_backend_listen_lb_zero` | Omi - Services Alerting (Telegram) |
Backend-listen receiving zero LB traffic for 10+ minutes — transcription
pipeline may be down | existing baseline |
| `tz_backend_listen_pods_zero` | Omi - Services Alerting (Telegram) |
Backend-listen has zero ready pods — all replicas are down or failing
health checks | existing baseline |
| `tz_pusher_connections_zero` | Omi - Services Alerting (Telegram) |
Pusher has zero active WebSocket connections for 10+ minutes — live
transcription pipeline broken | existing baseline |
| `tz_backend_cloudrun_zero` | Omi - Services Alerting (Telegram) |
Backend Cloud Run service receiving zero LB traffic for 15+ minutes —
API may be unreachable | existing baseline |
| `tz_chat_agent_requests_zero` | Omi - Services Alerting (Telegram) |
The AI chat agent lane served under 5 requests in an hour; the lowest
hour in the preceding week was 18 | existing baseline |
| `omi-journey-capture-success-critical` | Omi - Services Alerting
(Telegram) | Capture finalization success share below the 90% paging
floor while at least 20 journeys were accepted in 30m | existing
baseline |
| `omi-journey-pusher-success-critical` | Omi - Services Alerting
(Telegram) | Pusher session success share below the 90% paging floor
while at least 20 journeys were accepted in 30m | existing baseline |
| `omi-journey-chat-success-critical` | Omi - Services Alerting
(Telegram) | Chat response success share below the 90% paging floor with
at least 20 journeys accepted and at least 5 failures in 30m | existing
baseline |
| `omi-stt-chain-exhausted-page` | Omi - Services Alerting (Telegram) |
More than 60% of accepted /v4/listen sessions exhaust the live-STT
provider chain in 5m | existing baseline |
| `omi-stt-provider-budget` | Omi - Services Alerting (Telegram) | A
live STT provider is out of balance or quota - top up the provider named
in the alert instance labels. | existing baseline |
| `omi-soniox-budget-exhausted` | Omi - Services Alerting (Telegram) |
Soniox balance exhausted — top up now | existing baseline |
| `omi-slo-live-critical` | Omi - Services Alerting (Telegram) | Live
transcription - SLO budget burn (critical) | existing baseline |
| `omi-slo-chat-critical` | Omi - Services Alerting (Telegram) | Mobile
chat - SLO budget burn (critical) | existing baseline |
| `omi-slo-pusher-critical` | Omi - Services Alerting (Telegram) |
Pusher session - SLO budget burn (critical) | existing baseline |
| `omi-datasource-prometheus` | Omi - Services Alerting (Telegram) |
Prometheus alert query path failed or returned no sentinel samples. |
existing baseline |
| `omi-datasource-cloud-monitoring` | Omi - Services Alerting (Telegram)
| Cloud Monitoring alert query path failed or returned no sentinel
samples. | existing baseline |
| `omi-datasource-gmp` | Omi - Services Alerting (Telegram) | GMP alert
query path failed or returned no Cloud Run sentinel samples. | existing
baseline |
| `omi-capture-summary-never-published` | Omi - Services Alerting
(Telegram) | Capture finalization - summary has not published | existing
baseline |
| `omi-stt-no-full-stage-target` | Omi - Services Alerting (Telegram) |
No live STT target has been at cost-routing stage 100 for 10m, so the
router serves every session from its availability escape | existing
baseline |
| `omi-sync-provider-budget-exhausted` | Omi - Services Alerting
(Telegram) | Sync/prerecorded transcription jobs are failing because an
STT vendor says the account is out of credits or budget | existing
baseline |
| `omi-device-wal-backlog-over-cap` | Omi - Services Alerting (Telegram)
| Device signal wal-backlog-over-cap: distinct devices in the last hour
exceed both the floor and 2x the 7-day hourly median. | existing
baseline |
| `omi-device-wedge-count-cap` | Omi - Services Alerting (Telegram) |
Device signal wedge-count-cap: distinct devices in the last hour exceed
both the floor and 2x the 7-day hourly median. | existing baseline |
| `omi-batch-queue-safety-blind` | Omi - Services Alerting (Telegram) |
Batch queue safety cannot measure every queue/retry priority, or its
sample has been stale for fifteen minutes. | new/changed set |
| `omi-batch-vendor-overflow-spend` | Omi - Services Alerting (Telegram)
| Batch GPU overflow has sent more than $50 of fresh audio to Modulate
in the last 24 hours | new/changed set |
| `omi-finalization-pair-drift` | Omi - Services Alerting (Telegram) |
Fresh lifecycle pair drift persists | new/changed set |
| `omi-pipeline-upload-503-storm` | Omi - Services Alerting (Telegram) |
Backend-sync upload admission exceeds 100 size-class 266-byte 503s/min
for 10 minutes. | new/changed set |
| `omi-pipeline-firestore-contention` | Omi - Services Alerting
(Telegram) | Batch services log more than 20
FirestoreContentionExhausted entries/min for 10 minutes. | new/changed
set |
| `omi-pusher-storage-queue-critical` | Omi - Services Alerting
(Telegram) | Pusher storage work is queuing persistently. | new/changed
set |
| `omi-pusher-memory-working-set-high` | Omi - Services Alerting
(Telegram) | Pusher memory is approaching its container limit. |
new/changed set |
| `omi-batch-held-backlog-growing` | Omi - Services Alerting (Telegram)
| Held batch backlog is growing or at least 10000 units | new/changed
set |
| `omi-enrichment-queue-depth-page` | Omi - Services Alerting (Telegram)
| Enrichment queue is beyond its recent operating range | new/changed
set |
| `omi-stt-vendor-benched-page` | Omi - Services Alerting (Telegram) | A
serving STT vendor remains at a low routing stage | new/changed set |
| `omi-incluster-guard-unsafe-page` | Omi - Services Alerting (Telegram)
| An in-cluster safety guard reports TRIP or BLIND | new/changed set |
| `omi-modulate-credit-page` | Omi - Services Alerting (Telegram) |
Modulate has rejected company credit | new/changed set |

Historically firing page rules are paused; the queue-blind cadence fix
should remove its healthy-cycle false positive. Current firing state
must be rechecked at deployment. Existing baseline rules were not
re-evaluated by the 66-rule dry-run.

## Paused at import

Pausing withholds these five known-debt pages while #24731/#24893 drain
owners track recovery. No automatic unpause; each requires a separate
approved source/provisioning change. Missing/stale observations do not
count as recovery.

| UID | Unpause criteria (thresholds unchanged) |
| --- | --- |
| `omi-pipeline-held-row-age` | After #24731/#24893 drain work and the
N5 invalid-clock sampler guard reach production, require fresh samples
of every held leg below 21600s continuously for 24h. The drain owner
must approve a separate unpause change; missing, stale or undated
samples do not count as healthy. |
| `omi-batch-unit-unpublished-2h` | After #24731/#24893 drain work
reaches production, require both fresh timeliness and queue sources
below 7200s continuously for 24h, with no blind scan. The drain owner
must approve a separate unpause change; missing or stale samples do not
count as healthy. |
| `omi-enrichment-fresh-dwell` | After #24893 enrichment drain work
reaches production, require fresh, untruncated fresh-cohort observations
below 3600s continuously for 24h. The lifecycle owner must approve a
separate unpause change; missing or stale samples do not count as
healthy. |
| `omi-record-pending-dwell` | After #24893 record-admission drain work
reaches production, require fresh, untruncated record_pending cohort
observations below 7200s continuously for 24h. The lifecycle owner must
approve a separate unpause change; missing or stale samples do not count
as healthy. |
| `omi-pipeline-projection-drain-stall` | After #24731 projection drain
work reaches production, require fresh projection-debt samples and
complete delayed turn metrics continuously for 24h: either no pending
projection debt, or claim_busy share <=0.5 and progress >=10 rows/s. The
drain owner must approve a separate unpause change; missing or stale
samples do not count as healthy. |

## Debt: 22 rules not evaluable from GMP until N1 scrape fixes land

The dry-run could not query the in-cluster-only series through the
ro-prod bot; these verdicts are **fires-unknown**, not healthy. Retro N1
owns listen/pusher scrapes and token, PodMonitoring and record-seal
crashloop recovery. Four listed page-tier guards are expected to remain
blind until their series exist; verify directly against Grafana's actual
in-cluster datasource before import rather than treating GMP absence as
acceptance.

- `omi-scrape-backend-listen-metrics`
- `omi-scrape-pusher-metrics`
- `omi-scrape-llm-gateway-metrics`
- `omi-scrape-dg_engine_metrics`
- `omi-scrape-stackdriver-metrics`
- `omi-scrape-cloud-run-application-metrics`
- `omi-scrape-gpu-metrics`
- `omi-scrape-parakeet`
- `omi-scrape-record-seal-worker-metrics`
- `omi-scrape-batch-pipeline-worker-metrics`
- `omi-scrape-diarizer-batch-metrics`
- `omi-stt-enabled-state-unknown`
- `omi-stt-evidence-loss`
- `omi-stt-pressure-sampler-stuck`
- `omi-stt-snapshot-unready`
- `omi-stt-stage-disagreement`
- `omi-stt-vendor-benched-page`
- `omi-modulate-credit-page`
- `omi-pusher-storage-queue-warning`
- `omi-pusher-storage-queue-critical`
- `omi-pusher-storage-pcm-refusals`
- `omi-pusher-memory-working-set-high`

## Expected firing and design questions

From the historical baseline, **snapshot-stale will enter Alerting**
after 10m if its measured 6859s stall persists, silently at agent tier.
Known backlog pages remain paused; BYOK remains silent even when its
dwell threshold crosses. Existing retry-age, lifecycle scan-blindness
and sentinel warnings remain active agent-muted debt.

Review-desk FIX-FIRST correction: all four series families require at
least 55 minutes of per-series timestamp history within the 1h window
(1m subquery, five-minute scrape/grid tolerance). This proves an
observed span, not continuous scrape coverage, and cannot combine
replicas. The existing 10m pending period remains. The standalone
summary freshness arm, including `or vector(1)`, is removed entirely:
intentional absence, zero or staleness of this optional producer cannot
independently fire the rule. Summary flat-age counts require the same
replica's sample younger than 300s, excluding retained former lease
holders under `summary-guarantee.md:109–115`. Separate runbook debt: add
an enablement/expected-producer signal and a dedicated freshness rule
before claiming summary-debt blindness coverage. Current production
enablement is not measured here. Offline Prometheus fixtures cover
startup, 55-minute eligibility, pending/fire/recovery, cadence, replica
separation, disabled/absent/stale timestamps and lease handoff.
Review-thread replies are authorized; no review requests or production
actions.

## Deploy, readback and rollback (not performed here)

1. Deploy the invalid-clock guard through the normal **backend train**
to backend-integration and batch-worker sampler consumers. Verify each
running release identity plus a fresh sampler metric/log; held ages must
no longer use epoch-zero clocks. No migration or historical data repair.
2. After merge, an authorized deployer dispatches
**`grafana_dashboard_provisioning.yml` with `environment=prod`**. A main
push provisions dev only; live-STT egress import does not carry the N5
rules. No workflow edits or dispatches in this PR.
3. The separate live-STT coverage verifier currently rejects
intentionally paused gated rules
(`verify_pusher_live_alert_route.py:585–591,664–684`); report that debt
to the import owner rather than unpausing known backlog to satisfy it.
Full provisioning preserves the approved pauses. Read back production
definitions with the provisioner without `--apply`. Require no drift:
both N5 UIDs and queries/no-data states, all five pause flags and
unpause annotations, queue-blind >=900s, BYOK warning/agent mute,
preserved thresholds, receiver routing. Recheck signals on the actual
datasource, including the 22 N1-debt rules. Then verify fresh snapshot
publication and gauge behavior. Offline tests prove no live notification
delivery.
4. Rollback uses the provisioner's saved backup or a scoped
revert/regenerate/reapply through authorized provisioning. Pausing the
new sampler UIDs is reversible; revert the clock guard through the
backend train if needed. Do not unpause known backlog pages or restore
the known 120s false-positive arm as an incidental rollback. No
lifecycle/data rollback.

## Validation and publication

- Correction head **20213fb59ddfc8faac2876f907c91d51a0433024**,
local/remote/PR readback **2026-11-08T23:21:25Z**. Worktree clean; PR
OPEN/unmerged, zero review requests. Published with required credential
scrubbing, `TZ=UTC`, `OMI_PR_BODY_FILE` and 900s backend file budget
through `bin/omi-heavy`.
- Regenerated/linted **222 combined/split definitions**, regenerated GMP
query audit, and passed the actual Promtool rule parser. The review
correction changes only the flat-age rule query/annotations among those
222 UIDs.
- Complete publication hooks passed: **51 manifest checks in 814.45s**,
Pyright (192s), OpenAPI compatibility/schema checks, incremental macOS
debug build (16.63s), and pinned formatting. No application
launch/install or deployed acceptance.
- Changed-file unit gate: **565 passed / 86 existing strict known-gap
xfails**, seven isolated files. This includes all **14 oldest-age
tests**, with four real Prometheus regressions covering **53 synthetic
scenarios**, no skips (23:17Z). Startup/short history cannot qualify;
sustained flat ages fire after observation history plus pending time,
then resolve on change. Optional producer and replica-handoff controls
pass. The 98-test sampler suite also passed, including invalid enqueue
clocks.
- All **14 requested monitoring/store suites passed: 535 tests, no
skips**, verified **2026-11-08T23:33:16Z**. Five suites passed in the
hook (215 tests); nine complementary suites passed through
`bin/omi-heavy` (320 tests). `PROMTOOL_BIN` also executed the two older
optional semantic regressions. These are two isolated runner commands on
the same correction SHA, not a single combined pytest session.
- Registry prerequisite:
[#24950](#24950), merge
`fadad03099acbf133fa6461f8f928d606cf6a236` at **2026-11-08T19:20:24Z**,
covers the overdue flag and UTC date. Merged origin/main without
rebasing before publication; no own registry metadata or `.github/`
edits.
- Exact-head CI **GREEN at 2026-11-08T23:33:16Z**: **64 terminal
checks**, 0 pending/failed, first run on this correction (no retry).
`scripts/pr-preflight --suggest`, draft-body metadata validation and
complete publication checks passed. Four related review threads received
correction/validation replies. Earlier source-audio CPU-budget timing
instability and prior-head retries are recorded in the implementation
report; no assertion, duration limit or allowlist was weakened.
- No production reads or GCP tier used; no deployment, Grafana
apply/readback, production historical replay, live notification
delivery, merge, review request, bus post, heartbeat or new ANX ask.

Failure-Class: none

This observability/sampler and import-disposition change does not match
an existing lifecycle/admission failure class. It changes no lifecycle
decision or user row and adds no `.github/` definition under the lane
boundary. Regression coverage pins invalid-clock walking, query
observation history, optional-producer freshness, replica matching,
inventory, preserved thresholds, pause recovery criteria and silent
agent routing.
Git-on-my-level added a commit to Git-on-my-level/omi that referenced this pull request Nov 10, 2026
…contract

Rewrite the ledger around a post-commit CAS transaction so a ledger failure
can never fail the real transition, and a concurrent writer cannot overwrite a
newer stage. Add the C2 census fields (schema version, identity, owner key,
admission/created/updated clocks, revision, terminal, speech basis, Home and
episode clocks), stage+revision idempotency with explicit late-append and retry
re-open, a closed reason vocabulary, and a bounded read-only iter_window /
census_window helper.

Instrument seal, first durable notes and the upload-failure terminal. Add the
independent admission counter, write outcome/failure counters, transition and
stage gauges, and the unknown-end-type counter. Include the ledger collection
in the portability export inventory and the recursive account wipe.

Admission and transcript landed remain C1b because BasedHardware#24893 owns those files.
Git-on-my-level added a commit that referenced this pull request Nov 10, 2026
Add a storage-neutral stage contract and fail-open store helper under
database/pipeline_ledger.py. One document per capture records stage,
entered_at, deadline_at, attempt, reason, end_type, end_at, the last 16
transitions, and a terminal TTL. Every nonterminal stage has a deadline
and an exit; advance() is idempotent and refuses backward transitions.

Instrument the seal transaction (database/record_audio.py) and the first
durable notes transaction (database/conversations.py). The ledger read and
plan happen before the real transaction, so the real transaction stays
write-only; a ledger error returns None and the real transition proceeds
unchanged. PIPELINE_LEDGER defaults on and off stops all ledger writes.

Admission and transcript landed are deferred to C1b because #24893 still
owns those files.
Git-on-my-level added a commit that referenced this pull request Nov 10, 2026
…age contract (#25047)

# C1a-core: storage-neutral in-flight ledger contract (dormant, no live
hooks)

Failure-Class: FC-state-deadline-without-reader-exit

Line-Count-Exception: backend/database/firestore_index_registry.py |
2342 -> 2343 | one collection-group single-field index for the C2 ledger
window read helper.

## Size (measured, not estimated)

`git diff --numstat 720f078...HEAD`
outside
`backend/tests/**`:

```
4   0  .github/scripts/dead_code/backend.allowlist.json
7   0  backend/charts/monitoring/metric-inventory.prod.json
5   0  backend/config/refactor_modes.py
1   0  backend/database/firestore_index_registry.py
462 0  backend/database/pipeline_ledger.py
2   0  backend/docs/feature-flag-registry.md
21  0  backend/utils/observability/reasons.py
1   0  config/feature-flags.yaml
23  0  firestore.indexes.json
```

**526 changed non-test lines** (526 additions, 0 deletions), 26 over the
500-line cap. The C1 fix batch itself is **77 changed non-test lines**
(56
additions, 21 deletions) in `backend/database/pipeline_ledger.py`, under
the
200-line fix cap. The 26-line overage is the fix batch on top of the
491-line
split; the alternative was to leave the pre-review findings open. Total
including tests: 1,073 additions / 2 deletions.

The one `.github` change is the dead-code allowlist entry the ratchet
itself
prescribes for a dormant module (same mechanism as
`backend/utils/batch_pipeline/vendor_health.py`). It is a data file, not
a
workflow. C1a2 removes the entry when the first caller lands.

## Base and head

- Base: `720f078b33dde3872f5156fb87a961ffec2300c7` (`origin/main` at
branch
  creation; still the merge base).
- Head: `d84481d96c321e0c4c62ea4cfc90662beb88fd5e` (push 3/3).

This is push 3/3 for #25047. Push 2/2 (`d9efc6ce`) was the mechanical
content
split that brought the dormant core under the cap. Push 3/3 is the C1
fix
batch for the three `28a41fa` pre-reviews. The live
seal/notes/upload-failure
callers are still not in this PR; they remain in
`evidence/c1a2-live-transition-hooks.patch` (C1a2).

## C1 fix batch — finding by finding

The three pre-reviews were written against `28a41fa`, which still
carried the
live callers. The split moved those callers to the preserved C1a2 patch,
so
the P1 caller findings are fixed there, not in this dormant core head.
The
core findings are fixed in this head.

| # | Finding | Resolution |
| --- | --- | --- |
| 1 | P1 post-commit writer recreates ledger data after deletion |
**C1a2 patch.** `advance()` accepts `source_ref`/`owner_ref`; the ledger
transaction reads both and refuses to create a row when the source is
missing/deleted or the owner document is gone. Fail-open for the
already-committed source transition. Emulator test
`test_delayed_ledger_write_does_not_recreate_after_source_delete` pauses
before `advance()`, deletes the source, and asserts no row. |
| 2 | P1 callers never supply revision/reopen | **C1a2 patch.**
`pipeline_ledger.source_revision()` derives an ordered revision from the
source snapshot's `update_time`; seal and notes pass it with
`reopen=True`, so a proof repair can close a `failed:upload_failed`
recording and a stale failure hook loses. Emulator test
`test_late_event_from_an_older_revision_is_refused`. |
| 3 | P2 TTL type | **This head.** `expires_at` is a UTC `datetime`
(Firestore timestamp), not a numeric epoch.
`test_expires_at_is_a_utc_timestamp_not_an_epoch` asserts the serialized
type. |
| 4 | P2 upload-failure terminal has no firing clock | **C1a2 patch.**
`mark_record_upload_failed` persists `record_upload_failed_at`; the seal
hook passes it as `end_at` (falling back to the observation time), never
last speech or the ledger-write time. |
| 5 | P2 first durable summary skipped when the acceptance clock is
unknown | **C1a2 patch.** The `noted` predicate accepts `reason in
{'summary', 'accept_unknown'}` while still excluding `discarded` and
`local_only`. |
| 6 | P2 census helper has no owner scope | **This head.**
`iter_window()`/`census_window()` require `uid` and query
`users/{uid}/pipeline_ledger`; no cross-owner read. Emulator test
`test_census_window_never_reads_another_owner`. |
| 7 | P2 raw identifiers in rows | **This head.**
`capture_id`/`conversation_id` are no longer stored in the row body; the
document path is the documented key. The census projects bounded fields
only. |
| 8 | P2 partial results before truncation failure | **This head.** The
window is materialized before the first yield, so a truncated window
raises `LedgerWindowTruncated` without handing the caller a prefix.
`test_iter_window_yields_no_prefix_before_truncation`. |
| 9 | P2 arbitrary `failed:<text>` bypasses validation | **This head.**
`plan_advance()` normalizes any `failed:` stage through
`failed_stage()`, so only the closed failure vocabulary is stored;
unknown text collapses to `failed:other`.
`test_arbitrary_failed_reason_collapses_to_the_closed_enum`. |
| 10 | P2 repeated partial seals inflate admissions | **C1a2 patch.**
Admission is counted only when the seal actually closes the recording,
not on a partial-seal repair. |
| 11 | P2 ledger emulator suite never runs in CI | **Follow-up, not
fixed here.** Adding the path to `backend-emulator-proofs.yml` alone
would not run the suite: the workflow invokes
`backend/scripts/run-emulator-proofs.sh`, which does not list
`test_pipeline_ledger_firestore.py`. The one-line trigger addition is
therefore insufficient; the follow-up is to add the suite to that script
(and then the trigger path). No workflow change is made in this PR. |

## What C1a-core is

A storage-neutral ledger contract plus its declared inventory. It has
**no live
transition hooks**: nothing in the product calls `advance()`. It is
dormant
observation/schema infrastructure, and this PR does not claim otherwise.

- `backend/database/pipeline_ledger.py` (new, 462 lines): stage table
with a
deadline and exit per nonterminal stage; `plan_advance()` pure
transition
rules; `advance()` in its own Firestore transaction that reads the
document
  before writing it (CAS); `iter_window()` / `census_window()` bounded,
owner-scoped read helper; content-free document shape;
counters/gauges/histogram.
- `backend/utils/observability/reasons.py`: closed
`PipelineLedgerOutcome` and
`PipelineLedgerFailureReason` enums and the `PIPELINE_LEDGER` reason
family.
- `backend/config/refactor_modes.py` + `config/feature-flags.yaml` +
`backend/docs/feature-flag-registry.md`: `PIPELINE_LEDGER` via
`default_on`.
- `backend/charts/monitoring/metric-inventory.prod.json`: the seven
declared
  metric names.
- `firestore.indexes.json` +
`backend/database/firestore_index_registry.py`:
the `pipeline_ledger.admitted_at` collection-group index retained for
the
  future global aggregate; the per-owner read helper uses the automatic
  single-field index.

Stages: `capturing`, `sealed`, `transcribed`, `noted`, `done`; terminals
`no_speech`, `noise`, `failed:<reason>` with a closed reason vocabulary.
`advance()` is idempotent for the same stage+revision, refuses backward
transitions, loses a stale revision, and re-opens a terminal only with
an
explicit higher revision. Terminal rows carry `expires_at` clamped to
`[26h, 7d]` (`PIPELINE_LEDGER_TERMINAL_TTL_SECONDS`, default 93600).

## What core proves

- The pure transition contract: table invariants, forward/backward rank,
duplicate, stale revision, late-append and retry re-open, terminal
finality,
  max-16 history, bounded reason/end type, TTL clamp, schema fields and
content-free shape, `owner_key` truncated hash, closed `failed:`
vocabulary.
- `advance()` is fail-open on a store error, silent when the flag is
off, and
  writes the planned document with a read-before-write CAS in its own
transaction. A stale advance cannot overwrite a newer stage (emulator).
- The read helper is bounded, owner-scoped, read-only, rejects an
inverted
  window, projects bounded fields, and fails closed with
  `LedgerWindowTruncated` before yielding a prefix.
- Metrics are content-free (no uid, capture id, transcript, title or
reason
  text).
- The declared index and metric inventory match the code.

## What core does not prove

- **No real transition is instrumented.** Seal, first durable notes,
upload
failure, admission, transcript landed, episode composed and the
remaining
terminal exits are not wired. There is no production coverage claim; the
  99.5% target is measured only after those transitions land.
- **No atomicity with a real write.** There is no real write in this PR.
The
contract is that a ledger write is a separate transaction after the real
commit, so it is not atomic with it; a crash between them loses that row
and
the independent admission counter makes the loss visible. That statement
is
  inherited from the reviewed design and is not exercised here.
- **No portability/erasure wiring.** The collection is never populated
in
  core, so there is nothing to export or erase. The export inventory and
recursive account wipe move to C1a2 with the first live write, so no
window
  exists where rows are written without erasure.
- **The P1 caller fixes are in the C1a2 patch, not this head.** They are
not
  claimed as proven by this PR's tests.

## Default, rollback, metric honesty

- `PIPELINE_LEDGER` defaults **on**, but with no call sites it writes
nothing.
  The default is inert in this PR.
- Rollback is a no-op: setting `PIPELINE_LEDGER=off` changes nothing
because
  nothing calls `advance()`. No data deletion is needed.
- All seven metrics are registered and declared, but in production every
series
  is flat: `admit_total` is never incremented, `rows` never moves,
`stage_seconds` never observes, and `write_total` /
`write_failures_total` /
`transition_total` / `unknown_end_type_total` only move when a test
calls
  `advance()` directly. Do not read these as coverage.

## C1a2 allocation (preserved, not rewritten)

Moved to `evidence/c1a2-live-transition-hooks.patch` in the run
directory
(`data/run-2026-11-08-pipeline-refactor/evidence/`), with
`evidence/c1a2-handoff.md`. The patch now applies to this head
(`d84481d9`) and carries the P1 caller fixes plus findings 4, 5 and 10.

| File | Non-test add/del |
| --- | --- |
| `backend/database/record_audio.py` (seal + `failed:upload_failed`,
revision, firing clock, admission) | 49 / 2 |
| `backend/database/conversations.py` (first-summary `noted`,
revision/reopen) | 51 / 2 |
| `backend/database/pipeline_ledger.py` (`end_type_for_trigger`,
source/owner fence, `source_revision`) | 62 / 5 |
| `backend/utils/observability/reasons.py` (`DELETED` outcome) | 1 / 0 |
| `backend/services/users/data_export.py` (portability) | 13 / 0 |
| `backend/database/user_data_deletion.py` (wipe inventory) | 1 / 1 |
|
`backend/docs/listen_pusher_pipeline/changes/2026-11-10-pipeline-in-flight-ledger.md`
| 64 / 0 |
| `.github/scripts/dead_code/backend.allowlist.json` | 0 / 4 |
| **C1a2 non-test total** | **241 / 14 (255 changed)** |

C1a2 also carries the moved tests: seal, summary persistence, durable
outbox
transaction count, conversation transaction expiry, export inventory,
the two
`test_pipeline_ledger.py` cases, and the emulator hook cases including
the
deletion-interleaving and revision-ordering tests. C1a2 lands as a
separately
reviewed PR after C1a-core merges, and it removes the
`backend/database/pipeline_ledger.py` dead-code allowlist entry.

## Tests (this head)

Run with the worktree venv and GCP credential env vars unset, through
`bin/omi-heavy`:

- `tests/unit/test_pipeline_ledger.py` (31 passed): table invariants,
legal/illegal/duplicate/stale/terminal transitions, late-append and
retry
  re-open, max-16 history, bounded reason/end type, TTL datetime, closed
`failed:` vocabulary, schema/redaction, firing-clock separation,
fail-open,
  disabled switch, owner-scoped read helper, truncation-before-prefix,
  content-free metrics.
- `tests/integration/test_pipeline_ledger_firestore.py` (4 passed,
loopback
emulator): stale advance cannot overwrite a newer stage, disabled ledger
  writes nothing, census window reads committed rows, census never reads
  another owner.
- Inventory/flag/reason/index suites (355 passed):
`test_firestore_field_indexes.py`,
  `test_reason_label_enums.py`, `test_config_refactor_w6.py`,
  `test_monitoring_telemetry_contract.py`, `test_flag_budget.py`,
  `test_firestore_outside_query_contract.py`.
- Export/privacy and touched-transition suites (270 passed):
  `test_data_export.py`, `test_data_export_streaming.py`,
  `test_users_export_streaming.py`, `test_batch_pipeline_privacy.py`,
  `test_delete_account_purge_storage.py`, `test_record_audio_seal.py`,
  `test_summary_persistence.py`, `test_audio_durable_outbox.py`,
  `test_conversation_persistence_transaction_expiry.py`.
- C1a2 moved suites (281 passed) and C1a2 emulator (11 passed) were run
in a
temporary worktree at this head with the updated patch applied; the
patch
  applies cleanly to `d84481d9`.
- Full pre-push gate: passed (bounded local evidence; CI remains the
full test
  authority).

## Product invariants affected

- INV-MEM-3

## Scope split

- **C1a2** (preserved patch): seal, first durable notes, upload failure,
end-type mapping, portability export, recursive erasure, change note,
and
  the P1 caller fixes.
- **C1b**: admission (`utils/batch_pipeline/live.py`) and transcript
landed
(`database/batch_pipeline_projection.py`), blocked by the #24893
ownership
  fence; episode composed; remaining terminal exits; true admission
  denominator.
- **C2**: reads only through `iter_window()` / `census_window()`.

No admission live.py/projection fence, episode composition, Jev/E1, C2
endpoint, prod data/config, UI, `.github` workflow, credentials, model
names,
deploy or merge in this PR.
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Closing as part of a stale-PR cleanup David asked for on 2026-11-26 (Shipping lead agent): it has had no activity for days. Nothing is lost: the branch stays, and anyone can reopen this PR if the work is still wanted. If it still matters, reopen it and refresh it against main.

@github-actions

Copy link
Copy Markdown
Contributor

Hey @Git-on-my-level 👋

Thank you so much for taking the time to contribute to Omi! We truly appreciate you putting in the effort to submit this pull request.

After careful review, we've decided not to merge this particular PR. Please don't take this personally — we genuinely try to merge as many contributions as possible, but sometimes we have to make tough calls based on:

  • Project standards — Ensuring consistency across the codebase
  • User needs — Making sure changes align with what our users need
  • Code best practices — Maintaining code quality and maintainability
  • Project direction — Keeping aligned with our product principles and locked invariants

Before your next PR, please skim:

  • PRODUCT.md — product north star
  • Product invariants — locked rules (shared chat, memory tiers, agent control plane, integrations, brand)

If this was declined for direction or taste, maintainers should cite an invariant ID or open a proposed one — ask if that citation is missing.

Your contribution is still valuable to us, and we'd love to see you contribute again in the future! If you'd like feedback on how to improve this PR or want to discuss alternative approaches, please don't hesitate to reach out.

Thank you for being part of the Omi community!

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