Skip to content

fix(batch): hold structural record-target conflicts instead of wedging the owner chain - #23932

Merged
Git-on-my-level merged 2 commits into
mainfrom
lane/wedge7
Oct 29, 2026
Merged

Git-on-my-level merged 2 commits into
mainfrom
lane/wedge7

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Oct 29, 2026 •

Copy link
Copy Markdown
Member

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.

…g the owner chain

A discarded record target raises SyncAssignmentConflict from
replace_record; the projection walk does not handle it, so the owner's
chain head errors on every sweep and every later capture for that owner
stays pending (reentry29 10-29: watermark frozen at log_sequence 12,
15 pending rows, T3 wedge on 7 new units, durable merge hold at the
catch-up depth cap).

Apply the sync strike rule at both record assignment seams: structural
conflicts, and awaiting-writer conflicts on catch-up rows, persist the
existing quarantined disposition — quarantine_held receipt, audio held
for the recovery redrive, watermark advanced so the chain unblocks.
Fresh awaiting-writer conflicts keep waiting for their writer.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 29, 2026 •

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-29T02:35:17.819638Z 933c6b2 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: 2b3efea916

ℹ️ 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 +931 to +934
except SyncAssignmentConflict as error:
if not quarantines_assignment_conflict(error, job):
raise
receipt = persist_disposition(session, quarantined=True)

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 Document the new record-conflict quarantine lifecycle

This changes conversation projection from retrying record-target conflicts to durably withholding their text and advancing the owner watermark, but the required backend/docs/listen_pusher_pipeline.mdx update is absent. Its linked backend/docs/runbooks/batch-projection-repair.md still states that only ProjectionGenerationAmbiguous creates this disposition. Update the pipeline documentation and linked recovery guidance to distinguish structural conflicts from fresh/backfill awaiting-writer conflicts and explain the retained recovery obligation. backend/AGENTS.md explicitly requires the pipeline document to change in the same PR for conversation-lifecycle changes.

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

Useful? React with 👍 / 👎.

…U duration guard

