Skip to content

fix(batch): defer privacy-blocked record_pending rows off the drain page - #24841

Merged
Git-on-my-level merged 1 commit into
mainfrom
lane/pipeline-privdefer
Nov 7, 2026
Merged

Git-on-my-level merged 1 commit into
mainfrom
lane/pipeline-privdefer

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

What

Drainer cause 2. Every row on the record drainer's oldest due page (store.due('record_pending', now, 100)) can be privacy-blocked:

  • deletion-pending owners;
  • owners with private_cloud_sync_enabled=false on batch_live_v1, which hit BatchPrivacyBlocked('recording_privacy_changed').

The drainer's claim is a full job write, and the store flush privacy fence (FirestoreTransaction.flush → check_privacy) refuses it. drain_one then returned without deferring the row. The row stayed due forever, so every row behind that page starved. The deferral could not be written either, because it also went through the fenced flush.

This PR adds Store.defer_privacy_blocked_record(segment_id, until, now), implemented for Firestore, Postgres and the sim store. The drainer calls it when its claim meets the privacy fence. It follows the existing quarantine_fenced pattern: its own transaction, the fence rechecked, a shallow update.

Constraints from the privacy-lane ruling (faf00e), and how they are met

  1. An UPDATE of an EXISTING job doc, never a create.
    • It uses transaction.update, which carries Firestore's exists precondition.
    • It returns early when the snapshot does not exist.
    • Tests: test_purged_job_is_not_resurrected (no update/set/create) and the conformance case 'missing' (the doc is not created).
  2. Changes available_at only.
    • Enforced by PRIVACY_DEFER_FIELDS = {'available_at'} at the write site (_check_privacy_defer_fields).
    • Tests: test_any_other_field_in_the_defer_write_is_refused. The conformance test checks that the stored doc equals the original plus available_at.
  3. Kill switch, default ON.
    • RECORD_DRAIN_PRIVACY_DEFER_SECONDS: default 900, 0 restores today's behavior.
    • It lives in config/record_drain.py next to the other RECORD_DRAIN_* capacity knobs, which are outside the flag-budget scope.
    • Test: test_kill_switch_zero_restores_the_stay_due_behavior.
  4. Tests:
    • Purged job not resurrected.
    • A privacy-blocked owner's row moves, and the starved row behind the page is admitted on the next pass: test_a_fully_blocked_oldest_page_no_longer_starves_the_rows_behind_it.
    • Any other field is refused.
    • Plus: an allowed (unblocked) row is left to the normal claim; non-due and non-record_pending rows don't move; a failed defer keeps today's behavior (row due, idle wait kept).
  5. The 21 deletion-pending owners are NOT handled here.
    • Their rows are only deferred and re-checked every 15 min. Erasure (the RCA terminalizes them as source_deleted) keeps ownership.
    • Nothing is terminalized, deleted or admitted by this path.

The fence is rechecked inside the defer transaction. A row whose owner became allowed again returns False and goes back to the normal claim. No user data, conversation, audio or result is read beyond the job doc and the existing privacy state, and none is written.

Effect

A pass whose fenced rows were all deferred no longer forces the idle wait, because those rows left the page. A row whose defer failed still sets it, exactly as before.

Verification

  • tests/unit/test_record_drain_privacy_defer.py (new), plus test_batch_pipeline_live.py, test_batch_pipeline_scheduler.py, test_jobstore_projection_mirror.py: 175 passed.
  • Ratchets (test_batch_stage_env_ratchet, test_flag_budget, test_lifecycle_state_table_writers, test_cell_store_conformance): 1729 passed.
  • tests/integration/test_store_conformance.py -k "privacy_defer or quarantine_fenced": the sim backend passes locally; Firestore and Postgres run in CI.

Rollout

Ships on (the kill switch defaults ON). Trip: set RECORD_DRAIN_PRIVACY_DEFER_SECONDS=0 on the services that run the record drainer. Watch:

  • event=batch_drain_pass row_count;
  • the oldest record_pending age (omi_batch_record_pending_new_oldest_age_seconds), which should fall below its 24 h ceiling;
  • no outcome=privacy_defer_failed storm.

