Skip to content

fix(backend): serve the legacy graph when the canonical read is unavailable - #11623

Merged
mdmohsin7 merged 1 commit into
mainfrom
fix/knowledge-graph-legacy-fallback
Aug 15, 2026
Merged

mdmohsin7 merged 1 commit into
mainfrom
fix/knowledge-graph-legacy-fallback

Conversation

@mdmohsin7

@mdmohsin7 mdmohsin7 commented Aug 15, 2026 •

Copy link
Copy Markdown
Member

Summary

GET /v1/knowledge-graph has returned 503 knowledge_graph_unavailable to essentially every user since 13 Aug 05:33 UTC. This restores a fallback so the route serves the legacy graph when the canonical read is unavailable.

Root cause

5724a10084 ("feat: converge universal memory and task authority") repointed the route at the canonical (v3) graph and deleted the legacy read in the same commit, leaving nothing to fall back to:

-from database import knowledge_graph as kg_db
+        page = canonical_graph_service.get_canonical_knowledge_graph(...)
+    except canonical_graph_service.CanonicalGraphReadUnavailable as exc:
+        raise HTTPException(status_code=503, detail='knowledge_graph_unavailable')

The canonical read requires users/{uid}/memory_state/head. That document is only written by canonical intake in memory_apply_store, which is fenced by _require_canonical_intake_enabled() whenever MEMORY_MODE is not write/read. Production runs MEMORY_MODE=off, so the head is never written — 6 of 7 sampled accounts have none, and the read raises MISSING_STATE_HEAD.

The route was pointed at a store production deliberately does not populate.

Impact

  • ~96% of requests failing — 314 × 503 against 13 × 200 in a sampled hour, the same shape every hour since 13 Aug.
  • Worst for long-standing users: their graphs were built through the legacy path, which the commit stopped reading.
  • No new user gets one either, since intake is fenced — the feature is dark in both directions.
  • Nothing was lost. The graphs sit intact in the legacy store; this was a visibility outage.

Timeline: commit merged 11 Aug 17:18 → first revision carrying it (backend-strip-meu-0509, containing 0c36d94) deployed 13 Aug 05:09 → first 503 at 05:33, 24 minutes later. Confirmed 1947a53 and 9dfcf0d do not contain the commit; 0c36d94 and 66fe467 do.

Change

get_knowledge_graph catches CanonicalGraphReadUnavailable and serves kg_db.get_knowledge_graph(uid). An account with no graph gets an empty graph, never an error.

/v1/knowledge-graph/canonical is deliberately unchanged — a caller asking for canonical specifically should be told it is unavailable rather than silently handed legacy data.

Deliberately not done

Flipping MEMORY_MODE to write. It would un-fence canonical intake globally, only help after each user's next memory write, and do nothing for the graphs users have today. Too wide a blast radius for a read bug.

Verification

pytest tests/unit/test_knowledge_graph_legacy_fallback.py    -> 4 passed
  reverted the fix, re-ran                                   -> 2 of 4 FAIL (tests do catch it)
pytest (5 knowledge-graph test files)                        -> 30 passed
pytest (5 memory-state / memory-apply test files)            -> 49 passed
black --line-length 120 --skip-string-normalization          -> unchanged

Not verified against prod. The canonical-unavailable path is covered by unit tests with the real router; I have not exercised the deployed endpoint.

Product invariants affected

none

Failure class (fixes)

Failure-Class: none

Review in cubic

…ilable

GET /v1/knowledge-graph has returned 503 knowledge_graph_unavailable to
essentially every user since 13 Aug 05:33 UTC.

5724a10 repointed the route at the canonical (v3) graph and deleted the
legacy read in the same commit, leaving no fallback. The canonical read needs
users/{uid}/memory_state/head, which is only written by canonical intake in
memory_apply_store — and that path is fenced by _require_canonical_intake_enabled()
whenever MEMORY_MODE is not write/read. Production runs MEMORY_MODE=off, so the
head is never written: 6 of 7 sampled accounts have none, and the read raises
MISSING_STATE_HEAD for them.

The route was pointed at a store production deliberately does not populate.
Measured impact: ~96% of requests failing (314 x 503 against 13 x 200 in a
sampled hour), sustained for two days. The graphs themselves were never lost —
they sit intact in the legacy store, just no longer read.

The route now falls back to kg_db.get_knowledge_graph when the canonical read
is unavailable. An account with no graph gets an empty graph rather than an
error. /v1/knowledge-graph/canonical is deliberately left alone: a caller asking
for canonical specifically should be told it is unavailable, not silently handed
legacy data.

