Skip to content

test(batch): CI invariants for the 10-28 wedge classes (poison head, taxonomy, shard spread, boundary geometry, real claim) - #23946

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

Git-on-my-level merged 6 commits into
mainfrom
lane/simtests

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

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 ValueErrors, 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 fix(batch): hold structural record-target conflicts instead of wedging the owner chain #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 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 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 (fix: fence batch scheduler pulls and spread control shards #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 (fix(backend): clamp EOF VAD spans overrunning the admitted duration #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 fix(firestore): release the transaction retry deadline scope across Context boundaries #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 fix(backend): clamp EOF VAD spans overrunning the admitted duration #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.

…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 #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
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 #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 (#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.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 #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
@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-29T05:52:28.966572Z 9aead0e 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.

…ition

Luna round 1 (P1): the load phase sat outside the contract try, so a
corrupt committed artifact (invalid envelope, oversized body, bad
generation-pinned reference, undecodable JSON) raised ValueError before
the disposition and still wedged the chain head. A valid JSON body that
is not an object reached payload.get as an AttributeError with the same
effect.

Move the load inside the disposition scope and normalize a non-object
body to the contract ValueError. Two poison-head kinds pin it:
payload:corrupt-artifact and payload:non-object-result.

Failure-Class: FC-unresolved-head-blocks-projection
…facts

Luna round 2 (two P1s):

- The pre-loop contract catch lacked the payload_contract_violation gate:
  a contention-shaped ValueError surfacing through 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 the
  retryable outcome.
- A correctly-sized artifact with valid envelope but altered ciphertext
  fails AESGCM.decrypt as InvalidTag, not ValueError, and escaped the
  disposition. InvalidTag joins the contract class set
  (payload:tampered-artifact pins it); artifacts.py joined the taxonomy
  scan with PermissionError/TimeoutError documented as wait/transient.

Local verification: full CI changed-file shard (18 files) green under
backend/test.sh, duration guard clean.

Failure-Class: FC-unresolved-head-blocks-projection

@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: 9a9930ab4e

ℹ️ 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 +836 to +840
except ValueError as error:
# The committed result/manifest itself violates the contract: no
# retry can fix those bytes, and an unhandled raise would wedge
# every later capture behind this chain head.
self._quarantine_payload_contract(item, binding, policy, error)

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 Preserve contention retries in the result-loading catch

If Firestore contention exhausts retries during artifact authorization, this catch permanently quarantines a valid result. The production ArtifactStore.load_result and fetch_audio paths call batch_artifact_authorize (utils/batch_pipeline/retention.py), which uses @firestore.transactional and can raise the contention-shaped ValueError already recognized by payload_contract_violation. Unlike the later assignment catch, this handler never applies that discriminator, so a transient authorization failure advances the watermark and leaves the job recovery-held instead of retrying. Apply the contention exclusion here before persisting the quarantine disposition.

Useful? React with 👍 / 👎.

Comment on lines +26 to +28
body = ast.get_source_segment(source, node) or ''
if 'skip' in body:
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 Inspect skip decorators before counting real-claim tests

If the sole real-claim regression test is disabled with @pytest.mark.skip or @pytest.mark.skipif, this guard still passes: ast.get_source_segment(source, node) starts at the function definition and excludes its decorators, so the 'skip' check cannot see those markers. Adding a skip decorator to the existing test_real_claim_released_across_run_blocking_leaves_never_fails_the_task confirms that it still qualifies. Inspect node.decorator_list before counting the test so CI actually enforces the promised non-skipped real-claim coverage.

Useful? React with 👍 / 👎.

CI shards 4 and 6 tripped the fast-unit duration guard on the first
payload-tolerance case (1.19s) and the first poison-head conflict case
(1.12s): the lazy SUCCESS_PAYLOAD import pulled the projection graph, and
the assignment seam's monkeypatch string target resolved database.conversations,
inside those tests' call phases. Hoist both imports to module scope so
collection pays them; three consecutive guard runs on the two files and the
full changed-file shard stay green.
cProfile on the failing CI case shows the cost precisely: build_incoming's
function-level imports land in the first test that reaches them —
utils.stt.pre_recorded alone pulls the deepgram SDK (0.62s), plus
deterministic_minimum, models.conversation and sync.capture (~1.2s total).
Hoisting only database.conversations was not enough; CI shards 4/6 still
measured 1.09-1.19s CPU in the call phase. Import the full lazy set at
module scope in both new files so collection pays it; the changed-file
shard stays green with the duration guard clean.

@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: 9aead0e76f

ℹ️ 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 +1001 to +1002
session = session or self.store.session(item.segment_id, binding, self.clock(), policy=policy)
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 Update the required pipeline lifecycle documentation

This changes transcription lifecycle behavior: invalid committed payloads now advance the owner watermark, hold the job for recovery, and retain its audio instead of remaining pending. backend/AGENTS.md requires audio, transcription, and conversation-lifecycle changes to update backend/docs/listen_pusher_pipeline.mdx in the same PR, but this commit only updates CONTRACT.md. Document the new disposition and retry exclusion in the required pipeline guide.

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

Useful? React with 👍 / 👎.

if kind == 'payload:tampered-artifact':
# Authenticated decryption of altered ciphertext: InvalidTag, not
# ValueError (Luna round 2).
from cryptography.exceptions import InvalidTag

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 Move the new test imports to module scope

The new poison-head tests introduce imports inside functions, including this InvalidTag import and the conflict/contention imports in the matrix test. This violates the explicit import rule in backend/AGENTS.md, which requires all imports at module scope without a test exception. Move these newly added imports to the module's import section.

AGENTS.md reference: backend/AGENTS.md:L165-L167

Useful? React with 👍 / 👎.

@Git-on-my-level
Git-on-my-level merged commit ce20e1b into main Oct 29, 2026
56 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/simtests branch October 29, 2026 07:16
Git-on-my-level added a commit that referenced this pull request Oct 29, 2026
Sync #23948 with #23946 (simtests ce20e1b) and main after its delta
review, per lead ruling 5233f3: merge, no rebase.
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
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