Failure-Class: none

🤖 Generated with Claude Code

View guided diff Turn on auto-fix

The record drainer's claim is a full job write, so the store flush privacy
fence refused it and the blocked row stayed due forever, starving every row
behind the oldest page. Add Store.defer_privacy_blocked_record: an
available_at-only UPDATE of the existing job (never a create), fence
rechecked in its own transaction, kill switch
RECORD_DRAIN_PRIVACY_DEFER_SECONDS (default 900, 0 = previous behavior).
Privacy-lane ruling faf00e.

Failure-Class: none

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

chatgpt-codex-connector Bot commented Nov 7, 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-07T07:34:04.643943Z fae0682 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.

@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.

2 issues found across 9 files

Confidence score: 4/5

  • In test_record_drain_privacy_defer.py, the failure-path test can pass without exercising the defer call. Assert that defer_privacy_blocked_record was called once.
  • In test_record_drain_privacy_defer.py, the finally block can remove a pre-existing environment value and leak state if the test fails early. Use monkeypatch.setenv for automatic cleanup.
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/unit/test_record_drain_privacy_defer.py">

<violation number="1" location="backend/tests/unit/test_record_drain_privacy_defer.py:172">
P2: This failure-path test passes even if the defer is never called. Assert that the mocked `defer_privacy_blocked_record` was invoked once so the exception-swallowing path is exercised.</violation>

<violation number="2" location="backend/tests/unit/test_record_drain_privacy_defer.py:177">
P3: Use `monkeypatch.setenv` in this test instead of mutating `os.environ` and deleting the key in `finally`. The `finally` block removes a pre-set value and leaks state if the test fails before it runs.</violation>
</file>

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

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

live, admitted = drain
monkeypatch.setenv('RECORD_DRAIN_BATCH', '1')
store = fenced_store(('a-fenced', True))
store.defer_privacy_blocked_record = Mock(side_effect=RuntimeError('contention'))

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 failure-path test passes even if the defer is never called. Assert that the mocked defer_privacy_blocked_record was invoked once so the exception-swallowing path is exercised.

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/unit/test_record_drain_privacy_defer.py, line 172:

<comment>This failure-path test passes even if the defer is never called. Assert that the mocked `defer_privacy_blocked_record` was invoked once so the exception-swallowing path is exercised.</comment>

<file context>
@@ -0,0 +1,187 @@
+    live, admitted = drain
+    monkeypatch.setenv('RECORD_DRAIN_BATCH', '1')
+    store = fenced_store(('a-fenced', True))
+    store.defer_privacy_blocked_record = Mock(side_effect=RuntimeError('contention'))
+    assert asyncio.run(live.drain_recordings(store)) is False
+    assert store.rows['jobs', 'a-fenced']['available_at'] == 0
</file context>

assert store.rows['jobs', 'a-fenced']['available_at'] == 0


def test_kill_switch_parsing():

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: Use monkeypatch.setenv in this test instead of mutating os.environ and deleting the key in finally. The finally block removes a pre-set value and leaks state if the test fails before it runs.

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/unit/test_record_drain_privacy_defer.py, line 177:

<comment>Use `monkeypatch.setenv` in this test instead of mutating `os.environ` and deleting the key in `finally`. The `finally` block removes a pre-set value and leaks state if the test fails before it runs.</comment>

<file context>
@@ -0,0 +1,187 @@
+    assert store.rows['jobs', 'a-fenced']['available_at'] == 0
+
+
+def test_kill_switch_parsing():
+    from config.record_drain import record_drain_privacy_defer_seconds
+
</file context>

@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: fae068253d