This restores the read path only. It does not touch MEMORY_MODE — turning that
on would un-fence canonical intake globally, would only help after each user's
next memory write, and would do nothing for the graphs users have today.

Verification:
  pytest tests/unit/test_knowledge_graph_legacy_fallback.py -> 4 passed
  reverted the fix and re-ran -> 2 of 4 fail, confirming the tests catch the bug
  pytest (5 knowledge-graph test files) -> 30 passed
  pytest (5 memory-state/apply test files) -> 49 passed
  black --line-length 120 --skip-string-normalization -> unchanged

Failure-Class: none

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

1 issue found across 2 files

Confidence score: 4/5

  • In backend/routers/knowledge_graph.py, the except CanonicalGraphReadUnavailable fail-open path silently serves the legacy graph without logging/metrics, so canonical read outages can be masked and harder to detect while users see stale or inconsistent graph data — add structured logging and a counter/trace tag in that branch to restore observability.
Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="backend/routers/knowledge_graph.py">

<violation number="1" location="backend/routers/knowledge_graph.py:139">
P2: The new fail-open branch that serves the legacy graph when the canonical read raises is a silent degrade path with no telemetry: the `except CanonicalGraphReadUnavailable` block just returns, with no logging and no `record_fallback` call. Per backend/AGENTS.md and `utils/observability/fallback.py` (“Silent UX healing is allowed; silent ops is not. New degrade/failover branches must call record_fallback”), this branch should emit a fallback event so the canonical-outage condition that caused the 503 incident stays observable. As written, a recurrence (canonical permanently unavailable for every user) is indistinguishable from a healthy state in metrics.</violation>
</file>

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

Re-trigger cubic

)
except canonical_graph_service.CanonicalGraphReadUnavailable as exc:
raise HTTPException(status_code=503, detail="knowledge_graph_unavailable") from exc
except canonical_graph_service.CanonicalGraphReadUnavailable:

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: The new fail-open branch that serves the legacy graph when the canonical read raises is a silent degrade path with no telemetry: the except CanonicalGraphReadUnavailable block just returns, with no logging and no record_fallback call. Per backend/AGENTS.md and utils/observability/fallback.py (“Silent UX healing is allowed; silent ops is not. New degrade/failover branches must call record_fallback”), this branch should emit a fallback event so the canonical-outage condition that caused the 503 incident stays observable. As written, a recurrence (canonical permanently unavailable for every user) is indistinguishable from a healthy state in metrics.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/routers/knowledge_graph.py, line 139:

<comment>The new fail-open branch that serves the legacy graph when the canonical read raises is a silent degrade path with no telemetry: the `except CanonicalGraphReadUnavailable` block just returns, with no logging and no `record_fallback` call. Per backend/AGENTS.md and `utils/observability/fallback.py` (“Silent UX healing is allowed; silent ops is not. New degrade/failover branches must call record_fallback”), this branch should emit a fallback event so the canonical-outage condition that caused the 503 incident stays observable. As written, a recurrence (canonical permanently unavailable for every user) is indistinguishable from a healthy state in metrics.</comment>

<file context>
@@ -119,8 +136,12 @@ def get_knowledge_graph(uid: str = Depends(auth.get_current_user_uid)):
         )
-    except canonical_graph_service.CanonicalGraphReadUnavailable as exc:
-        raise HTTPException(status_code=503, detail="knowledge_graph_unavailable") from exc
+    except canonical_graph_service.CanonicalGraphReadUnavailable:
+        # Canonical intake is fenced off in production (MEMORY_MODE), so most
+        # accounts have no memory_state/head and the canonical read is
</file context>

