Skip to content

fix(batch): persist the held release scan cursor across instances - #24361

Merged
Git-on-my-level merged 2 commits into
mainfrom
lane/rollheld-release-cursor
Nov 2, 2026
Merged

Git-on-my-level merged 2 commits into
mainfrom
lane/rollheld-release-cursor

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

Why

The held-unit release scan keeps its keyset cursor in memory on the per-instance Projector. Every backend-integration instance start (scale-out, roll or recycle) begins again at page one, and an instance never lives long enough to wrap the whole set.

Measured on prod with the ro-prod tier, counts only, at 06:55Z 11-02: of 16,932 quarantine_held result rows in scan order (__name__), release attempts exist only in deciles 0–1. Deciles 2–9 carry no attempt at all. The scan examined about 4,750 rows/h, but always the same front rows. Any held unit that becomes releasable, including the 1,491 desktop units #24345 makes releasable, waits indefinitely unless it happens to sort early.

What

  • load_release_cursor and save_release_cursor (database/batch_pipeline_projection_release.py) keep the cursor in one {namespace}_control doc, projection_release_cursor.
    • The doc has no scheduler fields (p*_active, p*_service), so the control-shard queries never select it.
  • Projector.release_held_scan resumes from that cursor when its in-memory cursor is empty, which happens on a new instance or after a wrap. It writes the new position after each pass that examined rows or moved the cursor; a wrap writes None.
  • Both helpers are advisory. A failed load starts from the top, and a failed save only repeats rows the next pass re-checks, since release is transactional and idempotent. The scan itself never fails on them.
  • Concurrent instances may overwrite each other's position. That only repeats or skips ahead within one pass's span, and every instance keeps moving forward.
  • Cost: one read and one transactional write per pass, about 80 of each per hour.

Fail-first evidence

test_release_scan_resumes_from_the_durable_cursor_after_an_instance_restart on origin/main 3c329ff7661a: three fresh scanners all started at None ([None, None, None]). With the fix they read [None, 'held-01', 'held-03'], and the empty page past the end wraps back to None.

Verification (layer: local unit tests, this head)

backend/test.sh through bin/omi-heavy, nice 19, with ambient GCP credentials unset. The file list was the 9 unit files that reference the release scan, serving maintenance or the release module: release, hold recovery, serving, quarantine recovery, merge fresh-first, jobstore shadow seams, revision drain harness, record admission and memories. All passed.

Side effect, intended

The scan will also reach 3,329 units held on visible record targets (provenance_mismatch holds, 10-29 to 11-01). They already pass every release check but were never examined. Each one re-projects under the ordinary transactional provenance fences. It either lands its batch text, or it re-holds within the existing 3-attempt bound. Audio is untouched.

After deploy (expected; measured afterwards)

At about 4,750 rows/h, one full wrap of about 16.9k held rows takes about 3.6 h. release_held summaries should then show the #24345 cohort releasing across every decile, not only the front.

Deploy: backend-integration (the scan runs there; backend and backend-sync take it on their next roll).

Failure-Class: none

Product invariants: INV-DATA-1.

🤖 Generated with Claude Code

Git-on-my-level and others added 2 commits November 2, 2026 14:08
The release scan's keyset cursor lived in per-instance memory, so every
backend-integration instance start began at page one. Prod 11-02: of 16,932
quarantine_held rows, release attempts exist only in the first two deciles by
name. Keep the cursor in one control doc (no scheduler fields); a new instance
resumes where the last pass stopped. Load and save are advisory.

Failure-Class: none

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The durable-cursor wrapper delegates its only query to held_page_ids, like
release_page; record it as covered with its body digest.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@chatgpt-codex-connector

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 ⚠️ Failed 2026-11-02T07:19:46.886570Z
We couldn’t complete this review. Comment @codex review to try again.
c25c4e6 PR opened
ℹ️ 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

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@cubic-dev-ai cubic-dev-ai 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.

3 issues found across 5 files

Confidence score: 3/5

  • In projection.py, a failed cursor reset can leave the scan reloading a stale cursor and stalling on the final page. Preserve the wrapped cursor in memory across the retry.
  • The release_scan_pass digests in firestore_batch_pipeline_drivers.py and firestore_query_driver_registry.py are stale, so the digest-pinned contract test and query-shape guardrail fail in CI. Update both digests from the current function body.
Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="backend/tests/support/firestore_batch_pipeline_drivers.py">

<violation number="1" location="backend/tests/support/firestore_batch_pipeline_drivers.py:347">
P2: This `body_digest` does not match the current `release_scan_pass` function, so the digest-pinned Firestore query contract test fails. Replace it with the current AST digest.</violation>
</file>