The 1.00s per-test CPU guard failed PR-shard 6 on
test_helper_kill_switch_budget_entries_match_the_default_on_registry at
1.05s (PR #23932, 2026-10-29): a main-side boundary test whose cost is
import amortization under file isolation, unrelated to the lane's diff.
Grandfather it like the other boundary entries; no reroll.

@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: 933c6b20bd

ℹ️ 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 +702 to +704
if entry and assignment_held_without_recovery(job, entry):
held += 1
continue

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 Preserve successful parts when completing a quarantined result

For a multipart result with both a quarantined part and successfully assigned parts, ProjectionSession.persist marks the summary quarantined and now sets the job's recovery state to held. This branch then skips the entire result, including its successful projection_parts. Consequently, complete_partial omits those conversations from new_memories/updated_memories, and the matching skip in prepare_accounting excludes their successfully projected speech from usage. Process the individual parts instead: retain ready parts for publication and accounting, wait for unfinished follow-ups, and count only quarantined parts as held.

Useful? React with 👍 / 👎.

@Git-on-my-level
Git-on-my-level merged commit 91d5616 into main Oct 29, 2026
70 of 74 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/wedge7 branch October 29, 2026 03:22
Git-on-my-level added a commit that referenced this pull request Oct 29, 2026
…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.
Git-on-my-level added a commit that referenced this pull request Oct 29, 2026
…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.
Git-on-my-level added a commit that referenced this pull request Oct 29, 2026
…rgets (#23948)

## What

Two stacked pieces on top of #23946 (per lead ruling 0babf0 — no
duplication
of its seam-level payload-contract hold):

1. **The generic poison-head rule at the walk/sweep level** (lead ruling
   5d2ae7), composed with #23946's `payload_contract_violation`: any
**non-transient** exception that *escapes the seams* at an owner-chain
head
(unknown bugs — TypeError/KeyError/…, contract ValueErrors raised
outside
`assign_parts`' catch, structural conflicts) takes the held disposition
—
`quarantine_held` receipt, audio retained, watermark advanced — and the
   chain moves on. **Transient** failures (Firestore/API contention and
availability: Aborted, ServiceUnavailable, BadGateway, DeadlineExceeded,
TooManyRequests, ResourceExhausted, InternalServerError, GatewayTimeout,
network errors, contention-shaped ValueError) and fresh awaiting-writer
   conflicts keep retrying under a **durable bound**
(`projection_blocked_since`, 24h), after which they too hold. Applies at
   `_walk_rows` and the sweep's page rows alike.

2. **Restore → redrive** (ruling 7a09a7): a bounded maintenance scan
(one
page per 15 min tick, keyset cursor, leader-gated) re-examines held
units;
   when a discarded record target is genuinely restored (mirroring
   `replace_record`'s own fences), the row resets to `pending` with
`projection_redriven_at` and assignment re-runs. A redriven unit
persists
without dragging the owner watermark backward onto already-terminal
rows,
   and the predecessor fence accepts its one sanctioned out-of-order
re-assignment. This is the recovery path for every held unit — #23932's
   conflicts, #23946's payload holds, and this rule's holds alike.

Deliberate limits: `ProjectionBlocked`/`BatchPrivacyBlocked` keep their
existing semantics (shadow refusal must never hold; privacy has its own
machinery). The seam dispositions (#23932 strike rule, #23946 payload
contract) stay; this rule is the floor beneath them.

## Why

reentry29 10-29: a discarded record target froze an owner's watermark
for 6h;
#23932 fixed that seam, but its fresh-lane keep-waiting design still
retries
forever (~500/h live), and #23946 covers only ValueError/InvalidTag at
the
assign seams. Post-#23932 readback (owner hash 75235644, 04:2xZ):
watermark
12 → 39, zero pending — the wedge shape is gone; this PR makes that
guaranteed for every escaping exception class, bounded, and recoverable.

## Held audio is never swept before redrive (extends the 8f792d
condition)

- `expire_completed_segment` arms cleanup only for `projection_state in
{ready, projected, completed}`
(`utils/batch_pipeline/retention.py:269`);
  `quarantine_held` rows never receive expiry receipts, and
  `cleanup_completed_artifacts` deletes only due or erasure-requested
  artifacts.
- The held disposition holds the job (`recovery_state=held`) in the same
transaction as the receipt; `quarantine_job` documents "quarantine never
  deletes encrypted source material".
- `complete_held` performs "no retention: held audio stays for a
reviewed
  redrive".
- The release redrive touches only receipt/disposition fields;
`audio_uri`
  is untouched (asserted in tests).

## Notes for the lead

- Stacked on #23946 (merge commit; no force-push); merge #23946 first,
this
  PR's diff then collapses to its own additions.
- No flag, no env key, no `.github`/chart/workflow change. Normal
backend
  train; no deploy of mine.
- Predeploy `make batch-replay`: candidate should show *fewer* walk
exceptions and held heads where the baseline wedged (held heads unblock
  followers) — direction of fix, not newly-blocked units.
- Review r1 P1 (BadGateway 502 not transient → non-record units held
with no
  redrive target) fixed + classification matrix added.

## Tests

- classification matrix: availability errors retry (incl. BadGateway),
bugs
  and contract violations hold
- generic poison head (TypeError at the head) holds, advances the
watermark,
later rows project; held rows never arm retention; sweep page rows same
- transient retries within the bound; stamp written once per episode;
past
  the bound the same failure holds
- fresh awaiting-writer conflict keeps waiting, then holds at the bound
- release: refuses still-discarded/deleted/unfinalized targets and every
non-held shape; resets a restored target (receipt, lineage fence, bound
  stamp cleared; job released; audio untouched; watermark unmoved);
  idempotent; scan cursor wraps
- redriven re-assignment persists without regressing the watermark
- #23946's poison-head matrix, taxonomy and boundary-geometry invariants
stay
  green with this rule composed in (verified on the merged branch)

Local: 10-file merged shard via `test.sh` green; 21+6-file shards green
pre-merge; broader 477-test batch set green; query-shapes and
field-index
tests green with the new driver entries.

Failure-Class: none

Line-Count-Exception: backend/utils/batch_pipeline/projection.py | 1504
-> 1716 | #23946's seam-level payload hold (absorbed into this stacked
PR) plus the walk/sweep-level poison-head rule composed with it, and the
release scan hook
YinkaAdepoju pushed a commit to YinkaAdepoju/omi that referenced this pull request Oct 29, 2026
…wner chain

A committed result or manifest that violates the payload contract (VAD
spans, split geometry, word bounding, source decode, duration tolerance)
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 wedge
shape as BasedHardware#23932's unhandled record-target conflict.

Take the held disposition for the closed set of payload-contract
ValueErrors, exactly like a structural assignment conflict: quarantine
receipt, watermark advance, recovery owns the unit, audio retained. The
Firestore commit-contention ValueError ('Failed to commit transaction...'
chained from Aborted) is a ValueError that must stay retryable;
payload_contract_violation excludes that shape via error_type.

Failure-Class: FC-unresolved-head-blocks-projection
YinkaAdepoju pushed a commit to YinkaAdepoju/omi that referenced this pull request Oct 29, 2026
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
ocakciomursel-pixel pushed a commit to ocakciomursel-pixel/omi that referenced this pull request Oct 29, 2026
…rgets

The owner-chain walk retries a failing head forever, so any exception the
per-exception seams do not catch wedges every later capture behind it
(reentry29 10-29: watermark frozen for 6h; the fresh awaiting-writer
conflict stream still errors ~500/h after BasedHardware#23932 by design).

One generic rule now covers every seam the precise dispositions do not
(lead ruling 5d2ae7): a non-transient exception at a chain head takes the
held disposition - quarantine_held receipt, audio retained, watermark
advanced - and the chain moves on. Transient infrastructure errors and
fresh awaiting-writer conflicts keep retrying under a durable bound
(projection_blocked_since; 24h) after which they too hold. The walk and
the sweep page both apply it.

Restore->redrive closes the loop: a bounded maintenance scan re-examines
held units and, when the discarded record target is really restored,
resets the row to pending (projection_redriven_at) so assignment re-runs.
A redriven unit persists without dragging the owner watermark backward,
and the predecessor fence accepts its one sanctioned out-of-order
re-assignment.
Git-on-my-level added a commit that referenced this pull request Nov 2, 2026
…ch (#24320)

## Why

The prod quarantine-recovery sweep logs ~75
`event=batch_quarantine_recovery outcome=held` lines a minute
(backend-integration, 00:35–00:45Z 11-02: 744 held, 5 queued, 0
`action=dispatch` exception lines). These lines are not dispatch
exceptions. They are the sweep's per-candidate outcome summary.

Cause: since #23932 (10-29), `ProjectionSession.persist` marks a
committed job whose projection is quarantine-held with
`recovery_state=held`, so the held-partial scan owns it.
`recovery_candidates()` selects `recovery_state in [held, prepared,
running]` without the job state. Those committed jobs fill the dispatch
page, and `RecoveryStore.prepare()` refuses each one because `state !=
'quarantined'`.

Measured at 00:47Z (Firestore COUNT, ro-prod, counts only):

| | count |
|---|---:|
| `recovery_state=held` | 5,400 |
| … of which `state=committed` | **5,289** |
| … of which `state=quarantined` | 111 |
| quarantined `prepared` / `running` | 8 / 1 |

At `BATCH_PIPELINE_RECOVERY_DISPATCH_BATCH_SIZE=64` on the maintenance
leader, one full scan takes about 72 minutes, and the cursor is per
instance, so a leader change restarts it. Real quarantined units,
including language-guarded ones, wait that long before getting their
first recovery intent. None of the 111 has an intent today, and some
have waited for up to a day. Their siblings' conversations wait with
them (the T3 quarantine-held backlog). The committed-held stock grows by
about 1.3k a day at the current batch share.

## What

Add `state == 'quarantined'` to `recovery_candidates()`. `prepare()`
already requires that state, so no unit that could be dispatched is
dropped. All filters are equalities, so Firestore serves the query by
single-field index merging: probed against prod, `state==quarantined AND
recovery_state IN [...] ORDER BY __name__` returned 120 rows with no
index error. The sim model and the emulator sweep test now model the
state.

## Risk

- Behaviour changes only for jobs that `prepare()` already refuses. The
held-partial scan (`held_candidates`) is unchanged.
- No new flag. No index, schema or data change.
- Rollback: redeploy the previous image.

## Verification

- New unit test
`test_recovery_candidates_skip_committed_units_held_by_projection`: it
**fails before the fix** (1 failed, 135 passed) and passes after.
- Through `bin/omi-heavy`, nice 19, with ambient GCP credentials unset,
`backend/test.sh` ran 7 files: quarantine recovery, Firestore query
shapes, outside-query contract, query contract, pipeline sim,
characterization and owner drain. **824 passed, 0 failed.** Layer:
backend unit tests, hermetic.
- The emulator integration test
`test_global_recovery_sweep_advances_past_held_pages_without_extra_query`
gains a committed-held row. It was not run locally (no emulator); CI
runs it.
- Deploy: a backend-integration release (the recovery sweep's
maintenance leader) and the same image on serving. Lead's train.

Readout after deploy (backend-integration logs, counts only):
`outcome=held` lines should fall from ~75/min to roughly the real held
set per pass, `queued` should spike once as the 111 units get intents,
and quarantined `recovery_state=held` should drain within minutes,
except units held by design (cap or allowance, guarded zero-VAD).

Failure-Class: FC-batch-fault-domain-head-of-line-poison

🤖 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/24320?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/24320?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F24320&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. -->
MichaelC001 pushed a commit to MichaelC001/omi that referenced this pull request Nov 2, 2026
Since BasedHardware#23932 (10-29), a quarantine-held projection marks its committed job
recovery_state=held so the held-partial scan owns it. recovery_candidates()
matched recovery_state in held/prepared/running without the job state, so
those committed jobs (5,289 in prod at 00:47Z, against 120 real quarantined
candidates) filled the dispatch page. prepare() refuses every one of them,
the sweep logged ~75 outcome=held lines a minute, and real quarantined units
waited a full scan cycle (~72 min, longer across leader changes) before their
first recovery intent.

Add state == 'quarantined' to the query. All filters are equalities, so
Firestore serves it by single-field index merging (probed against prod, no
composite index). prepare() already requires state == 'quarantined', so no
dispatchable unit is dropped.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Git-on-my-level added a commit that referenced this pull request Nov 2, 2026
## Why

#24335 found three `durable_status` branches that told phones
`completed` while batch units were still held. Released phones read
`completed` as permission to mark the WAL synced and later age-delete
their only independent copy. Each branch was found by reading code,
about 12 days after it shipped (lane `artifactmissing`; risk review E4).
A golden per branch would not catch a fourth.

## What

Tests only. No runtime change.

- **Backend property test**
(`backend/tests/unit/test_batch_pipeline_custody_property.py`). It
enumerates every per-unit job state:
  - in flight (`ready`/`leased`/`retry`/`result_ready`);
  - committed, committed-but-held (#23932) and committed-recovered;
  - each quarantine recovery state;
- an open operator intent (`speech_redrive`, `terminal_disposition`,
`silence_disposition`).

It covers one-unit uploads and unordered two-unit pairs
(`durable_status` has no order dependence), beside every ledger shape
(as admitted, partial, `completed` with `held_audio`, valid `completed`)
and both settings of `BATCH_PIPELINE_HELD_TERMINAL_STATUS_ENABLED`. It
asserts the answer is `completed` only when every unit is committed with
no recovery or operator work owed.
- **Shared fixture**
(`backend/tests/fixtures/custody_status_shapes.json`). It pins every
`(status, reason_code, poll_after_ms)` the sweep produces, split into
resolved and unresolved. A new backend answer fails the backend test
until it is added there.
- **Phone test** (`app/test/unit/custody_status_shapes_test.dart`). It
replays each unresolved answer through `syncJobTerminalPolicy` and real
`LocalWalSyncImpl` reconciliation, and checks that a 14-day-old WAL is
never acknowledged, never marked synced and never age-evicted. Only the
resolved `completed` answer may acknowledge.
- A one-paragraph pointer in `CONTRACT.md` and a `kind:none` mobile
changelog fragment.

**Assumption, stated in the test:** a valid `completed` ledger is the
projection's own all-units receipt, and is authoritative over job rows
(`test_status_is_durable_and_completed_result_is_authoritative`). It is
paired only with all-terminal units. If projection ever wrote
`completed` early, this test would not see it; that needs its own
projection-side property.

## Fail-first evidence

- The backend property test was run against the pre-#24335
`backend/utils/batch_pipeline/intake.py` (`f520a2c92e687`, swapped in
locally, then restored). It **fails**: 175 unresolved uploads answered
`completed` with the switch on, and 165 with it off. That covers the
partial-ledger branch and `_held_status`.
- The phone test with the pre-#24335 answer
(`completed`/`batch_unit_held`/0) added to the unresolved fixture
**fails** on both the policy check and real reconciliation (1
acknowledgement where 0 is expected).

## Verification (layer: local unit tests, this head)

- `backend/test.sh` with
`BACKEND_UNIT_TEST_FILE_LIST=tests/unit/test_batch_pipeline_custody_property.py`,
via `bin/omi-heavy`, nice 19: **3 passed**. CPU time is about 0.4 s per
sweep, under the 1.0 s guard; the sweep is cached between tests.
- `flutter test test/unit/custody_status_shapes_test.dart
test/unit/held_partial_custody_test.dart
test/unit/sync_job_terminal_policy_test.dart`: **18 passed**.

Deploy: none (tests only).

Product invariants: INV-DATA-1.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
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