Skip to content

perf(deletion): coalesce owner scans for conversation batch purges - #25608

Merged
Git-on-my-level merged 18 commits into
mainfrom
lane/purge-coalesce
Nov 18, 2026
Merged

Git-on-my-level merged 18 commits into
mainfrom
lane/purge-coalesce

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

Contract

Bulk conversation deletion currently scans an owner's batch history once per conversation. Share the same traversal across a sealed group of up to 16 fresh same-owner deletion obligations, including the per-job result gets and corrupt-owner-key artifact fallback. Existing partial legacy runs execute independently. Arm-stamped legacy cursors resume; an unversioned or re-armed cursor restarts discovery with segment journals retained. This is its own train; margin-40 has no dependency on it.

Every member still requires a tombstone, all namespaces/phases, its WAL prefix sweep, and empty segment work before completion. The final transaction compares every arm revision and generation/token. Account gates, legal holds, short units and task/RPC deadlines, generation-pinned storage deletes, unknown-outcome gate settlement, pending-write repair, exactly-once WAL capacity release, shadow purge and mirror refresh use the existing implementation. New/rearmed members never inherit an advanced cursor.

No new work collection or task kinds: bounded group state is an owner_scan field on the existing leader obligation. Existing per-member segments journals remain authoritative. The reserved conversation_batch_purge_jobs/_owner_scan_v1_readiness metadata document is written/revoked by Release and read only by the new backend-sync scan consumer, transactionally at seal, resume, checkpoints/units and completion. Missing, malformed, false or expired readiness preserves legacy execution; read errors retry. Marker validity is bounded to 24 hours. Backend-sync's task consumer reads the new fields; its reconciler, tombstone producers and old workers still use ordinary conversation_batch_purge_jobs generations/leases. See state readers and safety proof.

Kill switch and rollback

CONVERSATION_BATCH_PURGE_COALESCING_ENABLED defaults on; false/off/0/no stops enrollment and hands members back with their original legacy progress and own remaining segment journals. Old workers see ordinary leases/superseded generations and recover by legacy execution after at most the existing lease interval. A takeover invalidates the shared run; handback never revokes the replacement worker's lease. Old completion has no arming-revision fence, so mixed-version coalescing is now refused until Release attests every consumer is new. Revoke readiness and switch off, then drain active delegated groups before routing an old binary. A route-presence probe cannot assert readiness. No journal transfer is needed.

Simplifications: enroll only fresh obligations; inline bounded group state instead of a new scan collection; use unchanged task payloads; retain segment associations until every member's dependent/parked work is finished, then remove them after binding erasure as legacy already does. Thus handback needs no second association journal.

Canary and owner

Release is the canary executor and owns expansion/rollback. Lead2 owns batch-custody pre-merge review. This remains its own train, independent of margin-40.

First deploy with the switch off and verify every purge-task consumer, including queued revision-specific targets, runs the reviewed image. Only then may Release assert conversation_batch_purge_jobs/_owner_scan_v1_readiness (all_consumers_new: true, valid_until timestamp within 24 hours). Route presence alone is insufficient. With the marker valid, enable one backend-sync canary revision for a full deletion lookback window. This PR creates no production marker and performs no production access.

Metric: deletion purge reads per armed conversation, origin http:/v1/conversations/deletion-batch-purges/run, including coordination and member-journal reads. Compare timestamped aggregates against the 24 hours before canary. Stop, revoke readiness and switch off if:

  • Any audit finds a completed member with rows remaining (audit both namespaces, artifacts, bindings and exact WAL prefixes/all generations).
  • Purge failure rate or dead-letter rate increases 20% or more versus the preceding 24 hours. Any new failures/dead letters from a zero baseline also stop.
  • Reads per armed conversation are not falling after the full lookback window.

Release expands only after a clean full window and completed-member audits. Local tests do not establish billed-read savings.

Mixed-version proof (lead2 follow-up)

Frozen byte-for-byte worker snapshots from pre-PR main f47914db8856fdb9f0be165b489e066f04088192 include both the runner and traversal, SHA-256 checked, with private per-test imports. The reconciler is unchanged from that base; emulator tests run its actual due queries and dispatch transactions with old jobs APIs and synthetic Cloud Tasks transport.

The actual old binary's re-arm gap is reproduced on the emulator: after takeover, a re-arm during its shadow phase can leave a new row behind its cursor while old completion removes the obligation. Generation/token alone cannot make that binary honor an arming revision. Code change required: new consumers now refuse coalescing until Release's expiring all-consumers-new readiness attestation is valid. Missing/false/malformed/expired readiness executes legacy work; it is rechecked transactionally at sealing, resume, every unit/checkpoint and completion. Revocation/expiry hands active groups back. The switch remains default on. Readiness is not inferred from the route probe.

