Skip to content

fix(backend): stop treating an empty extraction as a memory deletion - #12410

Merged
Git-on-my-level merged 1 commit into
mainfrom
fix-empty-conversation-replacement
Aug 30, 2026
Merged

Git-on-my-level merged 1 commit into
mainfrom
fix-empty-conversation-replacement

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

Live production regression

https://api.omi.me/v1/conversations/from-segments on PROD has been returning 500 for most requests since 2026-08-28T01:58Z. Measured over the 6h to 2026-08-30T01:00Z: 393x 500, 130x 200, 6x 422 — a 74% failure rate, steady at 200-480 exceptions/hour.

Every failure is:

LegalHoldAuthorityUnavailable: destructive operation gate is not active in this context

Cause

Bisected by log sampling: zero occurrences at 2026-08-27T12/16/20Z and 2026-08-28T00Z; first occurrence 2026-08-28T01:58:07Z on prod revision backend-add08a4-33114042056-1 (created 01:43Z), the deploy after backend-932e2f5-33095639201-1. The only commit in 932e2f5..add08a4 touching the implicated files is 2af083251c — #12084, the JIT knowledge ledger foundation — which added both the import and the failing line.

replace_conversation_source_firestore requires explicit_memory_deletion authority for an empty write set (memory_apply_store.py:1345, "empty replacement requires privacy gate authority"). That rule is deliberate and correct: emptying a conversation's replacement set normally retracts its canonical rows.

The caller keys that decision on not items. Emptiness is a proxy for two different things:

  • "remove this conversation's rows" — genuinely destructive, and the explicit-deletion callers hold a destructive_operation_gate (7 sites in canonical_memory_adapter.py, plus memory_service.py:137), so those work;
  • "this conversation produced no memories" — an ordinary outcome. Conversation finalization holds no gate, so routers/developer.py:1824 -> process_conversation -> memory_service.py:3848 -> replace_conversation_sourced_memories raised and the request 500'd unhandled through the ASGI stack.

Change

Emptiness cannot distinguish the two callers, but the gate can — so ask it, without letting the answer be fatal. When there are no extracted items and no existing rows for the conversation, attempt to read the deletion token: holding it means a deliberate deletion, so fall through unchanged; not holding it means there is provably nothing to do and no authority is required, so return a no-op.

Three cases, all preserved:

State Behavior
No items, no existing rows, no gate — conversation extracted nothing No-op return. This is the prod fix.
No items, no existing rows, gate held — explicit retraction removing nothing Falls through and still records the replacement, advancing source_generation.
No items, existing rows to retract Never reaches the short-circuit; still refused without authority.

This does not relax the gate. An empty replacement that would genuinely retract rows has a non-empty expected_source_items and never reaches this branch.

A first attempt short-circuited on emptiness alone. The repo's pre-push gate caught it: test_ws_j_delete_privacy.py::test_memory_service_retract_records_empty_source_replacement asserts that an explicit retraction removing nothing must still be recorded (source_generation 1 -> 2). That WS-J audit contract is why the condition keys on the gate rather than on emptiness.

Tests

Two added, in the file that already owns this boundary's contract:

  • test_conversation_yielding_no_memories_is_a_noop_not_a_deletion — reproduces the exact production exception without the change, and asserts the destructive path is never reached (injector.calls == 0) and control state is untouched.
  • test_empty_replacement_over_existing_rows_still_demands_the_gate — commits a row, then empties the same conversation, and asserts LegalHoldAuthorityUnavailable is still raised and the row survives. This is the half that keeps the repair from becoming a relaxation.

The pre-existing test_memory_service_retract_records_empty_source_replacement is the guard for the recorded-retraction case and passes unchanged.

Verified by reverting: the first new test fails with the production exception, the second passes in both states. With the change: 5 + 3 + 39 passed across test_conversation_replacement_backoff.py, test_cascade_retract_convergence.py, and test_ws_j_delete_privacy.py.

Note on scope

Fixing this on main reaches development only. The production deploy is a separate authorized step and is not part of this PR.

Two things worth checking separately, not addressed here: process_conversation is shared with normal mobile/desktop conversation finalization, so the blast radius is likely wider than the developer endpoint; and prod shows scattered 500s on /v3/memories/{id} (many distinct ids, ~1 each) that may be unrelated.

Failure-Class: new

