Skip to content

fix(backend): recognize the sweep's own committed write on crash replay - #12403

Merged
Git-on-my-level merged 1 commit into
mainfrom
jit-sweep-replay-fence
Aug 30, 2026
Merged

Git-on-my-level merged 1 commit into
mainfrom
jit-sweep-replay-fence

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Aug 30, 2026 •

Copy link
Copy Markdown
Member

What

The daily memory sweep recognizes its own already-committed canonical write when it replays after a crash, instead of superseding it with a duplicate.

The defect

backend/scripts/daily_memory_sweep_emulator_test.py — the crash-after-canonical-before-receipt scenario — fails deterministically on main, and has since #12084 introduced it. Reproduced 3/3 at origin/main, at c01861f3cf34, and at 2af083251c itself. It has never passed on merged main.

Two behaviors combine:

  1. _claim_receipt (daily_memory_sweep.py:2175) leases a receipt claim for RECEIPT_LEASE (10 min), and the default claimant is a fresh UUID per invocation (:2854). The next day's run is therefore always a "different claimant" with an expired lease, so it silently re-claims and redoes the work. That is by design and is safe when the redo is exact — the apply layer's deterministic _row_id then yields idempotent_skip.
  2. _apply_candidate (:2653) breaks exactness for slotted facts. The occupant it finds is this same candidate's own write from the crashed attempt, but it matches the sweep_slot_refresh rule intended for legitimate day-N+1 refreshes, so it takes the amend path. amend_fact sets supersedes=[prior], _row_id() hashes supersedes, the row id changes, and deterministic idempotency never fires.

Result per event: the row self-supersedes. One correct active row remains — this is not data loss and no wrong fact is shown — but it leaves a phantom superseded version, duplicate operation and commit rows, ~4 spurious outbox events that re-trigger downstream consumers, and telemetry reporting committed where it should report skipped. That last part is why this would not surface during a ramp: the health metric lies in the same direction as the bug.

The fix

Recognize the replay through the ledger's own sanctioned mechanism. evidence_id_for_ledger_provenance hashes {uid, source_id, source_type, source_version, action_id}, and the sweep's action_id is deterministic per (uid, local_date, source_key) — invariant across the add-vs-amend replay, while a next-day sweep derives a different _plan_id and therefore a different identity. So a genuine slot refresh is untouched; only the crash replay is recognized.

An occupant whose evidence is unreadable falls through to the ordinary authority rules rather than suppressing a write it cannot account for.

Evidence

  • Emulator proof passes with the change (3 runs) and fails without it (3 runs) — verified by applying and reverting.
  • The same test asserts the two behaviors that already worked, so both are held: the crash still leaves exactly one pending receipt, and a concurrent different claimant is still fenced with source_idempotency_conflict.
  • tests/unit/test_daily_memory_sweep.py: 51 passed. The first draft of this change crashed test_sweep_slot_refresh_amends_sweep_occupant_but_never_user_statements on an occupant stub without evidence; that is what the defensive read above fixes.
  • Other scenarios in the emulator proof (deletion race, generation contention, rollover, overlapping runners, paid-wipe) still pass.

Why this was invisible

No workflow in .github/workflows/ runs the Firestore emulator proofs — they are local-only. FC-daily-memory-sweep-fence names daily_memory_sweep_emulator_test.py as its canonical prevention artifact, so the registry reads as covered while the guard was red on main and never executed. Wiring these proofs into CI is the durable fix and is not attempted here.

Blast radius

The vulnerable window is between the canonical apply commit and the _finish_receipt transaction (~100-300 ms per candidate). It does not need a process crash — a residual post-retry failure of that one transaction is enough; a Cloud Run Job task kill mid-batch also lands in it. Because the receipt stays pending and the scheduler revisits pending dates, every crash-in-window deterministically becomes a corruption event on the next run. Order of magnitude ~1e-4 per user-day: negligible at the current 2 enrolled accounts, roughly monthly at ~300, and worse than linear because a larger batch also runs longer.

Failure-Class: FC-daily-memory-sweep-fence

Line-Count-Exception: backend/utils/memory/daily_memory_sweep.py | 4970 -> 4994 | Splitting a ~5000-line transactional module is a strictly larger risk than this 24-line correctness fix, which is an early-return recognition inside one existing branch. The split is worth doing, but not in the same change that repairs a red crash-recovery guard.

Product invariants affected

  • INV-MEM-1 — Held, unchanged. No tier is added, renamed, or split; the change adds no collection and touches no tier assignment or access policy. It only decides whether an already-committed canonical row is re-applied.
  • INV-MEM-4 — Held, and strengthened. Canonical promotion remains the sole Long-term authority and every pending item still gets exactly one terminal route. Before this change a crash replay gave one candidate a second apply — a duplicate operation and commit against a row that had already taken its route. Recognizing the landed effect restores the one-item-one-route property; the skip is accounted as skipped on the receipt rather than silently reported as a fresh committed.

Review in cubic

The crash-after-canonical-before-receipt scenario in the emulator proof has
failed since #12084 introduced it, on every ref tested. A replay always
presents a fresh claimant, so the expired 10-minute receipt lease is
re-claimed and the candidate re-applied. That is safe only while the redo is
exact; for a slotted fact the occupant found is the crashed run's own write,
which matches the day-N+1 slot-refresh rule and takes the amend path. The
resulting supersedes list changes the row id, so the apply layer's
deterministic idempotency never fires and the row self-supersedes.

