Repository navigation
fix(backend): clamp EOF VAD spans overrunning the admitted duration - #23926
Conversation
The worker's fetch_decode check admits decoded audio up to 0.1s longer than the admitted capture, and vad_speech_spans rounds span edges to the decoded sample clock, so an EOF span can end past the admitted duration by up to that tolerance (e.g. admitted 1.00001s, 16001 decoded samples). Record-origin assign_parts validates those spans against the admitted clock, so such units failed 'ordered nonoverlapping VAD spans required' deterministically and could never project: the chronic driver of T3 batch projection wedges (~5k refusals on the 10-28 revision window; reentry29 probe 2026-10-28). projection_speech_spans now clamps an EOF overrun within the worker's own documented tolerance (0.1s plus one 16 kHz sample, the same bound validate_measured_vad accepts) and keeps rejecting genuine violations: overrun beyond tolerance, spans that degenerate under the clamp (start >= end), overlap, and negative bounds. speech_seconds counts the decoded-clock union (the worker sums the exact spans it emits), so the accounting fence compares the pre-clamp union and keeps its one-sample tolerance. Already-wedged units become projectable again on the next recovery sweep once this rides the backend-integration deploy; rollback is a plain revert.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f639bc77e4
ℹ️ 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".
| if end > duration: | ||
| if end - duration > VAD_EOF_OVERRUN_SECONDS or start >= duration: | ||
| raise ValueError('ordered nonoverlapping VAD spans required') | ||
| end = duration |
There was a problem hiding this comment.
Update the pipeline documentation for the EOF clock contract
This changes the transcription pipeline's accepted VAD contract: decoded-clock spans can now exceed the admitted duration, while speech accounting deliberately uses their pre-clamp lengths. The commit updates only the validator and tests, leaving backend/docs/listen_pusher_pipeline.mdx unchanged. backend/AGENTS.md explicitly requires audio and transcription changes to update that document “in the same PR.” Document the overrun tolerance, clamping behavior, and accounting distinction there so the required pipeline contract stays aligned with production behavior.
AGENTS.md reference: backend/AGENTS.md:L163-L163
Useful? React with 👍 / 👎.
…g the owner chain (#23932) fix(batch): hold structural record-target conflicts instead of wedging the owner chain RCA (reentry29 10-29, lane wedge7; lead accepted 01:44Z): the 7/8 post-deploy projection wedge was a head-of-line block. The wedged owner's projection watermark froze at log_sequence 12; the head row (backfill record unit, committed 21:27:37Z 10-28) fails assignment on every sweep with SyncAssignmentConflict('record target discarded') from utils/batch_pipeline/live_projection.py:24 (replace_record) — the target conversation is discarded. The projection walk does not handle that exception, so the whole per-owner capture-ordered chain — every later capture, including 7 units admitted after the vadclamp/shardfix worker — stays pending, and the catch-up depth cap sets a durable merge hold that also blocks the owner's result_ready commits. The sync taxonomy (utils/sync/assignment_errors.py) already classifies these subtypes: structural conflicts cannot be resolved by retrying; RECORD_TARGET_DISCARDED is awaiting-writer, structural for hours-old backfill rows. This change applies that strike rule at both record assignment seams in the projector: - structural conflicts, and awaiting-writer conflicts on catch-up rows (fresh_capture=false), persist the existing quarantined disposition (persist_disposition(session, quarantined=True)): a quarantine_held receipt, audio held with no TTL for the recovery redrive (a later restore of the discarded record upgrades through it), and — because a quarantined receipt is assignment progress — the owner projection watermark advances, so the chain unblocks. - fresh awaiting-writer conflicts keep waiting for their writer, per the taxonomy and the raise-site comment (a discarded record is restorable without a status change). Failure-Class: none The dominant class (an unresolvable per-owner conflict retried forever at the chain head, wedging every later capture) is not in the failure-class registry; no new class file is added here. Line-Count-Exception: backend/utils/batch_pipeline/projection.py | 1476 -> 1504 | lead-ruled fix (bus a71099, 10-29): strike-rule quarantine needs one 14-line helper plus one except clause at each of the two record assignment seams; splitting the frozen file is out of scope for a prod-wedge hotfix UI-Evidence: none -- reason: backend projection-lane change only; no web/admin/app files touched. Evidence: ro-prod Firestore chain walk (owner watermark seq 12, head seq 13 pending, 15 pending rows, merge hold held=true at depth 29) and backend-integration logs: SyncAssignmentConflict site=live_projection.py:24 ~140/h since 20:00Z, rising to ~1030/h after #23926 removed the earlier contracts.py:45 wall (dead since the 00:30Z roll: 6 residual). Local shard: backend/test.sh with BACKEND_UNIT_TEST_FILE_LIST over the five projection test files, all green (34+30+21+34+22 style counts, exit 0). Tests: blocked head unblocks (payloaded assign_parts path and the record-silence path); a fresh discarded target keeps waiting; a structural retired target quarantines even on fresh rows; a later pass leaves the held receipt intact for recovery. Review round 1 (Luna, FIX-FIRST) closed the loop the disposition must land in: the quarantined receipt is now written in the SAME transaction as a job `recovery_state: held` update (session persist), so the held-partial scan (`held_candidates`) and the reviewed redrive own the unit immediately, and the upload completes as a client partial instead of staying `processing`: `prepare_accounting(held=True)` and `complete_partial` skip an assignment-held sibling (`assignment_held_without_recovery`: quarantined replay-fenced receipt + recovery-held job + no open operator intent), counting it under `held_segments` with its audio and committed result kept. Restoring the record resumes through the existing operator redrive/disposition tools (scripts/batch_pipeline_held_disposition.py); automatic re-assignment on restore is deliberately not promised by this change. The second commit grandfathers test_flag_budget.py::test_helper_kill_switch_budget_entries_match_the_default_on_registry against the 1.00s CPU duration guard (1.05s on a loaded PR shard, main-side boundary test, assertions all pass; not a reroll). Retention safety for assignment-held units (lead condition, ruling of 02:40Z): no retention path sweeps or expires a quarantine_held unit's retained audio before a restore->redrive exists. - utils/batch_pipeline/retention.py:269 — expire_completed_segment arms expires_at/cleanup_after only when projection_state is in {ready, projected, completed}; a quarantine_held row returns False and nothing is ever armed on the job, result, intake or artifacts. - The ordinary completion path cannot arm it for an upload with an assignment-held sibling either: prepare_accounting returns None while any sibling receipt is non-ready, so complete_content takes the hold path and its retention loop never runs. - The path that does serve such uploads, Projector.complete_held, is explicit in its contract: "No provider call, no job/intent write and no retention: held audio stays for a reviewed redrive." - The recovery/failure artifact-retention branches in retention.py:141-209 (register_batch_artifact) apply only to worker-quarantined jobs (state == 'quarantined'); an assignment-held job stays committed, so no recovery TTL applies to it. - The only unconditional eraser is the privacy purge (database/batch_pipeline_purge.py purge_batch_owner) — deliberate immediate privacy erasure, unchanged here. - obligation_due_at (written onto quarantined receipts, batch_pipeline_projection_session.py:360) has no consumer besides its writers; it schedules nothing.
…ay (#23943) ## Problem and change Batch projection fixes have needed another production ramp to encounter deterministic unit-shape failures. Add a fixed offline adapter and `make batch-replay REF=<sha> BASE=<sha> CORPUS=<path> OUTPUT=<path>` so the lead can compare immutable product revisions before deploying. The adapter runs the real owner walk, VAD span validator, partition/build, assignment transaction planner against StrictFirestore targets, source-audio slicing against synthetic PCM, and follow-up claims with real fakeredis Lua across copied executor Contexts. It blocks outbound sockets, gRPC channels, and cloud client construction. Bridge/summary external effects are fake leaves. ## Capture allowlist and limits Read-only `ro-prod` capture selects numeric durations/VAD sample counts; owner/unit/content/conversation/predecessor/watermark/sibling identities; lane, state, attempts, retry presence, recovery state; and target lifecycle/route/privacy flags. It never requests whole `speech_spans` or `manifest.references` arrays: Firestore cannot mask element subfields, so requesting them could read nested text or paths. The exact RPC field projections are in `backend/testing/batch_replay/capture.py`, the README and each corpus. Geometry slots remain null; only synthetic inputs supply geometry. IDs are HMAC-SHA256 with a fresh private corpus salt. No transcript, audio, names, emails, URIs, or error messages are persisted. Corpus/salt stay mode 0600 under a 0700 scratch directory, outside Git. Live capture contains 2,000 units. All 2,000 lack decoded durations, VAD span arrays and manifest geometry in Firestore. Lead ruling `a76a1a` explicitly forbids artifact export/decryption and accepts Firestore chain/state/assignment structures plus labelled synthetic geometry. The normal gate always adds the incident fixture and a duration-quantile boundary matrix (EOF minus/exact/plus one sample, invalid VAD overrun, first/last valid slices and invalid source/capture slices). Invalid shapes must be rejected. Reports name `coverage_scope=firestore-structure+synthetic-boundaries` and retain all missing captured geometry in `coverage_limits`. Optional strict captured-geometry mode fails those gaps. This PASS cannot claim replay of captured audio/VAD geometry. The follow-up corpus includes one-hop redirect-target lifecycle states. Delete private corpus/salt after the program (David ruling `a5c4f6`); lead owns that handoff. Tracked in anx `card:batch-replay-gate-20261029`. No production deploy or data mutation is part of this PR. ## Validation - Targeted backend shard: `BACKEND_UNIT_TEST_FILE_LIST=/Volumes/Ephemeral/scratch/replay/unit-files.txt BACKEND_PYTEST_WORKERS=4 bash backend/test.sh`, through `omi-heavy` and `nice -n 19`. - Historical synthetic corpus: baseline `7bc941c43d57409f02ce2d18c18bfa3eee7c8db1` reproduces the one-sample EOF VAD ValueError and discarded-backfill owner-chain block; main `91d5616fa922e8f77fe02dbea40fa85ef8f45f1e` clears those with #23926/#23932. The corpus also exercises cross-Context follow-up claim release (#23928). - Real-corpus initial strict gate vs `7bc941c`: zero new exception sites or blocked units; FAIL for missing geometry. Subsequent accepted-scope gate adds mandatory synthetic distributions and captures referenced redirect states. Reports stay under `/Volumes/Ephemeral/scratch/replay/` (private local artifacts). Gate fails new exception sites, regressions on previously exercised units, newly blocked units, synthetic oracle/incident failures, or missing structural coverage. Fixing a head can expose a known downstream conflict on an already-blocked baseline unit; that is recorded separately, while new classes/sites always fail. No `.github/` change. Lead owns merges/deploys; one Luna review round is required. ## Review fixes The first Luna review requested a tighter read boundary and dispatch/verdict fidelity. Capture now excludes whole geometry arrays at the RPC mask and never inspects them in sanitization. Unknown outcomes, terminal-empty results without proof, and unknown lanes block replay as coverage gaps. Both main-corpus and incident boundary lists are checked explicitly, independently of exception flattening. Quantiles retain observed duration frequency, and per-unit exception counters catch repeated failures at an existing site. Targeted regressions cover all six review findings; round two is limited to this delta.
…taxonomy, shard spread, boundary geometry, real claim) (#23946) ## Summary David, 10-29 (simtests lane): tonight's batch wedges were deterministic and testable, but no test covered the property that failed. This PR adds the five CI invariants from tonight's brief, wired into the existing backend unit suite (no new workflow), plus the minimal product fix one of them demands. **The wedge class still live on main:** a committed result or manifest that violates the payload contract raised `ValueError` through `assign_parts` with no disposition. The owner-chain walk retries a chain head forever, so a permanently invalid payload at the head froze every later capture behind it — the same head-of-line shape as #23932's unhandled record-target conflict, and the deterministic driver behind the #23926 EOF-span refusals (4,952 refusals on one revision). The fix takes the held disposition for the closed set of payload-contract `ValueError`s, exactly like a structural assignment conflict: quarantine receipt, watermark advance, recovery owns the unit, audio retained. The Firestore commit-contention `ValueError` shape stays retryable. ## The five invariants 1. **Poison-head matrix** (`test_pipeline_sim_poison_head.py`): for every failure kind the projection walk can raise — all 16 bounded assignment-conflict subtypes plus the unlabeled fallback, five payload-contract `ValueError` sites (duration mismatch, split duration, no words, missing VAD spans, corrupt source manifest), the contention-shaped `ValueError`, ambiguous generation, and a busy claim — inject it permanently at an owner's chain head. Advancing kinds quarantine-hold within K=2 walk attempts (watermark moves, later units project, audio retained); wait kinds stay in a bounded, observable pending state. Would have caught #23932 and the payload wedge. 2. **Exception-taxonomy coverage contract** (`test_batch_projection_exception_taxonomy.py`): AST-scans the walk's callee modules for constructor-raise sites; a new raise class without a `TAXONOMY` disposition fails the suite with instructions, and every injectable kind must appear in the poison-head matrix. Also pins the strike-rule sets (the one deliberately unclassified subtype, `bridge_source_not_tombstone`, waits on every lane). 3. **Multi-worker shard-spread sim** (`test_batch_pipeline_shard_spread.py`): `SpreadMemoryStore` models the real spread-mode candidate semantics (service primary, worker affinity on ties, exclusions, pull claims) plus Firestore write-write behavior — a control write on a shard committed by another puller after this puller's candidate read aborts. Six real `Scheduler`s over twelve shards from a shared per-round snapshot: writes spread (no shard > 2x mean, no round piles onto one document), every job leases exactly once with unique tokens, claims fence every pull, and stale-write contention stays far under the legacy no-affinity shape (measured 24 vs 240 aborts on this workload). Invisible with one simulated worker (#23927). 4. **Boundary-geometry property tests** (`test_batch_pipeline_boundary_geometry.py`): the ±1-sample boundaries of every duration fence — EOF VAD spans at each sample of the decode tolerance (#23926), measured-VAD tolerance, bound worker receipts, word clocks at EOF, manifest slices at the capture edge, and the projection payload's 0.1 s duration tolerance including its deterministic float asymmetries (nominal −0.1 s passes where +0.1 s rejects, one float ulp past the fence). 5. **Real-claim rule** (`test_projection_followup_real_claim_rule.py`): the projection_followup suite must keep at least one non-skipped test exercising the REAL `projection_claim` against fakeredis — the stubbed claim hid #23928's cross-Context token reset. ## Self-testing (definition of done) Layer: backend unit shard — the exact CI changed-file selection from `scripts/select_backend_unit_tests.py` for this diff (18 files, including the Firestore guard set the selector attaches to the `projection.py` change): ``` BACKEND_UNIT_TEST_FILE_LIST=<selection> BACKEND_PYTEST_WORKERS=4 bash backend/test.sh # green, exit 0, duration guard clean ``` Discrimination evidence (each invariant fails against the bug it exists for): - poison-head payload kinds fail without the parent fix's disposition; - the shard-spread sim was measured against `BATCH_SHARD_SPREAD_ENABLED=false`: 240 stale-write aborts and 49 one-lease rounds vs 24 aborts and 13 rounds with spread — the legacy flag also zeroes the claim counter; - the boundary sweep pins the exact clamp/reject sample where #23926's fence flipped. ## Review Round 1 (Luna, FIX-FIRST) — one P1: the result-load phase sat outside the disposition, so a corrupt committed artifact (invalid envelope, oversized body, bad reference — or valid JSON that is not an object reaching `payload.get` as an `AttributeError`) still wedged the chain head. Fixed: the load phase is inside the contract try, and a non-object body is normalized to the contract `ValueError`. Two new poison-head kinds pin it (`payload:corrupt-artifact`, `payload:non-object-result`). Round 2 (Luna, FIX-FIRST) — two P1s, both fixed: - The pre-loop catch lacked the `payload_contract_violation` gate: a contention-shaped `ValueError` from the load seam's Firestore-backed authorization would have quarantined a valid capture. Both catches now gate through the discriminator, and the `contention-value-error` poison kind injects at the load seam to pin it. - A correctly-sized artifact with altered ciphertext fails `AESGCM.decrypt` as `InvalidTag`, not `ValueError` — it escaped the disposition. `InvalidTag` is now part of the contract class set (`payload:tampered-artifact` pins it; the unit-level discriminator test asserts it). `artifacts.py` joined the taxonomy scan; `PermissionError`/`TimeoutError` entries document the authorization-wait and transient classes. Failure-Class: FC-unresolved-head-blocks-projection Line-Count-Exception: backend/utils/batch_pipeline/projection.py | 1504 -> 1558 | payload-contract quarantine disposition: one discriminator helper plus one catch per assign path section, mirroring the #23932 structural-conflict handlers; review rounds added the load-phase cover and the InvalidTag class UI-Evidence: none -- reason: no web/admin/app paths touched.
Tonight's batch failures were deterministic and testable, but no test covered the property that failed. Five invariants, wired into the existing backend unit suite (no new workflow): 1. Poison-head matrix (test_pipeline_sim_poison_head.py): for every failure kind the projection walk can raise — all 16 assignment-conflict subtypes plus the unlabeled fallback, five payload-contract ValueErrors, contention-shaped ValueError, ambiguous generation, busy claim — inject it permanently at an owner's chain head. Advancing kinds quarantine-hold within K=2 walk attempts (watermark moves, later units project, audio retained); wait kinds stay in a bounded, observable pending state. Would have caught BasedHardware#23932 and the payload wedge fixed in the parent commit. 2. Exception-taxonomy coverage contract (test_batch_projection_exception_taxonomy.py): AST-scans the walk's callee modules for constructor-raise sites; a new raise class without a TAXONOMY disposition fails the suite, and every injectable kind must appear in the poison-head matrix. 3. Multi-worker shard-spread sim (test_batch_pipeline_shard_spread.py): SpreadMemoryStore models the real candidate semantics (service primary, worker affinity on ties, exclusions, pull claims) plus Firestore write-write behavior (a control write on a shard committed after the puller's candidate read aborts). Six real Schedulers over twelve shards from a shared per-round snapshot: writes spread (no shard > 2x mean, no round piles onto one document), every job leases exactly once, claims fence every pull, stale-write contention stays far under the legacy no-affinity shape (measured 24 vs 240 on this workload). Invisible with one simulated worker (BasedHardware#23927). 4. Boundary-geometry property tests (test_batch_pipeline_boundary_geometry.py): the +-1-sample boundaries of every duration fence — EOF VAD spans at each sample of the decode tolerance (BasedHardware#23926), measured-VAD tolerance, bound worker receipts, word clocks at EOF, manifest slices at the capture edge, and the projection payload's 0.1s duration tolerance including its deterministic float asymmetries (0.9 passes where 1.1 rejects). 5. Real-claim rule (test_projection_followup_real_claim_rule.py): the projection_followup suite must keep at least one non-skipped test exercising the REAL projection_claim against fakeredis — the stubbed claim hid BasedHardware#23928's cross-Context token reset. Local verification (layer: backend unit shard, the exact CI changed-file selection from scripts/select_backend_unit_tests.py for this diff — 18 files): BACKEND_UNIT_TEST_FILE_LIST=<selection> bash backend/test.sh — green, duration guard clean. Failure-Class: FC-unresolved-head-blocks-projection
Summary
projection_speech_spansrequired every VAD span to satisfyend <= durationwheredurationis the admitted clock, but the worker emits spans on the decoded sample clock. The worker's ownfetch_decodecheck (backend/diarizer/batch_pipeline.py:703-707) accepts decoded audio up to 0.1s longer than the admitted capture, andvad_speech_spans(backend/diarizer/batch_pipeline.py:205-215) rounds/clips span edges to the decoded sample count. A span that ends at decoded EOF can therefore pass every worker check and still fail projection validation — deterministically, so the unit can never project and wedges forever. This was the chronic driver of T3 batch projection wedges: ~4,952contracts.py:45refusals on revision backend-integration-01404 between 16:00-20:16Z on 2026-10-28, and 1,173 assignment ValueErrors in the 21:40-22:33Z window (reentry29 probe, refsswarm/state/refs/1028-13ae93.txtandreentry29-operator-2026-10-28.md).Reproduction from the reentry29 synthetic probe: admitted
1.00001s, decoded16001samples =1.0000625s, VAD span ending at decoded EOF — worker 0.1s check accepts, admitted-clock projection refusesordered nonoverlapping VAD spans required.Change
In
backend/utils/batch_pipeline/contracts.py:VAD_EOF_OVERRUN_SECONDS = 0.1 + 1/16000is clamped todurationinstead of rejected. The bound is the worker's own documented metadata tolerance: thefetch_decodecheck cited above plus one 16 kHz sample for the sample-rounded span edge — exactly the boundvalidate_measured_vadin the same file already accepts for decoded-clock speech seconds.start >= endafter clamping, i.e. anything starting at/past the admitted duration), overlap (start < previous_endagainst the emitted previous end), negative/non-finite/non-numeric spans, unordered spans. All rejections keep the same message as before, so anything still failing looks identical in logs.speech_secondsaccounting fence is unchanged in strength: the worker computesspeech_secondsas the exact sum of the decoded-clock spans it emits (backend/diarizer/batch_pipeline.py:808), so the check compares that pre-clamp union at the same one-sample (1/16000 + 1e-9) tolerance. Clamping cannot manufacture or mask an accounting disagreement.Only the record-origin site (
projection.py:778,assign_partsvsitem.duration_seconds) compares across clocks; every other caller passes the payload's ownaudio_seconds, where spans are already in bounds and the clamp never triggers.Tests (
tests/unit/test_batch_pipeline_projection.py)1.00001s, 16001-sample decoded EOF span clamps to the admitted duration; the worker's exact 0.1s boundary also clampsLocal verification (layer: backend unit shard, exactly the CI changed-file selection from
scripts/select_backend_unit_tests.pyfor this diff — 15 files):Recovery note
No data change: already-wedged units carry valid worker payloads and become projectable again on the next recovery sweep once this rides the backend-integration deploy (projection runs there); the lead triggers that sweep.
Rollback
No kill switch needed — this narrows a validator to its documented intent and only converts deterministic rejections into clamped acceptance within the producer's own tolerance. Rollback is a plain revert of this commit.
Failure-Class: none
This is a first-of-class batch-pipeline clock-contract failure (decoded-clock spans validated against an admitted-clock bound); the guard surface is the four new tests in this PR. The nearest defined family,
FC-transcript-and-audio-on-independent-clocks, is scoped to live-listen placement and its prevention artifacts do not cover this surface, so it is not declared as a recurrence.