The reserved metadata document stays in the existing jobs collection; tests prove both versions' due queries, dispatch claims and owner queries exclude it (no due_at/uid, ID outside hashed job IDs). No new collection and no workflow/registry skip were added.

Tests cover old leader and follower deliveries (live lease and stale generation), acknowledged-task redrive through the old reconciler, old takeover followed by new takeover with the switch both on and off, fresh cursors, member journals/nonempty old progress retained through handback, old/new producer re-arms during seal preparation and after sealing/checkpoint, post-seal arrivals, readiness revocation/expiry and switch-off mid-group. Mixed-roll tests show old and new workers execute/redrive legacy tasks while coalescing is refused. Before binary rollback, Release must revoke readiness, switch off and drain delegated groups before routing old consumers.

Round 2: accepted F1-F3

Panel review-20261117t214631-a710 returned FIX-FIRST on cc3c09fed19c3256a8bcaa3fe4cfaabd4d084541; all three findings were accepted. This follow-up changes exactly those findings:

  • F1: Legacy claim transactionally captures armed_at/arm_revision as progress_arm. Every checkpoint, destructive-unit admission, segment-journal removal and completion transaction verifies it along with generation/token. A changed arm preserves the obligation and journals, clears the stale cursor, releases its own lease and makes the next generation due. A cursor without an arm stamp is conservatively rewound once at claim; a matching stamped cursor resumes intact. Accepted-delete cascade jobs are unchanged.
  • Pre-existing main gap: confirmed on fetched main 0c999f7a7c1890b62695c05ae9e7f17e711b22c2: legacy claim, checkpoints and completion compare generation/token only, while a re-arm updates armed_at without changing either. Rows added behind the cursor can remain after completion deletes the re-armed obligation. The new legacy path fixes that gap, including readiness-denied and switch-off fallback. The immutable historical-worker tests still reproduce the old binary's limitation; Release readiness/drain requirements remain necessary for old binaries.
  • F2: Coalesced traversal skips the redundant nontransactional tombstone precheck after its transactional member authority check. Legacy single-member traversal retains the precheck.
  • F3: A leader delivery reuses the obligation row already read at claim instead of fetching it again.

New unit tests cover re-arms at checkpoint, unit, journal removal and completion (both new revision producers and old armed_at producers), matching/older/unversioned cursor claims, and a real legacy traversal re-armed after a row is added behind its cursor. Six real-emulator regressions cover readiness-denied and switch-off fallback at checkpoint, unit and completion: the obligation remains pending, then the next generation erases the late row and completes. No frozen source fixtures, CPU budgets, workflows or skip paths were changed.

Validation

All data is synthetic. No production access, GCP tier, deploy or merge. The canonical backend/scripts/run-emulator-proofs.sh includes all four purge/WAL suites and fails its purge leg on a non-loopback host, preventing skipped fixtures from looking green. No .github/ changes, force-pushes or skip hatches.

Round-2 local results: 233 focused unit tests passed, 73 emulator tests passed, zero skipped (15 original purge + 23 coalesced-group + 26 frozen-version/legacy fallback + 9 WAL). The seven canonical guarded files passed under the unchanged 1.00s CPU limit. Full backend pyright reported zero errors; all 45 preflight checks passed (including the 608-test Firestore query guard). The read-growth assertion remains 5 deletions x 350 unmatched history rows per table: 350 shared unmatched result gets versus 1,750 legacy gets. This is synthetic traversal evidence, not billed-read savings.

Commands actually run from the repo root through /Users/dazheng/workspace/omi/bin/omi-heavy run -- (emulator run used an isolated 127.0.0.1:59161, project demo-purge-coalesce):