@mdmohsin7
mdmohsin7 merged commit 125f8e4 into main Aug 15, 2026
42 of 43 checks passed
@mdmohsin7
mdmohsin7 deleted the fix/knowledge-graph-legacy-fallback branch August 15, 2026 10:36
mdmohsin7 added a commit that referenced this pull request Aug 15, 2026
…e canonical fence (#11627)

## Summary

Conversation merge **and cascade delete** have both been broken since
**13 Aug**, from the same cause. Reported symptom: the app sits on
"merging" until it is restarted, and afterwards the merged conversation
**and both originals** are all listed.

## Root cause

`perform_merge_async` builds the merged conversation, then deletes each
source. `_delete_conversation_and_related_data` retracts the source's
canonical memories first and **re-raises** if that fails — deliberately,
so a source is never deleted while active memories still point at it.

Retraction runs through the canonical replace boundary, which
`_require_canonical_intake_enabled()` fences whenever `MEMORY_MODE` is
not `write`/`read`. **Production runs `off`.**

So every merge created the merged conversation, raised on the first
source, unwound into `_handle_merge_failure`, and reset the sources to
`completed`. **Step 10 — the FCM that tells the app the merge finished —
was never reached**, which is why the UI never left "merging" without a
restart, and why both originals came back.

Production logs, every merge, 1 ms apart:

```
Error processing merged conversation: 503: Memory writes are globally paused
Error deleting memories for <id>: canonical memory intake is globally paused
Merge failed with exception: canonical memory intake is globally paused
Merge failed for conversations
```

| Day | Merge failures |
|---|---:|
| 10 Aug | 0 |
| 12 Aug | 0 |
| **13 Aug** | **27** |
| 14 Aug | 18 |

Same origin as #11623: `5724a10084` introduced
`_require_canonical_intake_enabled`, and the first revision carrying it
deployed 13 Aug 05:09.

## Fix

The fence closes *intake*, so a conversation ingested while it was
closed has **no canonical memories to retract in the first place**.
Cleanup now reads the source cohort — an unfenced read — and skips
retraction only when the source has no active canonical memories.
Nothing can dangle because there is nothing there.

Unchanged:
- A source that **does** have memories still aborts exactly as before.
- A cohort read that **fails** also aborts, rather than assuming the
source is empty.
- The fence callback still fires on the skip path, since everything
after retraction destroys source state and failure handling must not
treat the source as untouched.

## On the existing tests

`test_merge_conversations_canonical_delete.py` describes a source that
*has* memories. Rather than rewrite its assertions — which would delete
the guard it exists to provide — the precondition is stated in a
fixture. Every assertion in that file is byte-identical; all 8 still
pass.

## A third breakage, found by self-review and unreported

`DELETE /v1/conversations/{id}?cascade=true` is the app's **only**
delete path (`app/lib/backend/http/api/conversations.dart:136`). It
called `retract_conversation_memories` with no error handling, so the
same fence turned every delete into a 500:

| Day | cascade-delete 500s |
|---|---:|
| 11 Aug | 0 |
| 12 Aug | 0 |
| **13 Aug** | **300** (query cap; 400 of 400 sampled were 500) |
| 14 Aug | 300 |

Users have been unable to delete conversations for two days and nobody
reported it. Same 13 Aug onset as merge and as the knowledge-graph 503s
in #11623.

The skip logic now lives in `utils/memory/retraction_scope.py` and both
call sites share it, so merge and delete cannot drift apart.

## Scope

This does **not** turn canonical intake back on. Merges work again;
memory extraction stays fenced while `MEMORY_MODE=off`. That flag is
still the underlying condition behind this, #11623, and the
silently-skipped memory extraction on every processed conversation —
worth a separate decision.

## Verification

```
pytest test_merge_skips_retraction_without_canonical_memories.py  -> 4 passed
  reverted the fix, re-ran                                        -> 3 of 4 FAIL (tests catch it)
pytest (5 merge test files)                                       -> 59 passed
black --line-length 120 --skip-string-normalization               -> unchanged
```

Not exercised against production — the fenced path is covered by unit
tests, but I have not run a real merge on the deployed backend.

## Line-Count-Exception

Line-Count-Exception: backend/routers/conversations.py | 1508 -> 1515 |
guards the cascade-delete retraction behind the shared skip helper; the
fence otherwise makes every delete a 500

## Product invariants affected

- **INV-MEM-1** — three product memory tiers. Matched on path globs; the
tier model is untouched. This change only decides *when* retraction
runs, never what a memory is or which tier it belongs to. No tier
vocabulary, promotion rule, or storage shape is altered, and the guard
test for the invariant is unchanged.

Worth noting **INV-MEM-3** (no legacy fallback after canonical
selection) is *not* violated: nothing here falls back to a legacy store.
When retraction is required it still runs through the canonical path and
still aborts on failure; the skip applies only where the canonical scope
is provably empty.

## Failure class (fixes)

Failure-Class: none
Git-on-my-level added a commit that referenced this pull request Aug 18, 2026
Second instance of the same cause in three weeks: PR #11623 restored the
read path after 5724a10 repointed GET /v1/knowledge-graph at canonical
state that production never provisions; this PR restores the mutation side
of the same repoint.

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

## Problem

Every mobile user who opens the knowledge-graph page and taps rebuild
gets the raw backend error rendered to their screen:

```
Exception: Failed to rebuild knowledge graph:
{"detail":"Canonical knowledge graph state is derived from canonical memories and cannot be deleted or rebuilt directly."}
```

`165c041a93` (2026-07-28) introduced the 409 on `POST
/v1/knowledge-graph/rebuild` and `DELETE /v1/knowledge-graph` behind a
**real per-account predicate**:

```python
def _is_assertion_backed_graph_account(uid: str) -> bool:
    if pin_memory_system(uid, db_client=firestore_db) == MemorySystem.CANONICAL:
        return True
    return kg_db.has_stored_memory_graph_assertions(uid, db_client=firestore_db)
```

`5724a10084` (2026-08-11, "converge universal memory and task
authority") replaced that whole body with an unconditional `return
True`. A correct per-account gate became a global one, so
`_require_legacy_graph_mutation()` 409s **every** account — including
accounts that have no canonical graph and therefore no derived state to
protect.

Those accounts have no canonical graph because the canonical read is
fenced on `users/{uid}/memory_state/head`
(`backend/utils/memory/canonical_graph.py`), and that doc is written
only inside the canonical apply transaction
(`backend/database/memory_apply_store.py`). The convergence deliberately
shipped no backfill. Memories survive this because their read path
unions canonical + historical
(`backend/utils/memory/memory_service.py`); the graph got the fence
without the union.

This is the mutation half of #11623, which restored the same repoint's
**read** half (GET falls back to the legacy graph on
`CanonicalGraphReadUnavailable`). #11623 did not touch rebuild or
delete.

## Fix

Repair the one predicate, which fixes rebuild and delete together rather
than patching route by route (AGENTS.md: "Repair the Failure-Class
Boundary"):

- `_is_assertion_backed_graph_account()` is a real per-account probe
again: canonical graph state established (the canonical read succeeds
for that uid), or stored memory-graph assertions present.
`pin_memory_system` no longer exists after the convergence and is banned
from public memory surfaces by
`test_universal_memory_route_surfaces.py`, so establishment is probed
through the canonical graph service itself instead of re-deriving the
head fence in the router.
- `POST /v1/knowledge-graph/rebuild` performs the legacy delete +
background rebuild again for accounts with no canonical state; the
background task sources memories through `MemoryService.read`, whose
read already unions canonical and historical memories.
- `DELETE /v1/knowledge-graph` performs the legacy delete again for
those accounts.
- When canonical state **is** established (or assertions are stored),
both routes keep the 409 and the existing message, unchanged. That
behaviour is intended: derived state must not be mutated directly.

Style follows #11623: fall back to the legacy store when canonical is
genuinely unavailable for that account; `/v1/knowledge-graph/canonical`
still reports 503 because that caller asked for canonical specifically.

## Tests

`backend/tests/unit/test_knowledge_graph_canonical_mutation_routes.py`
previously asserted the broken behaviour (409 for
`"uid-arbitrary-account"`, and `_is_assertion_backed_graph_account(...)
is True` for any uid). That was a static tripwire pinning the constant,
not coverage of a contract, so it is corrected rather than kept. The
suite is now behavioural, driven through the FastAPI route boundary with
`TestClient`:

- **legacy-principal test** (AGENTS.md: "New fail-closed gates ship with
a legacy-principal test"): no `memory_state/head`, no assertions →
rebuild returns 200 `rebuilding` and schedules the rebuild task, delete
returns 200 `deleted`, both after the legacy delete ran.
- converse: canonical read available → both routes 409 with
`CANONICAL_GRAPH_MUTATION_CONFLICT` and no legacy mutation.
- stored assertions with no state head → still 409.
- the predicate answers differently for two different uids (it cannot be
a constant again).
- the rebuild task filters locked memories and feeds the legacy rebuild;
it is a no-op for an assertion-backed account.

## Verification

All commands run from `backend/` on this branch, `.venv` interpreter
(Python 3.11).

```
python -m pytest tests/unit/test_knowledge_graph_canonical_mutation_routes.py -q
  -> 7 passed

git stash push -- routers/knowledge_graph.py   # revert the fix, keep the tests
python -m pytest tests/unit/test_knowledge_graph_canonical_mutation_routes.py -q
  -> 5 failed, 2 passed
     (legacy rebuild, legacy delete, per-account predicate, and both rebuild-task
      cases fail without the fix — the regression proof)
git stash pop

python -m pytest \
  tests/unit/test_knowledge_graph_canonical_mutation_routes.py \
  tests/unit/test_knowledge_graph_legacy_fallback.py \
  tests/unit/test_knowledge_graph_canonical_pagination.py \
  tests/unit/test_knowledge_graph_extract_helper.py \
  tests/unit/test_knowledge_graph_extract_route.py \
  tests/unit/test_memory_graph_assertion_read.py \
  tests/unit/test_historical_graph_enrichment.py \
  tests/unit/test_universal_memory_route_surfaces.py \
  tests/unit/test_universal_memory_task_authority.py \
  tests/unit/test_rate_limiting.py -q
  -> 162 passed, 1 skipped

python scripts/check_module_stub_pollution.py
  -> Checked 918 backend test file(s); 0 violation(s).

black --line-length 120 --skip-string-normalization routers/knowledge_graph.py \
  tests/unit/test_knowledge_graph_canonical_mutation_routes.py
  -> 2 files left unchanged

make preflight  (OMI_PR_BODY_FILE set to this body)
  -> see below
```

`test_universal_memory_route_surfaces.py` and
`test_universal_memory_task_authority.py` are included deliberately:
they are the ratchets that forbid `pin_memory_system` and direct
historical-store imports in this router, and they constrain how the
predicate could be rebuilt.

**Not verified:** the change was not exercised against a live backend or
a Firestore emulator. Verification is route-boundary tests with the
canonical graph service and `kg_db` stubbed; the Firestore reads
themselves (`has_stored_memory_graph_assertions`,
`kg_db.delete_knowledge_graph`, `MemoryService.read`) are pre-existing
calls restored verbatim from `165c041a93`/the convergence and are not
re-proved here. No mobile client was run against this branch.

## Failure class

Failure-Class: new

`FC-derived-state-gate-without-legacy-source-path` — when a route is
repointed from a legacy store to derived canonical state, every
principal whose canonical state is not yet provisioned must keep a
served path, on the read side and the mutation side alike.

Why a new class and not an existing one:

- This is the **second** instance of the same cause in three weeks.
#11623 repaired the read side of the very repoint whose mutation side
this PR repairs. AGENTS.md: "If two or more recent fixes share the
cause, add a reusable guard surface in the same PR." The reusable guard
is the legacy-principal route-boundary suite named in
`canonical_prevention_artifact`, alongside #11623's read-side suite.
- Near neighbours considered and rejected:
`FC-gate-principal-outside-consolidated-entitlement` (about synthetic
gate/CI principals dropped from a consolidated entitlement set, not
about derived state that was never provisioned for real users);
`FC-unestablished-capability-default` (a client rendering a
not-yet-established capability's default value, not a server route
denying on unprovisioned state); `FC-ship-before-required-route` (a
client shipping ahead of a route's existence — the route exists here);
`FC-denial-rendered-as-empty-success` (the opposite failure mode: this
bug renders the denial loudly rather than hiding it as empty success);
`FC-split-mutation-authority` (mutation authority is correctly
single-owner here; the defect is that the gate protecting it has no
per-account basis).

## Out of scope (follow-ups)

- **Mobile renders any non-200 as an empty memories list** —
`app/lib/backend/http/api/memories.dart` returns `[]` for any non-200,
and `backend/routers/memories.py` has a circular 503 fallback. Separate
bug, separate PR.
- **Migrating clients off the rebuild endpoint** — Flutter
`memory_graph_page.dart` and `onboarding/wrapper.dart`, macOS
`MemoryGraphPage.swift`, Windows. Follow-up; this PR keeps the endpoint
working for them.
- **Config split-brain** — GKE `backend-listen` runs
`MEMORY_ENABLED=off` while Cloud Run `backend` runs `MEMORY_ENABLED=on`.
Not touched here.

Per AGENTS.md: "Do not broaden a safe bug-fix PR into an unreviewable
migration."


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/11783?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 18, 2026
…y knowledge-graph mutation (#11799)

Hardens the per-account knowledge-graph mutation gate restored by #11783
before it ships (prod still serves `523d194333`). Findings from an
adversarial review of that PR — "nothing blocking", four concrete fixes
and one documented gap.

Failure-Class: FC-derived-state-gate-without-legacy-source-path

Product invariants touched (path-glob match): **INV-MEM-1**. The diff
changes no tier vocabulary, no collection layout, and no default access
policy — it only changes how one route classifies the *absence* of
canonical state. Cited because `backend/utils/memory/canonical_graph.py`
is inside the invariant's globs.

Failure-class rationale: the class's contract is "gate on a per-account
probe of whether the derived state is actually established, and keep the
pre-migration source path served for accounts that fail that probe".
#11783 restored the probe; this PR fixes the probe's classification,
which is the same contract. Registry edit is limited to appending two
`canonical_prevention_artifact` paths (the probe and its test); no
definition text, status, or evidence field was touched.

## 1. Mutation fail-open on a destructive path (SHOULD-FIX)

`_has_canonical_graph_state` called `get_canonical_knowledge_graph` and
treated **every** `CanonicalGraphReadUnavailable` as "canonical state is
not established". `read_memory_v3_trusted_account_generation`
(`backend/utils/memory/v3/account_generation_source.py`) swallows every
head-get exception into `READ_FAILED`, so a Firestore timeout or
permission blip on `users/{uid}/memory_state/head` was indistinguishable
from an absent document — and `POST /rebuild` / `DELETE
/v1/knowledge-graph` then deleted the user's legacy
`knowledge_nodes`/`knowledge_edges`.

`GET` may fail open on any unavailable canonical read (#11623): worst
case is a stale view. These routes destroy the store `GET` would have
shown. Copying the catch-all onto the mutation side was the miss.

New `canonical_graph.probe_canonical_graph_state` returns a tri-state
keyed on the **typed** `V3AccountGenerationFailureReason` enum, not on
strings:

| head read result | probe | route |
|---|---|---|
| valid head document | `ESTABLISHED` | 409 conflict |
| `MISSING_STATE_HEAD` | `UNESTABLISHED` | legacy mutation allowed |
| `READ_FAILED`, `MALFORMED_STATE_HEAD`, `UNSUPPORTED_SCHEMA`,
`UID_MISMATCH`, `SOURCE_MISMATCH`, `MALFORMED_ACCOUNT_GENERATION` |
`INDETERMINATE` | **503, nothing deleted** |
| head reads cleanly but carries no usable revision fence |
`INDETERMINATE` | **503, nothing deleted** |

`_rebuild_graph_task` re-runs the same decision and stops on anything
other than `ALLOWED`, so the background half cannot rebuild while the
state is unverified either.

**Probe shape — took the reviewer's alternative.** The old probe
materialized a whole canonical page (`limit=1`, plus the atlas query,
plus the trailing revision re-read) to answer a boolean, which made the
answer depend on `MEMORY_V3_CURSOR_SECRET` and on the atlas composite
index — a missing cursor secret came back as `missing_cursor_secret`,
i.e. "no canonical state", i.e. delete. The head document is the actual
"canonical state exists" signal and only the canonical apply transaction
writes it, so the probe now reads that one document.
`_read_canonical_graph_revision` and the probe share
`_revision_from_trusted` so the two cannot drift on what counts as a
well-formed head.
`test_the_probe_needs_no_cursor_secret_and_no_atlas_query` pins this:
the fake client raises if anything calls `.collection()`.

Choice of 503 over 409: 409 asserts "derived state owns this graph",
which is exactly the claim we could not verify. 503 is honest and
retryable, and it does not reuse a message that mobile renders as a
permanent refusal.

## 2. Tests now bind to the case they claim to protect (SHOULD-FIX)

The reviewer was right that
`test_established_canonical_state_still_conflicts` stubbed a page with
non-empty `nodes`, so a production body wrongly written as `return
bool(page.nodes or page.edges)` would still have passed it. The whole
suite now stubs the trusted head read — the real seam the gate depends
on — instead of the page.

New tests:
- `test_an_established_head_with_zero_assertions_still_conflicts` — head
exists, zero assertions. `has_stored_memory_graph_assertions` is
replaced with a raiser, so the test fails if the gate consults it at all
instead of deciding on the head.
- `test_an_unanswered_canonical_probe_must_not_delete_the_legacy_graph`
— parametrized over all six non-`MISSING_STATE_HEAD` reasons; asserts
nothing was deleted, no rebuild was scheduled, and both routes return
503.
-
`test_a_malformed_head_without_a_read_error_must_not_delete_the_legacy_graph`.
- `test_rebuild_task_is_a_noop_when_the_canonical_probe_is_unanswered`.
- `test_the_legacy_fail_open_reports_shared_fallback_telemetry` /
`test_a_conflicting_account_reports_no_fallback`.
- New file `tests/unit/test_canonical_graph_state_probe.py` covers the
probe directly, including
`test_a_thrown_head_read_is_classified_as_read_failed_not_absent`, which
drives a client that raises `TimeoutError` so the classification comes
from the real reader rather than a hand-written enum value.

The existing legacy-principal tests (`test_legacy_principal_can_rebuild`
/ `_can_delete`) are retained — the fail-closed arm still ships with its
legacy-principal proof.

### Each new test proved to fail for its own specific reason

Not "5 of 7 fail once the function disappears". Six independent
single-line mutations were applied to the shipped code, one at a time,
restoring between each. Failure line reported by `pytest --tb=line`:

| Mutation | Test that failed | Assertion |
|---|---|---|
| A: probe collapses every unavailable reason into `UNESTABLISHED` (the
pre-fix semantics) |
`test_an_unanswered_canonical_probe_must_not_delete_the_legacy_graph[read_failed]`
| `assert ['uid-arbitra...rary-account'] == []` |
| A |
`test_rebuild_task_is_a_noop_when_the_canonical_probe_is_unanswered` |
`AssertionError: legacy rebuild ran while canonical state was
unverified` |
| A | `test_every_other_failure_reason_is_indeterminate[read_failed]`
(+5 params) | `assert <CanonicalGraphState.UNESTABLISHED> is
<CanonicalGraphState.INDETERMINATE>` |
| A | `test_a_thrown_head_read_is_classified_as_read_failed_not_absent`
| same |
| B: an established head no longer short-circuits the gate |
`test_an_established_head_with_zero_assertions_still_conflicts` |
`AssertionError: an established head must decide the gate on its own` |
| C: fail-open branch stops calling `record_fallback` |
`test_the_legacy_fail_open_reports_shared_fallback_telemetry` | `assert
0 == 1` |
| D: `record_fallback` fires on every call, conflicts included |
`test_a_conflicting_account_reports_no_fallback` | `assert
[{'component'...}] == []` |
| E: head with no usable revision fence treated as `ESTABLISHED` |
`test_a_head_without_a_usable_revision_fence_is_indeterminate` | `assert
<ESTABLISHED> is <INDETERMINATE>` |
| F: probe goes back to materializing a canonical page |
`test_the_probe_needs_no_cursor_secret_and_no_atlas_query` |
`AssertionError: the state probe paged the canonical atlas` |

Negative control: under mutation A,
`test_an_established_head_with_zero_assertions_still_conflicts` and
`test_the_legacy_fail_open_reports_shared_fallback_telemetry` both still
**passed** — they do not bind to that line, which is what makes the
table above meaningful rather than a blast radius.

## 3. Fallback telemetry (NIT, repo rule)

The fail-open to legacy mutation now calls the shared `record_fallback`
(`component=knowledge_graph`, `from_mode=canonical_graph`,
`to_mode=legacy_graph`, `reason=unmigrated_principal`,
`outcome=degraded`) per `AGENTS.md` and
`docs/agents/fallback-telemetry.md`. No new counter: `knowledge_graph`
was added to `ALLOWED_COMPONENTS` and `unmigrated_principal` to
`ALLOWED_REASONS` in `utils/observability/fallback.py`, so it lands on
the existing `omi_fallback_total`. The conflict and unverified arms
deliberately do not emit — those are hard refusals, and inflating the
counter with them would destroy the "how many accounts still run on the
legacy path" reading this exists to give.

## 4. Banned import (NIT)

`backend/AGENTS.md` (Service Map): `database._client.db` "remains a
legacy lazy compatibility proxy only; do not use it in new code" — use
`get_firestore_client()` at call time. #11783 reintroduced the proxy
import; removed in its own commit (`chore(backend): stop the
knowledge-graph router using the legacy Firestore proxy`).
Behaviour-identical: `_LazyFirestoreClient.__getattr__` already
delegates to `get_firestore_client()`.

## 5. Known gap, documented not fixed: rebuild deletes before it
rebuilds

`POST /rebuild` calls `kg_db.delete_knowledge_graph(uid)` and returns
200 before the rebuild worker runs. If the worker dies the user is left
with no graph, and `_rebuild_graph_task` re-checks the gate *after* the
delete — an account that becomes assertion-backed (or whose head read
starts timing out) in that window no-ops and the graph stays gone. This
is the restored pre-`5724a10084` contract, not a hole introduced here,
and it is deliberately **not** restructured in this PR. **There is no
test coverage for "delete succeeded, rebuild failed."** Tracked: #11796.

Note that this PR slightly widens that window's failure modes — the new
`UNVERIFIED` arm is another way the post-delete re-check can stop the
rebuild. It also removes the far worse version of the same problem:
before this PR, the transient failure deleted the graph in the first
place.

## Verification

Branched from `origin/main` at `494edbb7f8` (contains #11783). Python
3.11.15.

```
$ backend/test.sh tests/unit/test_canonical_graph_state_probe.py \
    tests/unit/test_knowledge_graph_canonical_mutation_routes.py \
    tests/unit/test_knowledge_graph_legacy_fallback.py
tests/unit/test_canonical_graph_state_probe.py                       11 passed
tests/unit/test_knowledge_graph_canonical_mutation_routes.py         21 passed
tests/unit/test_knowledge_graph_legacy_fallback.py                   11 passed

$ pytest -q tests/unit/*canonical_graph* tests/unit/*knowledge_graph* \
    tests/unit/*fallback* tests/routers/*knowledge*
145 passed in 5.72s

$ OMI_PR_BODY_FILE=<this file> make preflight
Manifest checks passed: 25 check(s).
PR preflight passed: 25 checks in 104.94s.        # exit 0

$ scripts/failure-class validate --pr-body-file <this file>
"ok": true, "declaration": "FC-derived-state-gate-without-legacy-source-path"
```

`backend/test.sh` runs the whole unit tree, and on this machine it
reported 16 unrelated files as failed — every one of them the
**fast-unit CPU-duration guard** (`0.13s > 0.12s`, e.g.
`test_desktop_transcribe.py`, `test_windows_rest_inventory.py` which
itself logs `7 passed`), not an assertion failure. None of them are in
this diff, and the three files above are not among them. `make
preflight` — the actual gate — is green.

Mutation harness output for the table in section 2 is reproduced above
verbatim from `pytest --tb=line`; the harness itself was a throwaway
script and is not in the diff.

### Not verified

- **No live/staging exercise of the real user-facing path.** Every
result here is hermetic unit tests against fakes. The 503 arm in
particular has not been observed against a real Firestore timeout, and
no client (mobile or desktop) was run against the new 503 to see how it
renders — #11783's original defect was mobile printing a 409 body to the
screen, so the new `CANONICAL_GRAPH_STATE_UNVERIFIED` string deserves a
look from someone with the app in front of them.
- **No measurement of how often `INDETERMINATE` will actually fire in
production.** If head reads flap, users will see 503s where they
previously (silently, destructively) succeeded. The new
`record_fallback` gives the denominator for the fail-open arm but not
for the 503 arm.
- **`record_fallback` output not observed in a running service** —
asserted at the call site only; the Prometheus counter itself was not
scraped.
- Full `backend/test.sh` was not run end to end locally; selection above
plus `make preflight` is the evidence.


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/11799?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 18, 2026
…y graph mutation

BasedHardware#11783 restored the per-account mutation gate, but its probe called
`get_canonical_knowledge_graph` and treated *every* `CanonicalGraphReadUnavailable`
as "canonical state is not established". `read_memory_v3_trusted_account_generation`
swallows every head-get exception into `READ_FAILED`, so a Firestore timeout or a
permission blip on `users/{uid}/memory_state/head` was indistinguishable from an
absent document — and `POST /rebuild` / `DELETE /v1/knowledge-graph` would then
delete the user's legacy `knowledge_nodes`/`knowledge_edges`.

`GET` may fail open on any unavailable canonical read (BasedHardware#11623): the worst case is
a stale view. These routes destroy the store `GET` would have shown, so the
answers are not symmetric.

- `probe_canonical_graph_state` replaces the boolean with a tri-state keyed on the
  typed `V3AccountGenerationFailureReason`. Only `MISSING_STATE_HEAD` is
  `UNESTABLISHED`; `READ_FAILED`, `MALFORMED_STATE_HEAD`, `UNSUPPORTED_SCHEMA`,
  `UID_MISMATCH`, `SOURCE_MISMATCH`, `MALFORMED_ACCOUNT_GENERATION` and a head
  carrying no usable revision fence are `INDETERMINATE`.
- The probe reads the head document directly instead of materializing a canonical
  page. The head is the real "canonical state exists" signal; paging the atlas to
  answer a boolean also made the answer depend on `MEMORY_V3_CURSOR_SECRET` and on
  the atlas composite index.
- The route maps `INDETERMINATE` to 503, not to a legacy mutation.
  `_rebuild_graph_task` re-checks the same decision and stops there too.
- The fail-open to the legacy store now calls the shared `record_fallback`
  (AGENTS.md / docs/agents/fallback-telemetry.md), so the count of accounts still
  served by the pre-canonical path is observable.

Co-Authored-By: Claude Opus 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