Repository navigation
fix(backlog): explicit retry state for batch backlogs, reviewed core + corrected rollback docs (supersedes #24936 head) - #25012
Conversation
Class 1 (the retry cap only observed outside the CAPTURE_COVERAGE_MODE serve cohort, so lease-expiring units retried forever). CAPTURE_RETRY_CAP_ENFORCED, default off (lead2 ruling 64b2fa: enforcing quarantines rows, a custody change). When on, a batch lease expiry at BATCH_PIPELINE_MAX_ATTEMPTS quarantines for every uid (retained held, the transition explicit worker failures already take). The sync dispatching cap keeps the cohort decision (enforce=False): a passed dispatch retry deadline is queue delay, not failure. Backlog switches are parsed literally and never re-read through the capture-coverage serve-mode parser, which would turn an unset default-off switch on. Alert omi-backlog-retry-cap-quarantine-rate. Tests run the switch true, unset and false; legacy cohort tests pin the off state. Failure-Class: FC-state-deadline-without-reader-exit
…base (default ON) Class 2 (a running sync lease expiry reset dispatch_attempt to 0, so the attempt budget never bounded crashes). SYNC_DISPATCH_ATTEMPT_CARRY_ENABLED, default on (lead2 ruling 64b2fa: it only stops the reset, cuts retries). The carry is unsafe without dispatch_attempt_base, so both ship together: dispatch_attempt stays the carried task identity, and dispatch_attempt_base restarts the legacy dispatching-deadline budget at each new epoch, exactly as main's reset did. Without the base a crash plus a delayed replacement fails the job in a capture serve cohort while class 1 is off. Crashes are counted in running_expiries (an expiry while a budget deferral's deferred_until marker is live is not a crash; reset at claim). The reconciler finalizes a running owner at SYNC_TASKS_MAX_ATTEMPTS only with class 1 on; the CAPTURE_COVERAGE_MODE cohort never turns that on, and with class 1 off the count is observed only. redrive_job never refuses a running owner. Alert omi-backlog-sync-running-cap-rate. Tests run the switch true, unset and false, class 1 on and off, serve mode and serve cohort, budget-deferral chains, terminal jobs and the delayed dispatch budget. Failure-Class: FC-state-deadline-without-reader-exit
…fault ON) Class 6, counter only (amendment 12:49Z: the counter goes in core because it is independent of the projection re-arm and the terminal stop, which stay in the follow-up). BATCH_HELD_REDRIVE_COUNTER_ENABLED, default on (lead2 ruling 64b2fa: counter and alert on). - Every held re-drive (nightly, operator, status poll of a held_expired dead letter) increments held_redrives through one shared helper. - The nightly scan and committed poll re-drives record held_redrive_budget_spent at or over MAX_HELD_REDRIVES (3), alerted by omi-backlog-held-redrive-budget-spent. Counting and an alert only: no requeue refusal, no state change, and the projection release path is untouched. Tests run the counter true, unset and false for requeue counting, the nightly observation and repeated poll re-drives. Failure-Class: FC-state-deadline-without-reader-exit
Class 3 (a requeue from held or dead-letter kept attempt at or above the cap, so a re-drive re-quarantined on its first failure). BATCH_HELD_REDRIVE_BUDGET_ENABLED, default off (lead2 ruling 64b2fa: a re-drive with a fresh budget moves held rows back into processing, a custody change). When on, every held re-drive (nightly, operator, status poll) resets attempt to 0 and keeps the prior value in held_redrive_last_attempt, through the same helper as the class 6 counter. Tests run the switch true, unset and false, and the counter x budget combinations through the real status-poll path. Failure-Class: FC-state-deadline-without-reader-exit
Switch table, defaults and rollback for classes 1, 2, 3 and the class 6 counter, plus the known pre-existing projection re-arm gap on main (batch_pipeline_projection_release.py:290), which this branch does not change.
One conflict: config/feature-flags.yaml, additive, both sides kept (the four core switches and main's new rows); the registry doc and monitoring exports were regenerated. No code conflicts. BATCH_HELD_DEAD_LETTER_ENABLED and ghost settle unchanged.
The pre-existing gap is now addressed on main behind BATCH_PIPELINE_PROJECTION_RESTORABLE_CAP_EXPIRY_ENABLED (default off). This branch still does not touch batch_pipeline_projection_release.py.
config/feature-flags.yaml conflicted again (additive). Resolved to main's file with the four backlog rows moved to the end of the flags list, so new rows main adds under 'flags:' no longer collide with them. Registry doc and monitoring exports regenerated. No code conflicts.
test_requeue_idempotent_and_usable_with_flag_off_retains_attempt_and_audio_history asserts a requeue keeps attempt at the cap, which is main's behavior and the class 3 off path. Running the suite with BATCH_HELD_REDRIVE_BUDGET_ENABLED=true in the environment made it fail by design. The class 3 on path (attempt reset, held_redrive_last_attempt) is covered in test_backlog_state_machine.py. Failure-Class: test-contract Co-Authored-By: Claude Opus 5.5 <[email protected]>
… sync running cap Custody review on a80f4fc, two blockers. 1. /redrive-dead on a held_expired dead letter bypassed the class 3 attempt reset and the class 6 count: only the status poll passed automatic=True. Every held_expired re-drive now goes through account_held_redrive, and Scheduler.redrive_dead records held_redrive_budget_spent after commit, like the nightly scan and the poll. Plain dead rows are unchanged. 2. With class 1 unset and CAPTURE_COVERAGE_MODE off, running_cap returned None, so a running lease that kept expiring past the cap was redriven forever with no signal. running_cap now always returns an observe-only decision while class 1 is off (would_quarantine), and a committed running-lease redrive at or over the cap records sync_running_cap_observed, alerted by omi-backlog-sync-running-cap-unenforced. The cap still terminalizes only with class 1 on. Tests drive the /redrive-dead route with counter x budget on and off, below and at the budget, and the sweep with class 1 unset, false and true. Main's two retain-attempt held tests pin class 3 off. No default changes. Failure-Class: FC-state-deadline-without-reader-exit Co-Authored-By: Claude Opus 5.5 <[email protected]>
…amilies Custody review on abd11f1. 1. The held re-drive alert needed more than 64 spent-budget observations an hour, so one recording looping through held, expiry and re-drive (about once per 8 days, no terminal stop in core) never alerted. New rule omi-backlog-held-redrive-unit-looping fires on any spent-budget observation in the last 8 days, so a single unit is enough and a looping unit keeps it firing. The 64/h volume rule stays. 2. The Cloud Run metrics exporters did not import omi_backlog_state_transitions_total or omi_capture_retry_cap_total, so every backlog alert read vector(0). Both families are added to the prod and dev main and sync exporter allowlists, with a contract test that every family the backlog alerts query is imported by both releases. 3. /requeue-quarantined counted the re-drive but never reported a spent budget. The operator requeue now records held_redrive_budget_spent after commit; the nightly pass, which already observes in its scan, does not signal twice. 4. retry_cap's docstring, a retry_hygiene comment and the quarantine-rate alert title said the cap enforces by default; class 1 is off by default. Tests evaluate the alert rule definitions through scripts/alert_backtest.py over a simulated nightly loop of one recording. No default changes. Failure-Class: FC-state-deadline-without-reader-exit Co-Authored-By: Claude Opus 5.5 <[email protected]>
…t rules The unit-looping alert test evaluates both held re-drive rules; the volume rule uses a 1h window, which the day-only parser rejected. Failure-Class: test-contract Co-Authored-By: Claude Opus 5.5 <[email protected]>
…chine-core # Conflicts: # backend/charts/monitoring/alert-rules.json # backend/charts/monitoring/gmp-query-migration-inventory.json
…itch parsing Custody review on 53a692d. A. An expired deferred_until marker was read as proof the budget-deferred replacement ran, so the running cap could fail the job and release its owner while the delivery was only late. The replacement retires the marker when it starts, so any marker still on the job now keeps the delivery obligation: the expiry is not a crash and the cap does not finalize. B. The class 3 attempt reset could run without the class 6 counter, and the terminal stop is not in core, so nightly re-drives could grant fresh budgets forever with no alert. The reset now takes effect only with the counter on and only while the unit has fewer than MAX_HELD_REDRIVES re-drives; a spent or uncounted unit keeps main's retained loop and the spent-budget signal. C. The backlog switches lowercased and trimmed their value, so TRUE enabled them. They now enable only on the exact raw value true; main's other switches keep their parsing. D. Terminal and vanished-job cleanup counted a running crash; only a lease expiry with no pending replacement does now. E. The sync running cap recorded quarantine before the fenced handoff; it is recorded only after finish_expired_job succeeds. Each fix has a test that fails on 53a692d and passes here. No default changes. Failure-Class: FC-state-deadline-without-reader-exit Co-Authored-By: Claude Opus 5.5 <[email protected]>
…t of core Coordinator ruling (b): core keeps class 1, class 3 and the class 6 counter; class 2 (SYNC_DISPATCH_ATTEMPT_CARRY_ENABLED) and the sync budget-deferral chain move to the follow-up branch with their open items. - utils/sync/retry_hygiene.py, utils/sync/uid_sequencer.py and database/sync_backfill_sequencer.py return to main's text: no attempt carry, running_expiries, dispatch_attempt_base, deferral_pending, running cap, running-cap observation or deferred-finalizer recording. - retry_cap now enforces only for callers that opt in (enforce=True); the batch lease-expiry cap opts in, so class 1 is batch-only and main's sync dispatch cap keeps its CAPTURE_COVERAGE_MODE cohort decision. - The switch, its flag row and registry entry, the sync_running_cap_reached and sync_running_cap_observed transitions, and the two sync running-cap alerts are removed; the runbook drops class 2. - Class 2 tests move with it; a new test pins main's sync dispatch cap under class 1 on and off. Defaults of the kept switches are unchanged. Failure-Class: FC-state-deadline-without-reader-exit Co-Authored-By: Claude Opus 5.5 <[email protected]>
…rt tests The class 2 removal restored this file to main's text, dropping the class 1 pin with it. Its batch cohort tests assert the legacy shadow decision, which is the CAPTURE_RETRY_CAP_ENFORCED off path; running the suite with the switch forced true failed them. The enforcing batch path stays covered in test_backlog_state_machine.py. Failure-Class: test-contract Co-Authored-By: Claude Opus 5.5 <[email protected]>
…es for the owner Custody review on da4132e (luna-core-5-1). With class 3 and the class 6 counter on but class 1 off, an owner outside the served CAPTURE_COVERAGE_MODE cohort got a fresh attempt budget although its lease expiries only defer: the unit stayed runnable without bound, the spent-budget alert never saw it, and the retry-cap alert counts only quarantines. The reset now takes effect only where the batch retry cap enforces for the owner (class 1 on, or the owner in the served cohort); elsewhere it is a no-op and main's behavior is kept. The class 6 counter is unchanged. test_class_3_reset_only_where_the_retry_cap_enforces_for_the_owner fails on da4132e and passes here; class 3 reset tests now enable class 1. No default changes. Failure-Class: FC-state-deadline-without-reader-exit Co-Authored-By: Claude Opus 5.5 <[email protected]>
Switching class 3 OFF stops new budget resets. Existing grants persist until their unit runs or finishes. Each grant is capped at MAX_ATTEMPTS. Documentation and a regression test only; no behavior or default change. Failure-Class: none Co-Authored-By: Claude Opus 5.5 <[email protected]>
omi-backlog-held-redrive-unit-looping was agent tier, so omi-tier-silent muted it, and its UID was outside live-alert-gate.json. One looping unit stays under the volume alert's threshold, so nobody was notified. Route it as a page on the same Telegram receiver with no mute interval, add the UID to live-alert-gate.json so the monitoring workflow imports and reads it back, and regenerate alert-rules.json. A test pins the route. Failure-Class: none Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ass 1 Switching class 1 OFF stops new cap enforcement and switching class 3 OFF stops new budget resets; existing grants persist with no clawback. Each grant is capped at MAX_ATTEMPTS only while the retry cap enforces for the owner (class 1 on, or the owner in the served cohort). With class 1 off, lease expiries defer, as on main. The earlier class 3 text claimed an unconditional cap. Documentation and a regression test only; no behavior or default change. Failure-Class: none Co-Authored-By: Claude Opus 5.5 <[email protected]>
backend/docs/feature-flag-registry.md conflicted: main added BATCH_LIVE_ORPHAN_REPAIR_ENABLED next to this branch's BATCH_HELD_REDRIVE_BUDGET_ENABLED row, and the undeclared-env list moved. The file is generated, so it was re-rendered from the merged config/feature-flags.yaml with scripts/render_feature_flag_registry.py (as-of 2026-11-05, unchanged). The result is main's doc plus this branch's three rows (CAPTURE_RETRY_CAP_ENFORCED, BATCH_HELD_REDRIVE_BUDGET_ENABLED, BATCH_HELD_REDRIVE_COUNTER_ENABLED), one table row and one list entry each. check_feature_flag_registry: OK. Failure-Class: none Co-Authored-By: Claude Opus 5.5 <[email protected]>
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 51527ef1c5
ℹ️ 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".
| # MAX_ATTEMPTS only while the retry cap enforces for the owner (class 1 on, | ||
| # or the owner in the served cohort). With class 1 off, lease expiries | ||
| # defer, as on main. | ||
| from utils.capture.retry_cap import retry_cap |
There was a problem hiding this comment.
Move the new backlog imports to module scope
backend/AGENTS.md explicitly requires “All imports at module top level — never inside functions.” This new function-local import violates that backend convention, as do the new record_transition imports in Scheduler.redrive_dead, RecoveryStore.requeue_quarantined, and durable_status. Move these imports into their respective module-level import blocks.
AGENTS.md reference: backend/AGENTS.md:L168-L168
Useful? React with 👍 / 👎.
The BATCH_HELD_REDRIVE_BUDGET_ENABLED note said the first failure after a re-drive re-quarantines. That holds only where class 1 (CAPTURE_RETRY_CAP_ENFORCED) enforces for the owner; with class 1 off for an owner outside the served cohort, lease expiry defers instead, as on main. Wording only; no default or behavior change. Failure-Class: none Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts: # backend/charts/monitoring/alert-rules.json # backend/charts/monitoring/gmp-query-migration-inventory.json # backend/database/batch_pipeline_quarantine_recovery.py # backend/docs/feature-flag-registry.md # backend/utils/batch_pipeline/held_dead_letter.py # backend/utils/batch_pipeline/scheduler.py Conflict-resolution: backend/charts/monitoring/alert-rules.json: union main staged-input-age and all backlog retry/redrive alerts. Conflict-resolution: backend/charts/monitoring/gmp-query-migration-inventory.json: union query consumers and recompute total to 271. Conflict-resolution: backend/docs/feature-flag-registry.md: retain both flag families and main current registry dates. Conflict-resolution: backend/utils/batch_pipeline/held_dead_letter.py: preserve independent pre-sleep input expiry and malformed-clock protection alongside spent-budget observations. Conflict-resolution: backend/utils/batch_pipeline/scheduler.py: retain input-expiring poll guard and operator override alongside retry accounting and committed spent-budget signals. Conflict-resolution: backend/database/batch_pipeline_quarantine_recovery.py: keep expected-job/privacy/content CAS and input expiry alongside post-commit budget reporting. Conflict-resolution: backend/tests/unit/test_backlog_state_machine.py: adapt two nightly-counter fixtures to main independent urgency-query seam. Failure-Class: merge-drift
Address PR 25012 pre-review batch A-F under lead2 ruling 7a3c9e. Keep telemetry rollback independent of custody, repair malformed counters, normalize switches and preserve the sync scrape contract. Failure-Class: FC-state-deadline-without-reader-exit
Conflict-resolution: Keep main's sync scrape regex exactly and insert backlog_state_transitions_total| immediately after omi_(. This preserves both backlog transitions and the upstream quiet-check allowlist. Failure-Class: merge-drift
Build durable status from the staged job after a successful re-drive. Keep refused re-drives unchanged and pin returned status and poll intervals for both outcomes. Failure-Class: FC-state-deadline-without-reader-exit
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 5b4e70a9e5
ℹ️ 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".
| for _transition in TRANSITIONS: | ||
| TERMINAL_TRANSITIONS.labels(_transition) |
There was a problem hiding this comment.
Register the transition counter before the first spent event
In a fresh serving process, the first spent-budget transition is invisible to the new alerts: all three production imports of backlog_metrics occur only after a re-drive returns 'spent', so this initialization and the first increment happen together, before Prometheus can scrape a zero baseline. If only one unit spends its budget, subsequent samples remain at 1 and increase(...[1h]) stays zero; the durable spent marker then prevents that unit from emitting again. Import and initialize the collector during startup, before transitions can occur. The tests mask this because their transitions() helper imports the module before exercising the re-drive. This also follows the backend's module-level import requirement.
AGENTS.md reference: backend/AGENTS.md:L168-L168
Useful? React with 👍 / 👎.
Move unchanged ledger ownership predicates into a dependency-free shared module so the GPU scheduler fence cannot import Cloud Tasks. Regenerate the GMP query inventory for the current backlog alert window. Failure-Class: FC-runtime-image-boundary
Summary repair currently walks the oldest debt in its bounded window
before recent user-visible debt. Apply David's 2026-11-10 03:19Z ruling
(`relay-cl1 6db8f2`): serve rows at risk of expiry first, then newest to
oldest.
## Behavior
- Scan the first 600 seconds above the age-gate cutoff oldest-first,
then the remaining window by pending time DESC, with due/path
tie-breaks. The margin spans five 120-second ticks: up to 40 attempts at
the default eight-attempt cap. This provides headroom, not an overload
guarantee.
- Share the scan/admission budgets across both phases, with independent
versioned cursors. Owner fairness allows at most three attempts per
owner per tick across both phases, including failed/blocked attempts.
Each durable phase cursor continues after every examined row, including
owner-quota deferrals, so later owners remain discoverable across ticks
even when one owner fills multiple scan budgets. Deferred rows are
retained separately as unchanged conversation debt (`summary_due_at`);
later passes/wraps select them again. Admission/time interruptions
preserve the unexamined fetched tail. Exhausted phases wrap as before,
with no additional retry queue or cursor schema. Legacy phase cursors
reset safely.
- With the age gate disabled, preserve the legacy `summary_due_at <=
now` query ordered by `(summary_due_at, __name__)` and its flat due/path
cursor. Rows with missing or explicitly null pending time remain
admissible, using their due time to bound admission pending time.
Gate-enabled cursors advance on finite numeric due values, including
zero/negative values; datetime handling is preserved.
- Fetch chunks of at most 500 rows. Stop starting work at the admission
cap, total scan budget, or a 90-second cooperative scan-work deadline
checked between rows/chunks; an in-flight RPC can finish later.
`scanned` includes the fetched-but-unexamined tail: it counts returned
document rows, not examined rows or admissions.
- If the newest query raises `FailedPrecondition` (including an
unavailable DESC index), emit
`event=summary_debt_repair_newest_index_unavailable outcome=error` once,
count one error, skip that phase and still finish the near-expiry cursor
and counters. No alternate query is used; other exceptions propagate. An
empty near-expiry page followed by a newest-phase precondition failure
still finishes the cursor lease and publishes all five counters with one
error. Pagination uses the last examined row directly and never indexes
an earlier phase’s page tail. Both sweep callers accept an older
tick-result shape without `near_expiry_admitted`.
No extra per-user ranking reads are added. Eligible rows have no
reliable denormalized Home-today or active-user rank, so that preference
is deferred. Existing lifecycle/local-only exclusions remain.
## Settings and capacity
Three startup settings are registered in the flag catalog and
deployment-setting classification:
| Setting | Default | Bounds |
|---|---:|---:|
| `SUMMARY_DEBT_REPAIR_ADMISSION_LIMIT` | 8 | 1..60 |
| `SUMMARY_DEBT_REPAIR_PER_OWNER_LIMIT` | 3 | 1..10 |
| `SUMMARY_DEBT_REPAIR_SCAN_LIMIT` | 100 | 1..5000 |
Invalid values restore defaults. At 120 seconds/tick there are 30
ticks/hour, so the admission-attempt ceiling is the per-tick limit x 30:
default 240/hour, maximum 1800/hour. Lead2 `8b9c8f` sets
prod/backend-integration to eight attempts/tick in the runtime overlay
and ops inputs; the runtime manifest is regenerated. No other service
receives an override. Lead2 `d233ac` also sets the code default/fallback
to eight. The owning capacity record
`/Users/dazheng/workspace/omi/data/run-2026-11-08-retro-fixnow/out-sd-capacity.md`
uses a $0.0054/repair mean: 8/tick = 5760/day = $31.104/day (~$31.1),
within David's $36 planning budget. This is the ruling's worst-case
full-admission estimate using a mean, not a hard dollar bound or a
billing measurement by this task. Production cap rollback is explicit 10
in both inputs followed by regeneration and an authorized deploy; unset
now restores default 8.
Owner `215fdc` raises the scan maximum to 5000 without changing default
100 or adding an overlay value. Full-utilization row-read arithmetic:
720 ticks/day x 100 rows = 72000 document reads/day per 100 rows/tick.
At 2800 rows: **2800 document reads/tick and 2016000/day**; at 5000:
3600000/day. These figures exclude retries, empty-query minimums,
index-entry charges, cursor transactions and admission/fence/outbox
reads. The supplied ~84k-row window (`refactor-lead a7dc6f`, original
measurement timestamp not supplied) implies an ideal ~28h pass at
100/tick and ~1h at 2800/tick. Strictly under one hour needs more than
2800 if 84k is exact, before admission/time stops and cursor rewinds. A
debt-only index/filter that skips refusals is the structural fix and is
out of scope.
## Index readiness and telemetry
Keep the ASC composite and add `(summary_first_pending_at DESC,
summary_due_at ASC, __name__ ASC)` for the conversations collection
group, with index/query-shape/driver registries and generated manifest
updated. **The new DESC index must be READY in the target project before
deploy**, through the existing provisioning/readiness lane. The
selective phase error handling preserves urgent progress but does not
remove this deployment prerequisite. No deploy, index apply, flag flip
or production access is performed here.
Keep expired_seen/overdue/oldest/sample gauges and add
`near_expiry_admitted` to tick/sweep counts plus its gauge.
`omi_summary_debt_repair_total{outcome}` accumulates exactly the
returned tick values for `scanned`, `admitted`, `error` (returned
`errors`), `expired_seen` and `near_expiry_admitted`. It increments once
after cursor completion, outside transactional callbacks; unclaimed
ticks and transaction retries do not duplicate increments. All metric
names/outcomes are declared and pinned in tests.
Post-deploy admissions readback:
`sum(rate(omi_summary_debt_repair_total{outcome="admitted"}[10m]))`,
alongside `near_expiry_admitted`, `error`, the serving release identity,
sample freshness and summary receipts. Admissions are redrives, not
completed summaries. No live backlog, throughput, index readiness or
vendor spend was measured by this task.
## Validation
Current fix verification runs on m1 through
`/Users/david/workspace/omi-workspace/bin/omi-heavy`, with file-isolated
unit processes and `BACKEND_UNIT_FILE_BUDGET_SECONDS=900`. Local
results: **2675 passed** across 12 targeted files (104 summary/age-gate,
1729 lifecycle inventory, 842 index/query guards; one test deselected by
the standard marker filter) at 2026-11-10T17:03:08+00:00; **225 passed**
across the repair-cap, production-policy and sweep-caller files at
2026-11-10T16:59:25+00:00; **49 passed** against the real loopback
Firestore emulator at 2026-11-10T17:02:41+00:00. `make preflight`: **51
checks passed** before the final hardening at 2026-11-10T17:00:13+00:00,
including the complete query-shape guard (560 passed). Final PR-body
preflight: **51 checks passed** against `1112536b8397` at
2026-11-10T17:05:26+00:00. Normal pre-push hooks remain enabled.
Detailed evidence is recorded in
`/Volumes/scratch/cl2-fixnow-push25019/out-25019-fix4.md` with
timestamps. CI after this push is the authority for the complete backend
suite.
Regressions cover three persistent failing urgent rows for A and more
than two scan budgets of A's newest rows before B; B must be discovered
within a bounded number of ticks. After the obstruction is removed,
every retained deferred row must be admitted across wrap. Both enabled
and disabled age-gate modes are covered. The index-failure regression is
parameterized over empty urgent and owner-deferred urgent pages. The
emitted version-2 phase cursors remain usable by existing phase readers;
cleared flat fields cause older enabled-gate readers to rewind, while
disabled-gate readers retain the compatible flat due/path continuation.
No lifecycle field, query shape, or cursor field is added, so the
existing inventory and query-driver declarations remain applicable.
Existing tests retain near-expiry priority, the shared owner cap of
three and admission cap of eight, scan/time limits, preservation of
fetched tails, lease fencing, `FailedPrecondition` completion and
counter publication.
## Merge order
**#25019 merges first. #25020 and #25021 rebase and regenerate after
it**, then rerun their summary/enrichment/sync suites. For overlapping
generated artifacts (also touched by #25018/#25012/#24731/#24857),
regenerate from the combined sources rather than hand-resolving output
ordering: runtime-env compose, Firestore index manifest and flag
registry, followed by exact-match guards. This PR performs no merge or
review request.
Rollback: revert this PR, leaving the additive index. Unset restores
admission 8 / owner 3 / scan 100; prior admission rollback is explicit
10. The cursor schema remains version 2. Existing phase readers continue
correctly; cleared flat fields make older code rewind safely with the
gate enabled; disabled-gate mode keeps its compatible flat due/path
cursor. Deferred conversation debt remains queryable after rollback.
## Product invariants affected
- INV-MEM-4 — the generated runtime-manifest diff adds only the summary
repair cap on prod/backend-integration. Canonical memory intake,
consolidation, promotion receipts and projection authority remain
unchanged.
Failure-Class: FC-bounded-discovery-pinned-by-blocked-page
Failure mechanism: repair order: oldest-first starves user-visible debt.
Line-Count-Exception: backend/database/firestore_index_registry.py |
2336 -> 2342 | Declare the additive newest-first repair composite beside
the existing ASC requirement.
Line-Count-Exception: backend/routers/sync.py | 3820 -> 3821 | Expose
near-expiry admission counts through the existing scheduled sweep
response.
Return the updated job and spent flag from transactional redrives. Build poll status from that value, preserve post-commit operator/nightly accounting, and finish queue append reads before staging writes. Add a strict get-after-write regression and retain refusal coverage. Failure-Class: FC-joined-writer-writes-before-transaction-reads
Keep BATCH_PARTIAL_STATUS defined in sync_ledger.py as before the ownership extraction so the unchanged lifecycle scanner resolves its literal alias. The pure ownership module remains independent of the sync runtime. This CI-only restoration changes no persisted status value or lifecycle baseline. Failure-Class: none
Exercise two- and three-unit re-drives through the real buffered Firestore wrapper and a strict raw transaction, including active-token/receipt refusals and spent telemetry. Document why later candidate reads are safe before flush and distinguish the existing returned-job test from raw Firestore ordering. Failure-Class: none The production re-drive path already buffers every write. This adds review evidence and regression coverage without changing runtime behavior.
Requested by David
Merge head:
14752f01a0ba0e75cfb89642dd4187eddf0eea87(14752f0). Luna delta review SHIP and CI green (63 passed, 0 failed) at this exact head. Merge with--match-head-commit 14752f01a0ba0e75cfb89642dd4187eddf0eea87. Switches ship default OFF.Supersedes #24936's head
This supersedes the head of #24936 (
lane/backlog-state-machine-core, now71c6774e720on the remote). That branch was moved by another lane and carries 11 commits that were not reviewed here. This PR carries only the reviewed rollback docs and pin test on top of9f7d51691fe9, the last reviewed head of #24936. #24936 stays open for now.What this PR contains, against main:
9f7d51691fe9(class 1 retry cap, class 3 held re-drive budget, class 6 counter, the single-unit looping page). Its description, switches, defaults, ramp plans and verification are in fix(backlog): explicit retry state for batch backlogs (core: class 1 retry cap, class 3 held re-drive budget, class 6 counter) #24936's body; nothing in it changed here.a8f3ad08ebf. Its only conflict was the generatedbackend/docs/feature-flag-registry.md, re-rendered from the mergedconfig/feature-flags.yaml: main's rows plus this branch's three switches.Product invariants affected
Those of #24936's reviewed core, unchanged (see #24936). The commit added on top is documentation, code comments and one unit test: no behavior, default or switch change.
Failure class (fixes)
Failure-Class: FC-state-deadline-without-reader-exit
Retry state in the batch and sync backlog paths lost its counters or never ended work. This core PR gives three classes their own counter or budget, each behind its own switch, with tests that run each switch on and off.
Known gaps
config/feature-flags.yamlis now qualified: re-quarantine after a class 3 grant depends on class 1 (CAPTURE_RETRY_CAP_ENFORCED) enforcing for the owner, and with class 1 off for an owner outside the served cohort, lease expiry defers instead, as on main. The test is not in this PR. Follow-up:lane/backlog-state-machine-followup(local, scope in the bus post).backend/database/sync_backfill_sequencer.py:947,dispatch_attemptreset to 0 on the running-lease path). Class 2 is out of this PR. Follow-up:lane/backlog-state-machine-followup.Why
The rollback text for class 1 (
CAPTURE_RETRY_CAP_ENFORCED) and class 3 (BATCH_HELD_REDRIVE_BUDGET_ENABLED) claimed every grant stays capped atMAX_ATTEMPTSafter a switch goes OFF. The code does not do that:expire_leasereads class 1 on each lease expiry, and with it off (owner outside the served cohort) the unit defers as on main and is not quarantined at the cap.Change
Rollback semantics, now stated the same way in
backend/utils/batch_pipeline/scheduler.pycomments, thebackend/docs/runbooks/backlog-state-machine.md"Turning it off" cells, and here:MAX_ATTEMPTSonly while the retry cap enforces for the owner (class 1 on, or the owner in the served cohort). With class 1 off, lease expiries defer, as on main.MAX_ATTEMPTSonly while the retry cap enforces for the owner (class 1 on, or the owner in the served cohort). With class 1 off, lease expiries defer, as on main.Tests
test_class_1_on_to_off_keeps_grants_quarantines_only_while_on_then_defersinbackend/tests/unit/test_backlog_state_machine.py, with class 1 switched mid-run:It passes on the current code (a regression pin). A temporary mutation that kept the cap enforcing after OFF (
enforced = enforceinutils/capture/retry_cap.py) made it fail: attempts[1, 2]instead of[1, 2, 3, 4]. The mutation was reverted and is not committed.🤖 Generated with Claude Code
Merged origin/main (no force) on m1-mac-studio per lead2 0dac49; pre-push hook ran on m1.
Pre-review fix batch A-F (lead2 7a3c9e); pre-push hook ran on m1
The batch changes runtime behavior; the earlier documentation-only scope statement describes the original head. Audio custody is retained and content/privacy ownership is verified before re-drive grants. Validation details below reflect hermetic tests; no production endpoints were called.
Validation on m1 (2026-11-10): 765 passed across ten backend/test.sh invocations with xdist and per-file sessions (121 state-machine, 62 scheduler, 42 held dead letter, 163 quarantine recovery, 85 intake, 108 input retention, 54 monitoring telemetry, 75 alert-rule contract, 27 provisioning, 28 alert backtest). Changed production files: pyright 0 errors. Registry check OK; all 19 runtime-image source contracts and all 45 local preflight checks passed. Shared checked() fence extraction preserves worker source closure. Endpoint routes are exercised hermetically with FastAPI TestClient; no live backend was started.
Dated evidence: backend/docs/listen_pusher_pipeline/changes/2026-11-10-backlog-redrive-fence-accounting.md.
Full pre-push hook passed on m1 at 2026-11-10T13:17:01.181572+00:00; complete push wall time 74.92s, exit 0. Hook evidence: 45 shared preflight checks, full backend pyright 0 errors, 297 hook-selected unit tests (121/62/42/18/54), OpenAPI compatibility/codegen and pinned formatting passed. Pushed earlier commit 9e593c9. No force push, no verification bypass, no merge.
P2 polling-status fix (2026-11-10): refresh the status snapshot from the successful re-drive transaction so ready units return queued with a 3000 ms poll hint; refused re-drives retain held status and 300000 ms polling. Added returned-status assertions and active-token/provider-route refusal coverage; backend/test.sh passed 312 tests across state machine, intake, scheduler and held dead letter.
CI fix (2026-11-10, m1-mac-studio): extract the unchanged ledger owner predicates into dependency-free
database/sync_ledger_ownership.pyand migrate all batch callers, cutting the scheduler recovery-fence import path intoutils.cloud_tasks; regenerate the GMP inventory withbackend/scripts/monitoring_gmp_shadow.py --inventory --output backend/charts/monitoring/gmp-query-migration-inventory.jsonto match the current 1h backlog alert. Contract tests remain unchanged.CI-fix validation on m1:
backend/scripts/run-unit-ci.sh --changed-files <PR changed paths> --shard 8/5passed all 345 file-isolated sessions (8,205 passed, 37 skipped). The whole shard was rerun withDYLD_LIBRARY_PATH=/opt/homebrew/libafter the first local run could not discover the installed libopus. Separately, everytest_runtime_image_contracts*.py, everytest_monitoring_gmp*.py, andtest_backlog_state_machine.pypassed (265 tests across four separate file sessions).make preflightpassed all 45 checks.Existing sync ownership/checkpoint and batch projection/artifact-missing regression tests also passed (139 tests across four isolated files).
Full-hook push passed for
6aa568fa0bc17ae0a4129463abdfb9d7d721ef7a: 45 PR checks, full backend Pyright (0 errors), hook-selected unit tests, OpenAPI/compatibility checks, and pinned formatting. The shared owner predicate has a public name for cross-module type checking. Final-head focused/ownership regression rerun: 404 passed in eight isolated files; final-head shard 5/8 rerun: 8,205 passed, 37 skipped in 345 isolated files. Failure-Class in the CI-fix commit:FC-runtime-image-boundary. No production endpoints were contacted.FIX-FIRST poll transaction-order fix (2026-11-10, m1-mac-studio):
Scheduler.redrive_in_transactionandrequeue_quarantined_in_transactionreturn the updated job plus its spent flag (RedriveResult | None).durable_statusbuilds the refreshed response from that returned job without a post-writetx.get. Queue append completes its queue/frontier/control reads before staging writes./redrive-deadand nightly/operator recovery keep boolean acceptance and emit the spent signal only from the successfully committed transaction result. The existing refused-redrive test is retained. A strict transaction regression raisesReadAfterWriteErroron every get after a put or patch and covers held-expired/historical jobs, below/at budget, and telemetry on/off. Fix commit class:FC-joined-writer-writes-before-transaction-reads. Pipeline note:backend/docs/listen_pusher_pipeline/changes/2026-11-10-backlog-poll-redrive-status.md.FIX-FIRST validation on m1:
backend/test.shpassed 483 tests across five separate file sessions: backlog state machine 131, intake 85, scheduler 62, held-dead-letter 42, quarantine recovery 163.backend/scripts/run-unit-ci.sh --changed-files <PR changed paths> --shard 8/5passed 8205 tests, 37 skipped across all 345 files, withDYLD_LIBRARY_PATH=/opt/homebrew/lib.make preflightpassed all 45 selected checks.FIX-FIRST published earlier commit
e98f7063a69fcc54fcafafac577205af729e8876. The full pre-push hook passed: 45 shared checks, full backend Pyright with 0 errors, hook-selected unit tests, runtime source closure, OpenAPI/client compatibility and pinned formatting. Negative control: restoring only the old polltx.getmade all eight strict regression cases fail withReadAfterWriteError: get after write: jobs/segment; after restoring the fix all eight passed. The source was restored exactly before publication. No force push, verification bypass, PR merge or production endpoint access.Shard-2 lifecycle CI fix (2026-11-10, m1-mac-studio): restore the original local
BATCH_PARTIAL_STATUS = 'partial'declaration and comment indatabase/sync_ledger.py, and import onlyledger_owner_matchesfrom the pure ownership module. The lifecycle scanner can again resolve the writer's literal alias; no contract test or lifecycle baseline changes. The ownership helper and GPU import boundary remain unchanged. This restores the unchanged value's source visibility, with no runtime state/value change; fix commit declaresFailure-Class: nonefor this CI-only correction.CI audit: run 42871725269, shard 2/8 has exactly one failed test:
test_no_undeclared_or_stale_lifecycle_field_builder[database/sync_ledger.py]. The other seven shards and guardrails passed. No tests directly importsync_ledger_ownership; the local ownership regression manifest conservatively follows static and literal dynamic imports to 873 unit/service/router test files, plus the runtime-image contract file.Shard-2 fix validation on m1:
backend/test.shpassed the lifecycle file alone (1,734 tests) and the complete ownership-import regression manifest plus runtime image contract (874 files; 28,323 passed, 64 skipped), using isolated pytest sessions. The unchanged authoritative runnerbackend/scripts/run-unit-ci.sh --changed-files <PR changed paths> --shard 8/2passed all 342 files (9,127 passed);--shard 8/5passed all 345 files (8,187 passed). Both usedDYLD_LIBRARY_PATH=/opt/homebrew/libfor the installed native Opus library.make preflightpassed all 45 checks.Shard-2 fix published earlier commit
9f7a6a07ea57ffd598121ec629300e0daf988c5a. Full pre-push hook passed: 45 shared checks, backend Pyright with 0 errors, hook-selected unit tests, runtime source closure, OpenAPI/client compatibility and pinned formatting. Shard 2: 9,127 pytest tests passed, 15 skipped; shard 5: 8,187 pytest tests passed, 37 skipped. The canonical shard-5 pytest count excludes 18 environment-validation checks printed inside another test, which were included in earlier 8,205 totals. No contract test or lifecycle baseline was changed. No force push, verification bypass, PR merge or production endpoint access.Review follow-up: multi-unit poll transaction buffering
Verified earlier commit
9f7a6a07ea57ffd598121ec629300e0daf988c5abefore creating a fresh task worktree; ranmake setuponly there.The review concern does not reproduce with the production transaction wrapper. The class is named
FirestoreTransaction(notBatchTransaction):backend/database/batch_pipeline_store.py:159-176buffers put/patch/defer_set,:281-282runs the complete callback before flush, and:220-241completes commit-fence reads before raw set/update calls.RecoveryFence.checked(backend/database/batch_pipeline_recovery_fence.py:28-82) only reads; scheduler requeue/redrive and queue append (backend/utils/batch_pipeline/scheduler.py:73-104,994-1042) use buffered puts. No raw transaction set/update or external document write joins these helpers. Privacy token minting, when enabled and eligible, schedules a delayed independent transaction (backend/database/batch_pipeline_privacy.py:426-478), not a write to the poll transaction.Added 12 two/three-unit poll cases using the real FirestoreStore, wrapper, recovery fence, scheduler and flush against the shared StrictFirestore raw transaction double. They demonstrate actual raw reads after earlier buffered puts, all candidate writes still buffered on entry to flush, and privacy reads during flush before raw writes. All-eligible and mixed active-token/receipt refusals verify refreshed status, queue head/tail/links, unchanged refused records, per-unit spent telemetry on/off, and a negative control that raw reads after flush raise ReadAfterWriteError. Kept the existing single-unit refusal and returned-job regressions; renamed the latter to distinguish its stronger wrapper-level constraint. No runtime ordering or flag changes are required. Commit declaration:
Failure-Class: none(evidence and regression coverage, no production read-after-write violation found).Validation: backlog state machine, intake, scheduler, held dead-letter, projection held dead-letter and quarantine recovery: 521 passed across six isolated files. CI runner shard 2/8: 342 files, 9,127 passed, 15 skipped; shard 5/8: 345 files, 8,187 passed, 37 skipped.
make preflightwith the saved PR body passed all 45 checks; Full publish hook passed (manifest checks, backend Pyright with zero errors, unit tests, runtime-image contracts, OpenAPI compatibility and formatting). Pushed head14752f01a0ba0e75cfb89642dd4187eddf0eea87; no main conflict or merge was needed.