ℹ️ 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 +27 to +30
def record_drain_privacy_defer_seconds() -> int:
"""How long a privacy-blocked record_pending row leaves the drain page (privacy ruling faf00e).

Kill switch: 0 restores the previous behavior (the blocked row stays due and is retried every 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.

P1 Badge Document the drainer behavior and its new kill switch

This changes the audio admission pipeline and introduces a default-on operational setting, but the commit includes neither a pipeline change note nor an update to the environment contract. A repository-wide search for RECORD_DRAIN_PRIVACY_DEFER_SECONDS finds only implementation and tests, leaving the documented pipeline without the new 900-second deferral or its rollback switch. Add a dated note under backend/docs/listen_pusher_pipeline/changes/ and document the setting and default in backend/docs/listen_pusher_pipeline.mdx, as required by backend/AGENTS.md.

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

Useful? React with 👍 / 👎.


def defer_privacy_blocked_record(self, segment_id: str, until: float, now: float) -> bool:
"""Same fence recheck and available_at-only change as the Firestore privacy defer."""
from database.batch_pipeline_recovery import privacy_defer_update

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 function-local imports to module scope

The new Postgres method imports privacy_defer_update inside its body, contrary to the explicit backend/AGENTS.md requirement that all imports be at module scope and never inside functions. Move this import to the module header; the function-local imports introduced in test_record_drain_privacy_defer.py need the same adjustment to satisfy the applicable backend convention.

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

Useful? React with 👍 / 👎.

@Git-on-my-level
Git-on-my-level merged commit a767a4b into main Nov 7, 2026
63 of 65 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/pipeline-privdefer branch November 7, 2026 08:18
Git-on-my-level added a commit that referenced this pull request Nov 7, 2026
…24863)

## What
Since #24841 went live, the record drainer reaches about 19k due
`record_pending` rows that the privacy-blocked heads used to hide.
Nearly all of them fail admission with `capture upload/finalization
barrier not closed`: the conversation is not `completed`, or
`record_audio_closed` is unset, or upload sessions are still open
(`config/record_audio.require_record_audio_barrier`). Each is
re-selected about every 60 s.
- In 15 min: at least 5k passes of 100 rows and at least 4,982 barrier
retries.
- Firestore read/write cost about $15/h above baseline (firestore-lead
af9abb).
- These rows can only admit once their capture finalizes; re-reading
them every minute buys nothing.

## Change
A barrier-blocked row backs off by its `record_pending` age
(`enqueued_at`):
- under 10 min: 60 s (unchanged);
- under 24 h: 15 min;
- older: 1 h.

Other admission errors, and partial-inventory polling, keep their
current delays. Rows that finalize are picked up within one backoff
period. Expected: about 15-60x fewer reads on stuck rows.

Kill switch: `RECORD_DRAIN_BARRIER_BACKOFF=off` restores the flat 60 s.
It lives in `config/record_drain.py` beside the other `RECORD_DRAIN_*`
capacity knobs, outside the flag-budget scope.

Not in scope: rows stuck for days behind a barrier that will never close
need a lifecycle (park/dead-letter), which is the architecture thread's
per-conversation state machine.

## Tests
`tests/unit/test_record_drain_barrier_backoff.py`:
- the steps;
- age-based delay on the real drain path;
- other errors stay at 60 s;
- the kill switch;
- a missing `enqueued_at` counts as young;
- the barrier text matches the raise site.

Also run: `test_batch_pipeline_live`, `test_record_drain_privacy_defer`,
env ratchet, flag budget. 151 passed.

## Verify after deploy (backend-integration)
- The `batch_live_admission ... barrier_not_closed` log rate drops about
15x.
- Firestore reads on `batch_pipeline_prod_jobs` fall (firestore-lead's
meter).
- Uncapped `record_pending` (funnel `current.md`) keeps admitting rows
as captures finalize.

Failure-Class: none

🤖 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/24863?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/24863?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F24863&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. -->
kriegcloud pushed a commit to kriegcloud/omi that referenced this pull request Nov 7, 2026
Rows whose capture upload/finalization barrier is still open cannot admit until
the conversation finalizes; the drainer retried ~19k of them every 60 s after
BasedHardware#24841 exposed them (~$15/h of Firestore churn). Back off 60 s -> 15 min (>10 min
old) -> 1 h (>24 h old); other errors unchanged. Kill switch
RECORD_DRAIN_BARRIER_BACKOFF=off.

Failure-Class: none

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

Every full page rescanned immediately; with privacy-blocked heads deferred off the
page (#24841), barrier-blocked rows were re-read in waves without admission
(store:due 108 -> 431/s). A pass that admitted nothing now keeps the idle wait;
kill switch RECORD_DRAIN_IDLE_WITHOUT_PROGRESS=off.

Failure-Class: none

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Git-on-my-level added a commit that referenced this pull request Nov 14, 2026
…mitted nothing (#24882)

## What
The record drain loop has no pacing: every full page (100 rows)
immediately triggers another pass. While privacy-blocked heads stayed on
the page, the pass returned "blocked" and idled; #24841 moved them off,
and since then any full page rescans at once even when nothing is
admitted.
- 2026-11-07 20:43Z to 21:13Z, after the #24841 defer was re-enabled:
`store:due` reads rose 108 to 431/s and `store:get` 1,088 to 1,751/s.
- Barrier-blocked rows (#24863 backoff) return due in waves and are
rescanned without any admission.
- firestore-lead tripped the defer back to 0 (bus cd411f/87a934).

## Change
A full page that ADMITTED nothing (every row deferred, failed or still
behind its barrier) keeps the idle wait, like a privacy-blocked page.
Only passes that made progress continue immediately.
- The drain still reaches every due row (a page per idle interval); it
just stops the hot rescan.
- Kill switch: `RECORD_DRAIN_IDLE_WITHOUT_PROGRESS=off` restores the old
behavior. It lives in `config/record_drain.py` with the other
`RECORD_DRAIN_*` capacity knobs, outside flag-budget scope.

With this live, `RECORD_DRAIN_PRIVACY_DEFER_SECONDS` can be unset again
(#24841 behavior) without the read climb.

## Tests
- `tests/unit/test_record_drain_pacing.py`:
  - a no-admission full page idles;
  - a page with progress continues;
  - the kill switch restores the old behavior;
  - a partial page never continues.
- `test_record_drain_privacy_defer`: a fully blocked page now idles one
interval, and the starved row is still admitted on the next pass.
- Also ran `test_batch_pipeline_live`,
`test_record_drain_barrier_backoff`, `test_batch_record_dead_letter`,
`test_batch_pipeline_serving`, `test_record_partial`,
`test_record_gap_fill` and `test_replay_harness`: 489 passed on the
rebased head.

## Review
One Luna round (blocking-only). Its blocker is fixed: a normal return
can be a no-op (an unchanged partial inventory poll), so progress now
counts only when the defer transaction sees the row out of
`record_pending`. The paging/shuffle tests pin the old mode through the
kill switch. lead2 ddc817: the defer stays at its default (900)
meanwhile.

SCA-2036 review fix: rebased onto `main` (`af24862981`). The defer
transaction now also reports dead-letter expiry, so it returns
`(progress, expired)` — a row that left `record_pending` is progress, a
dead-letter expiry is not, and a peer's dead-letter is not either.
`test_record_drain_pacing` pins both.

## Verify after deploy (backend-integration)
-
`omi_firestore_billed_reads_by_caller_total{caller="database.batch_pipeline_store:due"}`
falls back to about 100/s.
- `store:get` falls.
- Record admissions per minute stay unchanged.

Failure-Class: none

🤖 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/24882?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/24882?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F24882&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. -->




## Landing follow-up

Operator documentation now covers the default-on pacing control, its
`off` rollback value, and the conservative 20-second idle for
partial-record coordinators that admit children while their parent
remains pending. See
`backend/docs/listen_pusher_pipeline/changes/2026-11-14-record-drain-pacing.md`
and the record-drain pacing contract in
`backend/docs/listen_pusher_pipeline.mdx`.

CI on code head `d1a80c8081`: all eight backend unit shards and Backend
Hermetic Merge Gate passed. The advisory Backend Emulator Proofs job
failed the same six provider merge conformance cases already failing on
main (`54b960d947`; run
https://github.com/BasedHardware/omi/actions/runs/43578026940). The
affected merge implementation and conformance tests are unchanged
between that main snapshot and this PR. Deployment read-rate and
admission checks remain post-deploy work.
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