Skip to content

harden(backend): require reader contracts for durable batch state - #25210

Open
Git-on-my-level wants to merge 8 commits into
mainfrom
agent/m1-studio-codex-sol/4efb2acec92d
Open

Git-on-my-level wants to merge 8 commits into
mainfrom
agent/m1-studio-codex-sol/4efb2acec92d

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

What changed and why

Adds a durable batch-state reader registry and an offline AST guard after SCA-1894: a new ready_at stamp released backlog on an independently deployed older GPU worker, while the admission switch was on another service.

The registry names the GPU worker, shared API deployment envelope, minimum source commits, and the service honoring each containment flag. It inventories buffered job-store writes, literal Firestore payloads, unit fields, recovery queues, artifact prefixes and admission/serving/worker flags. Existing backend unit selection and the local/CI check manifest run the guard; no workflow or production behavior changes.

Review round 1 (2026-11-26) closed two gaps:

  • Collection identity. Coverage reduced every registry key to its final field suffix, so a new collection writing a field name another collection already registered (for example state) inherited that collection's reader contract. It now compares the full collection.field identity, maps the job store's nested content/conversations tables to their user-scoped collections, folds dotted update paths to their top-level field, and ignores in-memory cache.update(other) merges. A collision probe covers the failure.
  • Merge-tree drift. The gate was red on the PR merge tree for writes that landed on main after the 2026-11-13 seed. Those are now registered with their collection's custody envelope, including the after/complete projection clock markers and provider admission's late_upload; new collections since the seed (allowance holds, backlog release meter, merge-discovery cursor, source-alias projections, conversation batch-purge obligations) have their own entries. origin/main is merged in, so backend/AGENTS.md no longer conflicts.

Product invariants affected

none

State this change writes

None in production. backend/deploy/state_readers.yaml is review metadata. Seed reader minimums use baseline source commit f3902ec5435809d95ac7c15f6be7e9f056564d3d, not asserted live versions; the collections introduced after the seed name the commit that introduced their reader contract. Future state semantics changes must name each reader's required release/commit and rollout order. ready_at explicitly includes helm/batch-pipeline-worker, whose containment switch is BATCH_PIPELINE_WORKER_ENABLED; disabling API admission does not stop accepted work draining.

How it was verified

  • cd backend && pytest tests/unit/test_state_readers_registry.py --noconftest: 25 passed. (This host has no google.api_core, so the normal invocation cannot load tests/unit/conftest.py; CI runs the real invocation.)
  • cd backend && python3 scripts/state_readers_registry.py on the merged tree: all literal writes and deployables covered.
  • On a scratch branch, a direct write of unregistered x_probe_at fails naming {namespace}_jobs.x_probe_at.
  • A registry entry whose kill switch names a service that does not read the field fails naming that service.
  • A new collection reusing another collection's state field fails naming {namespace}_new_collection.state.
  • .github/scripts/check_agents_md_lean.py: all 13 AGENTS.md files within budget.
  • CI at head f9c2cb7b6f: Backend unit shard 6/8 (registry) and Hygiene batch-state-readers pass. The suite's remaining red is tests/unit/test_flutter_rest_inventory.py in shard 7/8, which fails identically on origin/main at the merge base 58a67241ab and at 557740c7c5: docs/api-reference/app-client-openapi.json has no entry for /v1/conversations/{id}/summary/wait or /v2/sync-local-files/receipts/wait, which the Flutter client calls and the backend routes already serve. This diff cannot affect that test; clearing it needs a main-side spec regeneration.

Tests

backend/tests/unit/test_state_readers_registry.py covers direct/transactional payloads, buffered puts, keyword updates, subscript assignments, spread dictionaries, function scope, nested update paths, collection-identity collisions, nested user-scoped tables, in-memory dict merges, missing readers/versions, unknown deployables and invalid containment ownership.

UI evidence

UI-Evidence: none -- backend tests and documentation only.

Failure class (fixes)

Failure-Class: none

@chatgpt-codex-connector

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

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-14T09:54:02.332804Z 0d9bfeb 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: a1c11ac1dc

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread backend/deploy/state_readers.yaml Outdated
Comment on lines +44 to +46
writers: [cloud_run/backend-integration]
readers:
cloud_run/backend-integration: "f3902ec5435809d95ac7c15f6be7e9f056564d3d"

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 Register the independent repair deployment for maintenance cursors