<file name="backend/tests/support/firestore_query_driver_registry.py">

<violation number="1" location="backend/tests/support/firestore_query_driver_registry.py:148">
P2: This digest is stale for the current `release_scan_pass` implementation, so the Firestore query-shape guardrail fails in CI. Replace it with the digest generated from the current function body.</violation>
</file>

<file name="backend/utils/batch_pipeline/projection.py">

<violation number="1" location="backend/utils/batch_pipeline/projection.py:843">
P2: A failed cursor reset can stall the scan on the final page: after the short page sets `self.release_after` to `None`, `release_scan_pass` reloads the stale durable cursor on the next tick. Preserve an in-memory wrapped state, or make the helper distinguish initial cursor loading from a wrapped cursor, so advisory save failures do not keep the backlog at the tail.</violation>
</file>

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

covered_by=('database.batch_pipeline_projection_release.held_page_ids',),
reason='durable-cursor wrapper over release_page; the cursor is one document get and set',
expect_observed=False,
body_digest='1b9c67910b80e2628cf61514e1b24875242fc623069e6a2f64764cb90f2fa27e',

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: This body_digest does not match the current release_scan_pass function, so the digest-pinned Firestore query contract test fails. Replace it with the current AST digest.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/tests/support/firestore_batch_pipeline_drivers.py, line 347:

<comment>This `body_digest` does not match the current `release_scan_pass` function, so the digest-pinned Firestore query contract test fails. Replace it with the current AST digest.</comment>

<file context>
@@ -339,4 +339,11 @@ def entries():
+            covered_by=('database.batch_pipeline_projection_release.held_page_ids',),
+            reason='durable-cursor wrapper over release_page; the cursor is one document get and set',
+            expect_observed=False,
+            body_digest='1b9c67910b80e2628cf61514e1b24875242fc623069e6a2f64764cb90f2fa27e',
+        ),
     )
</file context>
Suggested change
body_digest='1b9c67910b80e2628cf61514e1b24875242fc623069e6a2f64764cb90f2fa27e',
body_digest='01505434b880b1f891f45e98534891668238796f9fa87fbd58174be6ba7a05e1',

'database.batch_pipeline_store.FirestoreStore.ready_for_capacity': '975eabd92f43ba5da3d847439f4d8e3592525ccd31c11dcac6463365535eac10',
'database.batch_pipeline_store.FirestoreStore.oldest_admissible_ready': '293687cc6708d7ab2f673cb2984e6bb8cbfe581fa526db8c1040fd011dc00107',
'database.batch_pipeline_projection_release.release_page': '51d879075128af7e074b0ab3ccdb376e2171678351cad3ade376a3a3f78e2e69',
'database.batch_pipeline_projection_release.release_scan_pass': '1b9c67910b80e2628cf61514e1b24875242fc623069e6a2f64764cb90f2fa27e',

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: This digest is stale for the current release_scan_pass implementation, so the Firestore query-shape guardrail fails in CI. Replace it with the digest generated from the current function body.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/tests/support/firestore_query_driver_registry.py, line 148:

<comment>This digest is stale for the current `release_scan_pass` implementation, so the Firestore query-shape guardrail fails in CI. Replace it with the digest generated from the current function body.</comment>

<file context>
@@ -145,6 +145,7 @@ def patcher(client):
     'database.batch_pipeline_store.FirestoreStore.ready_for_capacity': '975eabd92f43ba5da3d847439f4d8e3592525ccd31c11dcac6463365535eac10',
     'database.batch_pipeline_store.FirestoreStore.oldest_admissible_ready': '293687cc6708d7ab2f673cb2984e6bb8cbfe581fa526db8c1040fd011dc00107',
     'database.batch_pipeline_projection_release.release_page': '51d879075128af7e074b0ab3ccdb376e2171678351cad3ade376a3a3f78e2e69',
+    'database.batch_pipeline_projection_release.release_scan_pass': '1b9c67910b80e2628cf61514e1b24875242fc623069e6a2f64764cb90f2fa27e',
     'database.monthly_usage_totals._rebuild': '2c9be83589399a6824fbb2ef7376cd7baf8492e8a780671e31b67a8294b40db0',
     'database.batch_pipeline_shadow.ShadowStore._busy': 'bf2a9290745e8dd01ebb927b03ed67b08fac05fdb43fd76f81f2dcfa54e0b85a',