backend/.venv/bin/python -m pytest backend/tests/unit/test_conversation_batch_purge_coalesced.py backend/tests/unit/test_conversation_batch_purge_resumable.py backend/tests/unit/test_conversation_purge_mixed_version.py backend/tests/unit/test_conversation_batch_purge_authority.py backend/tests/unit/test_conversation_batch_purge_deadlines.py backend/tests/unit/test_conversation_delete_gate_wait.py backend/tests/unit/test_conversation_delete_accept.py backend/tests/unit/test_flag_budget.py backend/tests/unit/test_complete_half_deleted_conversations.py backend/tests/unit/test_batch_result_protocol.py backend/tests/unit/test_batch_intake_outcome.py -q --disable-warnings
# 233 passed
FIRESTORE_EMULATOR_HOST=127.0.0.1:59161 GOOGLE_CLOUD_PROJECT=demo-purge-coalesce PROVIDER_MODE=offline MEMORY_ENABLED=on GOOGLE_AUTH_DISABLE_GCE_CHECK=true GCE_METADATA_HOST=127.0.0.1:9 backend/.venv/bin/python -m pytest -q -p no:cacheprovider backend/tests/integration/test_conversation_batch_purge_emulator.py backend/tests/integration/test_conversation_purge_coalescing_emulator.py backend/tests/integration/test_conversation_purge_mixed_version_emulator.py backend/tests/unit/test_record_wal_handoff_emulator.py
# 73 passed, zero skipped
OMI_PR_BODY_FILE=.agent-artifacts/pr-body.md make preflight
# 45 checks passed; repeated by normal pre-push
backend/.venv/bin/python -m pyright -p backend/pyrightconfig.json --pythonpath backend/.venv/bin/python
# 0 errors (also rerun by normal pre-push and CI)
bash -n backend/scripts/run-emulator-proofs.sh
# passed
# Isolated CI timing reproducer, same canonical runner and CPU guard:
printf '%s\n' tests/unit/test_lifecycle_invariants.py > .agent-artifacts/r2-ci-failed-files.txt
BACKEND_UNIT_TEST_FILE_LIST="$PWD/.agent-artifacts/r2-ci-failed-files.txt" bash -c 'cd backend && bash test.sh'
# 252 passed, 86 expected failures; measured case 0.20s CPU vs 1.00s limit

The emulator is stopped after verification. The purge fixture independently pins the WAL storage factory to synthetic local storage while retaining the original real loopback artifact-delete transport proofs. The earlier intake fixture setup change constructs the cold router harness before its call-phase CPU budget; the route assertions and CPU limit are unchanged.

CI note for this head: initial backend shard 3 passed all lifecycle assertions but the existing CPU guard measured test_latch_clause[batch:leased/entry_deadline] at 1.16s against 1.00s. The canonical BACKEND_UNIT_TEST_FILE_LIST=... bash test.sh reproducer passed all 252 tests (86 expected failures), with that case at 0.20s under the unchanged guard. Only failed CI jobs were requested for rerun on the same SHA; no source, budget, allowlist or workflow changed.

Review disposition

Latest follow-up head: a170f3c07a16c4dac843c12d7c9b8217b5c3ebd4. Round-2 FIX-FIRST findings F1-F3 are fixed as described above. Follow-up panel review-20261117t221555-061d returned SHIP on this exact head (Luna completed; GLM Flash completed just after the initial timeout and was collected). Its two advisory findings were triaged as accepted and deferred because David limited this follow-up to round-2 F1-F3: overflow candidates can fall back to independent scans while the first owner page is occupied; an ambiguous handback commit can undercount fallback telemetry. Neither changes erasure authority or member completion, and neither was changed in this follow-up. Earlier SHIP decisions below apply only to their named prior heads.

Panel review-20261117t200055-f054 returned SHIP on add2fe456b0263b8271443a553979806c04946c3 (all three reviewers completed). All six minor/nit findings were accepted and fixed: preserve original errors if failure settlement/handback also fails and return busy only after settlement; test complete/resumed multi-member WAL sweeps including new orphans; guard dangling/null scan epochs; deterministically exercise leader overflow; exclude reserved control IDs from the half-deleted operator's pending count and name that reader; replace a vacuous finish-result assertion with observable persisted lease/outcome checks. Panel review-20261117t202618-0c2c subsequently returned SHIP with no findings on 0a0796d479331c2991439232ce50e060fa701423 (Luna + GLM completed; DeepSeek ended without a usable answer). CI on that head was green after recovering a checkout-stalled runner and rerunning an isolated v3 CPU timing overrun; its canonical guarded reproducer passed 26 tests at the unchanged 1.00s limit.

While checks ran, main advanced to fd3f497915c5eb489fbe125774396e1c0cbcc0c1. A normal merge into this lane resolves the sole conflict by retaining both the purge switch and main's result-protocol guard. The purge entry was moved away from the shared top insertion point; behavior is unchanged. The frozen runner/traversal match pre-PR main byte-for-byte; the F1 follow-up changes the new legacy runner only. There are no .github/ changes relative to main. Merge head is cc3c09fed19c3256a8bcaa3fe4cfaabd4d084541; its normal pre-push passed all gates. Merged-head panel review-20261117t212106-34c0 returned SHIP with no findings on cc3c09fed19c3256a8bcaa3fe4cfaabd4d084541 (Luna + GLM completed; DeepSeek timed out and was stopped). CI is green on this exact head: 66 checks settled, zero pending/failing. The PR is open, clean and mergeable with no auto-merge. The canonical guarded runner also passed all seven relevant files under the unchanged 1.00s CPU limit.