The maintenance cursor contract names only cloud_run/backend-integration, but the independent record-seal-repair CronJob also reads and writes these cursors. Its chart (backend/charts/batch-pipeline-worker/templates/record-seal-repair.yaml) launches scripts/record_seal_repair_job.py, which calls record_seal_cluster_repair.run() and uses RepairCursor.read()/write() against batch_pipeline_prod_maintenance. The chart also supplies its own RECORD_SEAL_REPAIR_ENABLED value. Consequently, a cursor-format change following this registry would omit a real reader's minimum version, and disabling the documented Cloud Run service would leave that reader running. Include the repair deployment in the cursor custody contract and identify its actual containment control, as required by backend/AGENTS.md.

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

Useful? React with 👍 / 👎.

Git-on-my-level added a commit that referenced this pull request Nov 13, 2026
…#25224)

Fresh results now retain their admitted class when committed, and the
maintenance leader publishes the share still pending projection in the
10–20 minute commit window. No scheduling, projection, enrichment or
release behavior changes. SCA-2012 (fresh-first step 1/5). Includes the
round-one contract fixes for the registered guard kill switch and
reviewed merge-writer payload. 319 changed non-test lines.

## Implementation

- The merge transaction copies only exact job True to
results.fresh_capture; missing stamps become False.
- Two count aggregations per minute, an optional ratio, sample age,
default-on kill switch, and 120-second stale expiry. Scrapes do no IO
and do not wait for count RPCs.
- Generated prod/dev indexes and a planning read budget. No alert
changes. The ops kill switch is registered in the feature-flag catalog.

## Reader declaration (before implementation)

#25210 remains open, so the complete declaration is in
backend/docs/listen_pusher_pipeline/changes/2026-11-13-fresh-delivery-guard.md.
The merge transaction is the sole class writer; the guard is its only
new semantic reader. The audit covers backend/ result consumers and
shared services on current main; no existing reader routes on unknown
fields or this result field. Deployed image SHAs still need
release-owner confirmation.

| Readers / adapters | Existing interpretation; service scope |
| --- | --- |
| `utils/batch_pipeline/{merge,scheduler,provider_stt}.py`;
`database/batch_pipeline_{coalescing,paid_attempt,recognizer_receipts,terminal_empty,artifact_missing,speech_redrive}.py`;
`database/{batch_final_pass,batch_voice_evidence}.py` | Result
existence, sequence or explicit receipt/artifact fields;
backend-integration, sync handlers and GKE batch-worker/diarizer runtime
import these shared modules. Job-level class reads remain job reads. |
|
`utils/batch_pipeline/{projection,projection_drain,projection_discovery,projection_followup,projection_repair,voice_evidence}.py`;
`database/batch_pipeline_{projection,projection_session,projection_privacy,projection_release,privacy}.py`
| Projection state, binding, predecessor, privacy and named receipts;
serving/backend-integration. Discovery uses store queries; extra
metadata is ignored. |
| `utils/batch_pipeline/{retention,held_dead_letter,held_coverage}.py`;
`database/batch_pipeline_{store,purge,conversation_purge,quarantine_recovery}.py`
| Cleanup, recovery and metadata stock/age queries use named fields;
shared serving/worker paths. Erasure selects its retained metadata
explicitly. |
| `utils/batch_pipeline/{enrichment,metrics}.py`, `database/outbox*` |
Enrichment consumes its outbox/job priority and projection receipt, not
this result field; existing metrics select receipt/state/age fields. |
| `database/jobstore/{dual_store,postgres_store,codec,backfill}.py`;
`database/batch_pipeline_shadow_hook.py` | Generic document
copy/encoding and parity may carry or compare the new field. Typed
Postgres queries select explicit existing fields; no ordering or routing
decision uses it. DualStore delegates count client/namespace to its
Firestore primary. |
|
`testing/pipeline_sim/{store,postgres_store,sim,trace,scorer,policy_invariants}.py`;
`testing/{batch_replay,store_fixtures,sync_cloud_tasks_stack}`; unit
MemoryStore | Dict/document adapters preserve arbitrary fields;
assertions and traces select named fields. Transition traces select
named fields; final-result snapshots contain the full row, so goldens
are regenerated with only the added fresh_capture boolean. |
|
`scripts/{batch_pipeline_held_disposition,batch_pipeline_terminal_empty,batch_pipeline_artifact_missing,batch_pipeline_speech_redrive,reconcile_batch_projection_ghost_holds,redrive_staging_inputs}.py`;
replay/owner-lab metadata tools | Operator and test readers inspect
named custody/projection fields; no unknown-field routing. Artifact
paths named `results` are encrypted blobs, a separate namespace from
result-row metadata. |


## Cost and rollback