Line-Count-Exception: backend/utils/memory/canonical_memory_adapter.py | 3450 -> 3491 | The change is a 12-line guarded early return plus a multi-line import; the remaining lines are the comment explaining why returning before the destructive boundary is not a relaxation of the deletion gate. That reasoning is the part a future reader most needs, and a subtle compliance boundary is the wrong place to trade it for line count. Splitting this module is worth doing, but not in the change repairing a live 74%-failure production regression.

Product invariants affected

  • INV-MEM-4 — Held, and restored. Canonical promotion remains the sole Long-term authority, and every pending item still takes exactly one terminal route. The short-circuit fires only when there are no items and no existing conversation-sourced rows, so no item exists to be routed and none is created, promoted, archived, or retracted. Before this change that state did not take a route at all — it raised, failing the whole conversation enrichment, so the conversation got neither memories nor a summary.
  • INV-MEM-1 — Held, unchanged. No tier is added, renamed, or split; no collection is created; no tier assignment or access policy is touched. The change only decides whether to enter a write boundary that would perform no writes.

Blast radius (measured after opening this PR)

The developer endpoint is not the only caller. Grouping the app frames across 25 prod tracebacks from the last 2h, every one converges on the same call site — canonical_memory_adapter.py:2029, via memory_service.py:3831 and process_conversation.py — but they arrive from three different entries:

Entry frame Occurrences
routers/conversations.py:336 8
utils/conversations/lifecycle.py:323 7
routers/developer.py:1776 4

routers/conversations.py is the ordinary client-facing conversation route, so this is affecting real client traffic, not only the developer API. Because all paths funnel through the single guarded call site, this change covers all of them.

Backend 5xx by endpoint over 3h for context: /v3/memories/{id} 263, /v1/conversations/from-segments 157, /v3/memories 153, /v1/conversations 15, /v1/conversations/{id}/reprocess 8. In a 90-minute sample of ERROR entries, 26 of 27 were this exception.

Not characterized: whether the /v3/memories and /v3/memories/{id} 5xx share this cause. They did not appear as entry frames in the traceback sample, and HTTP-request log entries do not join 1:1 with traceback entries, so they may be a separate fault. One RuntimeError: canonical write failed: ApplyStatus.invalid_patch (add patch new_memory_id already exists) also appeared. Worth a look independently of this change.

#12084 made replace_conversation_source_firestore require
explicit_memory_deletion authority for an empty write set, which is right when
emptying a conversation retracts its rows. The caller keys that on `not items`,
and emptiness also means "this conversation produced no memories" -- an
ordinary outcome. Conversation finalization holds no gate, so those requests
raised LegalHoldAuthorityUnavailable and 500'd: 393 of 529 requests to
/v1/conversations/from-segments on prod over six hours, since 2026-08-28T01:58Z.

Emptiness cannot separate the two callers, so ask the gate instead without
letting the answer be fatal. Holding it means a deliberate deletion and still
records the replacement; not holding it with nothing to write and nothing to
retract means no authority is required. An empty replacement that would
genuinely retract rows keeps a non-empty expected_source_items, never reaches
the branch, and is still refused.

Keying on emptiness alone also broke the WS-J contract that an explicit
retraction removing nothing is still recorded; that test is the guard.

Failure-Class: new
@Git-on-my-level
Git-on-my-level merged commit 7a312b1 into main Aug 30, 2026
46 checks passed
@Git-on-my-level
Git-on-my-level deleted the fix-empty-conversation-replacement branch August 30, 2026 23:51
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. -->
Git-on-my-level added a commit that referenced this pull request Aug 31, 2026
## What changed and why

Bind JIT admission on every GCP `dev` evaluator (GKE listen, Cloud Run
listen, maintenance), then make first-open, ledger writes,
empty-watchlist suppress, drain, and public-docs hygiene correct before
flipping `jit-processing-v1` to 100% of Omi Beta / TestFlight.
Empty-extraction 500s already landed in #12410. Production `api.omi.me`
PostHog is unchanged.

## Product invariants affected

- INV-AGENT-*
- INV-DATA-1
- INV-MEM-1
- INV-MEM-4
- INV-TASK-2

## How it was verified

- `backend/.venv/bin/python -m pytest
backend/tests/unit/test_backend_runtime_env_validator.py
backend/tests/unit/test_conversation_jit_processing.py
backend/tests/unit/test_first_open_effect_resume.py` — 131 passed after
rebase onto `origin/main`.
- `python3 .github/scripts/check_agent_doc_references.py` and
`check_agents_md_lean.py` — OK.
- `python3 backend/deploy/compose_runtime_env.py` — generated
`runtime_env.yaml` matches overlays (dev TZ recon on, prod off).
- Did not deploy to GCP `dev` or flip PostHog in this PR. After merge:
probe a non-allowlist Beta UID, then operators flip `jit-processing-v1`
to 100% on the **dev** PostHog project only. Keep the two-UID allowlist
until soak.