</file context>
Suggested change
'database.batch_pipeline_projection_release.release_scan_pass': '1b9c67910b80e2628cf61514e1b24875242fc623069e6a2f64764cb90f2fa27e',
'database.batch_pipeline_projection_release.release_scan_pass': '01505434b880b1f891f45e98534891668238796f9fa87fbd58174be6ba7a05e1',

enabled = projection_hold_recovery_enabled()
started = time.monotonic()
counts, self.release_after = release_page(
counts, self.release_after = release_scan_pass(

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: A failed cursor reset can stall the scan on the final page: after the short page sets self.release_after to None, release_scan_pass reloads the stale durable cursor on the next tick. Preserve an in-memory wrapped state, or make the helper distinguish initial cursor loading from a wrapped cursor, so advisory save failures do not keep the backlog at the tail.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/utils/batch_pipeline/projection.py, line 843:

<comment>A failed cursor reset can stall the scan on the final page: after the short page sets `self.release_after` to `None`, `release_scan_pass` reloads the stale durable cursor on the next tick. Preserve an in-memory wrapped state, or make the helper distinguish initial cursor loading from a wrapped cursor, so advisory save failures do not keep the backlog at the tail.</comment>

<file context>
@@ -836,11 +836,11 @@ def sweep_held(
         enabled = projection_hold_recovery_enabled()
         started = time.monotonic()
-        counts, self.release_after = release_page(
+        counts, self.release_after = release_scan_pass(
             self.store,
             limit=limit if limit is not None else RELEASE_PAGE if enabled else HELD_PARTIAL_PAGE,
</file context>

@Git-on-my-level
Git-on-my-level merged commit c35a7e5 into main Nov 2, 2026
73 of 74 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/rollheld-release-cursor branch November 2, 2026 07:45
Git-on-my-level added a commit that referenced this pull request Nov 17, 2026
sweep_held kept its resume point in Projector.held_after, process memory.
backend-integration starts instances hundreds of times a day while one pass
over ~53k held units takes days under the read governor, so every new
maintenance leader restarted at page one and units late in ID order were
never examined. bp_2ba4592b's failed_held unit has waited since 11-12 while
an otherwise identical upload earlier in the ID order settled partial.

Persist the cursor in control/projection_held_partial_cursor through the
release scan's load/save helpers (#24361), one read and at most one write per
segment. A fresh pass also drops this process's upload dedupe, which another
instance's wrap made stale.

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

## Problem

An owner's batch uploads project strictly in order behind a per-owner
watermark. When the chain head fails in a way that may still resolve (a
transient error, or a fresh "awaiting writer" conflict such as a live
target that listen has not persisted yet), the head waits under a
durable 24 h bound. After that, the generic poison-head rule holds it
and the chain advances.

That bound never started. `Projector._note_head_blocked` passed a
**plain function** to `ProjectionStore.run`. `run_transactional` hands
its callable a raw, unbegun transaction, and only a
`@firestore.transactional` callable begins it. So every read raised
`ValueError('Transaction not in progress, cannot be used in API
requests.')`. The stamp was swallowed as `head_block_note
outcome=retry`, `projection_blocked_since` never landed, and
`head_retry_bound_exceeded` could never fire. Every such head waited
forever and froze its owner's chain.

## Evidence

Prod, read-only `ro-prod` tier, 2026-11-17 ~11:10Z.
`backend-integration` serves `backend-integration-fold-fb3d7732f270` at
100%, `OMI_BACKEND_RELEASE_SHA=0ce396503a55`.

- `head_block_note outcome=retry exception_type=ValueError`: 436 lines
in 9 minutes (~48/min).
- The same `ValueError` reproduces offline:
`firestore.Client(...).transaction()` passed unbegun to
`DocumentReference.get(transaction=...)`.
- The oldest 300 `projection_state=pending` results belong to just 6
owners, committed from 10-31 onward. Every one of their chain heads is
`pending`, has **no `projection_blocked_since`**, and has not been
written since its commit (up to 14 days).
- A field user's chain has been frozen since 11-16 22:59Z with 625 rows
behind its head, and their app shows "processing" for every newer
upload.

## Fix

- `ProjectionStore.note_head_blocked(segment_id, now, block_type)` is a
`@firestore.transactional` read-then-update, written like the store's
other transactions (`defer_finish`). It stamps only a
`pending`/`persisted`/`ready` row without an existing stamp, once per
episode.
- `Projector._note_head_blocked` delegates to it and keeps the same
failure logging.
- A static test fails if `utils/batch_pipeline/projection.py` calls
`store.run` directly again. A hard type check in `ProjectionStore.run`
was tried and rejected, because unit tests drive `run` with `Mock`
operations.

## Tests

New `backend/tests/unit/test_batch_projection_head_block_note.py`:
- The stamp lands through `ProjectionStore` on `StrictFirestore`, once
per episode, and never on a row outside the assignment states.
- `Projector._note_head_blocked` reaches the store, and the 24 h bound
starts from it.
- The static `store.run` guard.
- An old backfill head failing with `LIVE_TARGET_NOT_PERSISTED` is held
and frees the chain, through the real owner-chain walk.

Projection and owner-chain suites (`test_batch_pipeline*proj*`,
`test_batch_projection*`, quarantine, sweep owner chain, jobstore
mirror): 1,108 passed. One test,
`test_batch_projection_playback_artifact_missing.py::test_missing_staged_object_skips_playback_and_counts`,
failed only in the combined run. It passes alone with and without this
change, so it is order-dependent.

## Second fix: the held-partial pass never reached late IDs

A single-segment upload whose only unit is `failed_held` settles
`partial` through the held-partial sweep (`Projector.sweep_held`). That
sweep pages `recovery_state in (held, failed_held)` in document-ID
order, but kept its resume point in `Projector.held_after`, which is
process memory.

- `backend-integration` had 40+ revisions since 11-10 and 500+ instance
startups in the last 24 h.
- One pass over the ~53k held/failed_held jobs, at the observed ~32
units per 20–40 s segment under the hourly read governor, takes days.
- So each new maintenance leader restarted at page one. An upload with
an empty-ASR unit, `bp_2ba4592b`, has been `processing` since 11-12. An
otherwise identical upload (`bp_e232cfee`) about 800 IDs earlier settled
`partial` on 11-16.

The fix persists the cursor in `control/projection_held_partial_cursor`,
through the release scan's `load_release_cursor`/`save_release_cursor`
(#24361). That costs one read and at most one write per segment. A fresh
pass (no cursor) also clears this process's upload dedupe, which another
instance's wrap has made stale. New test:
`test_restarted_instance_resumes_the_held_pass_from_the_durable_cursor`.
The quarantine-recovery, serving, release, head-block and owner-chain
suites pass (511).

## Review fixes (panel review-20261117t121718-4c7e)

- `StrictFirestore(require_begun=True)` rejects an unbegun transaction
the way the SDK does. The stamp tests use it: removing
`@firestore.transactional` from `note_head_blocked` now fails 3 tests,
and a new test pins the pre-fix shape. It is opt-in because about 330
test files drive inner transaction bodies with a raw fixture transaction
on purpose.
- The live-target chain test is split in two. One covers an old capture
held by the 6 h age gate. The other covers a recent capture: it waits,
gets stamped, holds after 24 h, and the chain frees. That second one
fails if the stamp raises. The non-existent env var is gone.
- `merge_ready` (source fallback) clears
`projection_blocked_since`/`projection_block_type` when it re-pends a
preserved slot, like the release reset does.
- The stamp field names moved to
`database/batch_pipeline_projection_protocol.py`, so the store no longer
imports from `utils`.
- Pipeline change note:
`backend/docs/listen_pusher_pipeline/changes/2026-11-17-projection-head-block-stamp.md`.

## Third panel (review-20261117t132925-498a, SHIP) fixes

- The bound test now fails the head with a transient `TimeoutError`. An
awaiting-writer conflict on a capture older than 6 h holds on the age
gate before the 24 h bound is ever consulted. The test asserts the head
is still pending at 24 h − 1 s and held at 24 h + 1 s, and it fails if
`head_retry_bound_exceeded` or the stamp is broken.
- A failed cursor save keeps the in-memory cursor and retries the save,
so the next segment doesn't fall back to the stale durable value.
`save_release_cursor` now returns whether it wrote.
- The `store.run` static guard also catches a bare `store.run(...)`. The
`ResultLog.note_head_blocked` fake returns False for a missing row.

## Rollout note

Nothing is gated, and the existing kill switches are unchanged. After
deploy, every waiting head gets stamped on its next visit and holds 24 h
later. Heads that have waited for days therefore release about one day
after deploy, and their successors then project. Watch
`omi_batch_projection_*` holds and backlog in that window. Held units
keep their audio and follow the existing hold-recovery path.

Line-Count-Exception: backend/utils/batch_pipeline/projection.py | 1845
-> 1850 | durable held-partial cursor wrapper; the cursor helpers live
in batch_pipeline_projection_release.py and the stamp field names moved
to batch_pipeline_projection_protocol.py

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

## Product invariants affected

none

🤖 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