Failure-Class: FC-stale-selection-used-as-write-authority

Shared and new legacy workers revalidate the selected arm, generation and token inside unit/checkpoint/completion transactions. Old binaries cannot enforce that arm fence, so readiness refuses mixed-version coalescing until all consumers are new. Legacy handback retains journals and original progress.

@Git-on-my-level
Git-on-my-level marked this pull request as ready for review November 17, 2026 16:13
@chatgpt-codex-connector

Copy link
Copy Markdown
Codex Review Summary: ❌ Failed

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

Review Status Commit Review trigger
📝 Code Review ❌ Failed 2026-11-17T16:13:35.165160Z
We couldn’t complete this review. Comment @codex review to try again.
4678175 Draft marked ready
ℹ️ 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.

Preserve re-armed obligations and segment journals, rewind stale discovery and redrive the next generation. Skip redundant group tombstone reads and reuse the leader claim snapshot (panel round 2 F1-F3).

Failure-Class: FC-stale-selection-used-as-write-authority
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Follow-up (not blocking, accepted from independent panel review-20261117t230205-6d41 F1, minor): a non-completed leader finish (held/busy/checkpointed) leaves followers dispatchable at their last lease_until, so a leader pause longer than the lease lets a follower dissolve the group via handback, costing up to 16 independent legacy rescans. Safe (legacy path), not a correctness issue. Fix in a follow-up PR: push followers' due_at past the leader's recheck horizon in the finish transaction.

@Git-on-my-level
Git-on-my-level merged commit f82d921 into main Nov 18, 2026
71 of 73 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/purge-coalesce branch November 18, 2026 01:41
Git-on-my-level added a commit that referenced this pull request Nov 18, 2026
…te (#25647)

## Why
`SYNC_EARLY_CAPTURE_CLAMP_ENABLED`'s `review_by` (2026-11-17) passed, so
`test_flag_budget.py::test_pipeline_env_surface_holds_its_budget` fails
on main (Backend Unit Tests red on main since ~01:41Z 11-18) and blocks
every train, including #25608's. ADR 0006: renew with a reason or
delete.

## Change
- `SYNC_EARLY_CAPTURE_CLAMP_ENABLED`: registry `decision: keep`,
`terminal: keep`, default-on ops kill switch. Renewed to 2026-12-16 with
that reason.
- `BATCH_HELD_POLL_SKIP_ENABLED`: not changed here (removed after review
round 2). It runs true in prod on all four workloads; its owner
(firestore-lead) is asked to record its rollout gates and renew, or turn
it off, before it lapses at 2026-11-19T00:00Z.
- `LISTEN_BATCH_RECONNECT_ENABLED` (2026-11-20) left to its owner.

The other main-red cause (`lifecycle_record_pending_head` manifest
dates) is already fixed on main by 74c8708.

## Contract
Data-only change to `backend/config/flag_budget.json`; no runtime
behavior, reader or flag value changes.

## Test
`pytest tests/unit/test_flag_budget.py` -> 26 passed.

🤖 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/25647?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/25647?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F25647&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. -->
Git-on-my-level added a commit that referenced this pull request Nov 19, 2026
## Summary

Remove the expiring Firestore readiness check from conversation-deletion
purge coalescing. The default-on
`CONVERSATION_BATCH_PURGE_COALESCING_ENABLED` kill switch remains.
Disabling it stops enrollment and hands active groups back to the
existing per-conversation purge path with member journals intact.

This PR publishes the authoritative Cloud Run release floor for #25608
in `backend/deploy/release_floor.json`. Workspace tooling must load the
policy from product main through the GitHub Contents API and refuse
floor-gated operations if the policy is unavailable. Release still needs
to verify all traffic, tagged revisions and queued task targets against
that floor before rollout. Continue renewing the current marker daily
until every purge consumer runs the marker-free release.

## Product invariants affected

- INV-DATA-1. This change preserves the existing production data-plane
authority. Manual backend admission and eligible retained revisions must
satisfy the purge-safe source floor.

## Verification

- 40 focused backend unit tests via `omi-heavy` and the backend
`test.sh` runner.
- 42 coalescing and mixed-version tests against a loopback Firestore
emulator, including a mid-scan kill-switch flip that preserves both
member journals and lets both members finish after redrive.

## Rollback

Use the kill switch for emergency handback. Reverting this PR restores
the marker gate, so Release must write a fresh readiness marker after
verifying consumer compatibility to resume coalescing. Keep the Cloud
Run release floor in place.


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