Two count RPCs/sample: approximately max(1, ceil(total/1000)) + max(1,
ceil(pending/1000)) billed reads, normally 2/minute or 2,880/day per
leader. The extra advisory leader check reads the existing lease once
per maintenance invocation. A registered planning envelope of 100,000
rows/count gives 200 reads/sample/environment (576,000/day across
prod/dev); it is an estimate, not a throughput cap. No document/content
streaming. BATCH_PIPELINE_FRESH_GUARD_ENABLED=off suppresses count
queries and all four gauges. The unconditional row field rolls back by
revert; existing stamps have no other semantic reader.

## Review round 1 fixes

The guard now calls the registered policy kill-switch helper (with read
logging suppressed), preserving default-on and off/false/0/no behavior
in off, shadow and serve parser modes. Its helper-backed flag-budget
entry has an owner and review date; the budget's seeded/replacement
limit remains unchanged. The merge writer declaration is updated in
`backend/tests/support/lifecycle_writer_inventory.py`, which is imported
by `lifecycle_state_table.py` on this branch.

## Validation

- R1: required three-file suite: 134 passed, including all off spellings
and default-on semantics in off/shadow/serve parser modes.
- R1: all 45 `make preflight` checks and all 5 PR metadata checks pass
after merging current main.
- R1 final combined run after merging main: **2,141 passed** across the
required three files plus flag budget, stage env ratchet, policy and
lifecycle writer suites.
- R1: registered helper budget, policy boundary, batch-stage env ratchet
and lifecycle writer declarations checked; current main merged
preserving all flag registrations.
- Required three-file pytest command: 106 passed initially; final
expanded run including serving, simulator scenarios and concurrent
scraper coverage: 178 passed.
- Firestore index guard: all 7 files pass (including query-driver and
generated-manifest coverage).
- Characterization suite: 23 passed after regenerating goldens. All 14
changed golden files were structurally compared with HEAD: the only
changes are added final_result.fresh_capture booleans. No other trace
behavior changed.
- make preflight: 45 checks passed on the committed tree. PR metadata
validation: 5 checks passed. Normal commit formatter left all 9 Python
files unchanged.

## Live acceptance outstanding

Release owner must deploy indexes and this code to backend-integration
AND the GKE batch worker. Then record two timestamped ro-prod count
comparisons at least 30 minutes apart (within 1 percentage point), and
sample age under 120 s for one hour, on SCA-2012. This PR performs no
production reads, writes, deploys or activations. Merging is not
completion of the issue.

## Product invariants affected

none — additive internal metadata and count-only observability; no
user-facing behavior changes.

## Pipeline tuning disclosure

No capacity, scheduling, hold/release, routing or pipeline-state
changes. Sampling constants define measurement only (60 s cadence,
inclusive 10–20 minute cohort, 120 s visibility expiry); existing
pipeline capacity settings are unchanged.


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/25224?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/25224?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F25224&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. -->



Failure-Class: none
…ronJob

The encrypted maintenance frontier is constructed only by RepairCursor, which
only record_seal_cluster_repair.run() reaches, and only the record-seal-repair
CronJob launches that path. That CronJob ships in the independently released
helm/batch-pipeline-worker chart, so naming cloud_run/backend-integration as
the cursor's reader/writer and kill-switch owner claimed containment that
disabling Cloud Run does not provide.

Register helm/batch-pipeline-worker as the cursor and version reader/writer
with its minimum source version, move RECORD_SEAL_REPAIR_ENABLED ownership to
the deployment that actually binds it, and add a regression assertion anchored
to the chart template. ready_at ownership and both failure probes are unchanged.
Review round 1 on the merge tree named two gaps. Coverage reduced every
registry key to its final field suffix, so a new collection writing a field
another collection already registered (for example `state`) inherited that
collection's reader contract; it now compares the full collection.field
identity, maps the job store's nested `content`/`conversations` tables to their
user-scoped collections, folds dotted update paths to their top-level field,
and ignores in-memory `cache.update(other)` merges. A collision probe covers
the new failure.

The gate was also red on the PR merge tree: writes that landed on main after
the 2026-11-13 seed were unregistered, including the `after`/`complete`
projection clock markers and provider admission's `late_upload`. Register them
with the collection's existing custody envelope, add entries for the
collections introduced since the seed (allowance holds, backlog release meter,
merge-discovery cursor, source-alias projections, conversation batch-purge
obligations), and keep the reviewer-named fields under named readers with a
containment switch. AGENTS.md takes main's wording of the selector paragraph
so the merge no longer conflicts.
main reached 38 978 of the 39 000-byte backend/AGENTS.md budget, so the
registry pointer needs the slack it takes. Fold the selector paragraph to the
same instructions in fewer bytes instead of raising the ratchet.

This branch has not been deployed

No deployments
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