Recognize the landed effect through evidence_id_for_ledger_provenance, whose
identity is invariant across the add-vs-amend replay but differs for a
genuine next-day refresh. An occupant with unreadable evidence falls through
to the ordinary authority rules rather than suppressing an unaccounted write.

Failure-Class: FC-daily-memory-sweep-fence
@Git-on-my-level
Git-on-my-level merged commit 27420f8 into main Aug 30, 2026
42 checks passed
@Git-on-my-level
Git-on-my-level deleted the jit-sweep-replay-fence branch August 30, 2026 00:15
Git-on-my-level added a commit that referenced this pull request Aug 30, 2026
## Why

Nothing runs the Firestore emulator proofs. Verified 2026-08-30: no
workflow in `.github/workflows/` invokes `emulators:exec`, and none
references any `*_emulator_test.py`. They execute only when someone runs
them by hand.

They are the strongest correctness evidence the memory system has —
crash recovery, deletion races, account-generation contention, day
rollover, overlapping runners, writer cutover — against a real Firestore
emulator, covering classes that fakes cannot reach and a green deploy
does not reveal.

The cost of that gap is concrete. The daily-sweep crash-replay proof was
**red on `main` from the day #12084 introduced it until #12403 repaired
it**, and nobody knew. Worse,
`.github/failure-classes/FC-daily-memory-sweep-fence.json` names
`daily_memory_sweep_emulator_test.py` as that class's
`canonical_prevention_artifact` — so the registry read as covered while
the guard was never executed. A guard artifact CI does not run is worse
than no guard, because it is counted as coverage.

In the same window, #12084 also shipped two live production regressions
of exactly the class these proofs cover (`LegalHoldAuthorityUnavailable`
on conversation finalization, since fixed in #12410; and a duplicate
`new_memory_id` on `/v3/memories`, still open). Both ran for two days.
Neither was surfaced by a test or an alarm — they were found by grepping
service logs after an unrelated deploy.

## What this adds

`backend/scripts/run-emulator-proofs.sh` and a `Backend Emulator Proofs`
workflow that runs it under `firebase emulators:exec`, on backend
memory/database changes.

`firebase.json` already pins the Firestore emulator to `127.0.0.1:8085`,
so `emulators:exec` supplies `FIRESTORE_EMULATOR_HOST` and tears the
emulator down afterwards — a failing proof cannot leave one holding the
port.

The script's environment mirrors `_subprocess_env()` in
`jit_qa_orchestrated_dogfood.py`. `MEMORY_MODE=read` is required: the
production canonical-intake fence defaults to off, and without it every
write-path scenario fails closed with `CanonicalMemoryIntakePausedError`
— a harness precondition, not a defect.

Gating proofs:

- daily sweep — crash / deletion / generation / paid-wipe
- ledger correction, revert, standalone reopen, privacy fence
- writer cutover / rollback / rollforward

## The arbitration proof runs but does not gate

`jit_proactivity_reservation_emulator_test.py` is intermittent against a
freshly started emulator. It deliberately runs concurrent transactions
to prove cross-device reservation, and a cold emulator sometimes loses
them: `Aborted: 409 Transaction lock timeout`, surfacing as `ValueError:
Failed to commit transaction in 5 attempts`. When it completes it
reports correct semantics (`planned=['reserved','rejected']`,
`full_turns=['rejected','reserved']`), so this is an emulator limit
rather than an assertion failure.

Measured today: 3/3 passes against a long-warmed emulator; then two
consecutive failures and one pass under fresh `emulators:exec`,
including a failure when run alone — so it is not accumulated state from
the preceding proofs. Warm-up looks like the mechanism, but that is a
handful of runs, not a characterisation, and the comment in the script
says so.

It therefore runs, reports, and does not gate. Making it fatal would
redden the lane unpredictably, and a lane that fails for reasons nobody
trusts is one nobody reads — precisely the failure this lane exists to
correct. Making it silent would throw away the signal. Characterising
the contention and promoting it back to gating is the obvious follow-up.

## Not a required check

A new workflow is not automatically in branch protection, so this
reports without blocking. Promote it to required once it has a stable
green history — deliberately not done here, since a brand-new lane
gating every backend memory change is how a lane gets disabled instead
of fixed.

## Verification

Run end to end locally against `origin/main` under `firebase
emulators:exec` with Temurin 21: all three gating proofs pass, and the
full run reports `All emulator proofs passed.` The script was also
observed correctly failing the lane (exit 1, named failure) when a proof
genuinely failed, before the arbitration proof was made non-gating.

Failure-Class: none


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/12411?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="Review in cubic"
src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->
pull Bot pushed a commit to codingwatching/omi that referenced this pull request Aug 31, 2026
Nothing ran them. No workflow invoked emulators:exec or referenced any
*_emulator_test.py, so the strongest correctness evidence the memory system has
existed only when someone ran it by hand. The daily-sweep crash-replay proof was
red on main from the day BasedHardware#12084 introduced it until BasedHardware#12403 repaired it, while
FC-daily-memory-sweep-fence named that file as its canonical prevention
artifact -- the registry read as covered while the guard never executed.

Three proofs gate the lane: daily sweep, ledger correction/revert/reopen, and
writer cutover/rollback/rollforward. The arbitration proof runs for signal but
does not gate: it is intermittent against a cold emulator (409 transaction lock
timeout), and a lane that reddens unpredictably is one nobody reads.

Not added to branch protection; promote once it has a stable green history.

Failure-Class: none
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