## Tests

- Runtime-env compose requires PostHog +
`OMI_FIRESTORE_DATA_PLANE_PROJECT` on listen/maintenance.
- `force_process=True` still defers folders/apps when rollout admits;
`bypass_jit_first_open` is the explicit reprocess hatch.
- Empty folders initialize then assign; first-open never
`complete('folder_assignment')` on a skip.
- Ledger writes use the data-plane client; unknown preference slots stay
unslotted.
- macOS/Windows: complete empty watchlist suppresses; incomplete
snapshot consumes the visit; Insight stays gated.
- Cron skips `writer_mode=ledger` dreaming; sweep continues after one
unknown slot.

## Failure class (fixes)

Failure-Class: FC-rollout-flag-absent-from-a-cohost-of-its-code-path

Enabling `jit-processing-v1` while GKE/Cloud Run listen and maintenance
lacked `POSTHOG_PROJECT_API_KEY` (and GKE listen lacked the data-plane
overlay) would have produced two behaviours for the same UID: Cloud Run
chat/sync admitted, listen finalized as `configuration_missing`.

## Test plan

After merge, deploy this PR to GCP `dev`. Probe a **non-allowlist** Beta
UID:

1. `GET /v1/jit/rollout-decision` on desktop-backend and Cloud Run
`backend` → same `effective=enabled` once the flag is on for that UID
(PostHog override before 100% is fine).
2. Live-finalize via GKE listen: logs are not `configuration_missing`;
first-open attaches.
3. Kill-switch drill on **dev** PostHog, including allowlist, then off.
4. Chat `create_standing_trigger` appears on Mac **and** Windows
snapshots.
5. Empty ledger: no ambient nano/full; Windows does not run Insight.
6. Empty extraction conversation is 200.

Then flip `jit-processing-v1` to 100% on the **dev** PostHog project.
Watch writer_mode drain; do not claim extraction is off until `ledger`
is the majority. Keep the two-UID allowlist until soak.

Windows TestFlight floor is builds that include #12381 / #12391 /
#12397; older apps keep the legacy loop and cannot be remotely disabled.

## Line-count exceptions

Oversized files grew by the JIT admission/sweep patches; splitting them
is out of scope for this Beta-readiness PR.

Line-Count-Exception: backend/routers/conversations.py | 1955 -> 1956 |
pass bypass_jit_first_open through create/finalize without splitting the
router
Line-Count-Exception:
backend/utils/conversations/process_conversation.py | 2561 -> 2572 | add
bypass_jit_first_open so force_process stays a lazy-desktop hatch, not a
JIT bypass
Line-Count-Exception: backend/utils/memory/canonical_memory_adapter.py |
3491 -> 3496 | keep empty replace_conversation_source a no-op after
#12410 rebase
Line-Count-Exception: backend/utils/memory/daily_memory_sweep.py | 4994
-> 5008 | unknown-slot ValueError skips that candidate instead of
aborting the day
Line-Count-Exception: backend/utils/sync/pipeline.py | 2527 -> 2528 |
reprocess path sets bypass_jit_first_open


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/12452?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. -->
Git-on-my-level added a commit that referenced this pull request Sep 1, 2026
#12525)

The empty-replacement destructive gate is right for deletion callers, but the
conversation-extraction entry (finalize and reprocess) reaches it whenever a
model pass extracts zero memories over a conversation that already has
canonical rows. Reprocess holds no explicit_memory_deletion gate, so those
requests died with LegalHoldAuthorityUnavailable — the residual prod 500s
after #12410 (3/day on routers/conversations.py reprocess_conversation).

Extraction emptiness is model variance, not deletion intent. The boundary now
takes intent as an explicit argument (the prescription this failure class
already carries): replace_conversation_sourced_memories grows
empty_set_intent, the extraction wrapper declares "extraction", and an empty
extraction over existing rows keeps them as a successful no-op. Deletion
callers keep the default "retraction" semantics, and a caller genuinely
holding the gate still falls through so the retraction is recorded.

Failure-Class: FC-destructive-gate-keyed-on-proxy-for-intent

Co-authored-by: Claude Fable 5 <[email protected]>
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