Repository navigation
fix(backend): restore the per-account knowledge-graph mutation gate - #11783
Merged
Merged
Conversation
POST /v1/knowledge-graph/rebuild and DELETE /v1/knowledge-graph have returned 409 to every account since 5724a10, and the mobile graph page renders the body verbatim: Exception: Failed to rebuild knowledge graph: {"detail":"Canonical knowledge graph state is derived from canonical memories and cannot be deleted or rebuilt directly."} 165c041 introduced that 409 behind a real per-account predicate: canonical memory system pinned, or stored memory-graph assertions present. 5724a10 replaced the predicate body with an unconditional `return True`, turning a correct per-account gate into a global one. Canonical graph state is fenced on users/{uid}/memory_state/head, written only by the canonical apply transaction, and the convergence deliberately shipped no backfill — so the accounts being refused have no derived state to protect. The predicate is now a real probe again: canonical graph state established (the canonical read succeeds), or stored assertions present. pin_memory_system no longer exists post-convergence and is banned from public memory surfaces, so establishment is probed through the canonical graph service itself rather than re-deriving the head fence here. Repairing the one predicate fixes rebuild and delete together instead of patching each route. Accounts with no canonical state get the legacy rebuild/delete back; accounts with canonical state keep the 409 and its message unchanged. The rebuild task sources memories through MemoryService, whose read already unions canonical and historical memories. Co-Authored-By: Claude Opus 5 <[email protected]>
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
force-pushed
the
fix/knowledge-graph-mutation-legacy-path
branch
from
August 18, 2026 02:25
ecf6463 to
69413f6
Compare
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
…store proxy `backend/AGENTS.md` (Service Map): `database._client.db` "remains a legacy lazy compatibility proxy only; do not use it in new code" — call `get_firestore_client()` at call time instead. BasedHardware#11783 reintroduced the proxy import while restoring the mutation gate. Same client, same laziness; this only removes the banned indirection. Co-Authored-By: Claude Opus 5 <[email protected]>
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]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
Every mobile user who opens the knowledge-graph page and taps rebuild gets the raw backend error rendered to their screen:
165c041a93(2026-07-28) introduced the 409 onPOST /v1/knowledge-graph/rebuildandDELETE /v1/knowledge-graphbehind a real per-account predicate:5724a10084(2026-08-11, "converge universal memory and task authority") replaced that whole body with an unconditionalreturn 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_systemno longer exists after the convergence and is banned from public memory surfaces bytest_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/rebuildperforms the legacy delete + background rebuild again for accounts with no canonical state; the background task sources memories throughMemoryService.read, whose read already unions canonical and historical memories.DELETE /v1/knowledge-graphperforms the legacy delete again for those accounts.Style follows #11623: fall back to the legacy store when canonical is genuinely unavailable for that account;
/v1/knowledge-graph/canonicalstill reports 503 because that caller asked for canonical specifically.Tests
backend/tests/unit/test_knowledge_graph_canonical_mutation_routes.pypreviously asserted the broken behaviour (409 for"uid-arbitrary-account", and_is_assertion_backed_graph_account(...) is Truefor 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 withTestClient:memory_state/head, no assertions → rebuild returns 200rebuildingand schedules the rebuild task, delete returns 200deleted, both after the legacy delete ran.CANONICAL_GRAPH_MUTATION_CONFLICTand no legacy mutation.Verification
All commands run from
backend/on this branch,.venvinterpreter (Python 3.11).test_universal_memory_route_surfaces.pyandtest_universal_memory_task_authority.pyare included deliberately: they are the ratchets that forbidpin_memory_systemand 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_dbstubbed; the Firestore reads themselves (has_stored_memory_graph_assertions,kg_db.delete_knowledge_graph,MemoryService.read) are pre-existing calls restored verbatim from165c041a93/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:
canonical_prevention_artifact, alongside fix(backend): serve the legacy graph when the canonical read is unavailable #11623's read-side suite.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)
app/lib/backend/http/api/memories.dartreturns[]for any non-200, andbackend/routers/memories.pyhas a circular 503 fallback. Separate bug, separate PR.memory_graph_page.dartandonboarding/wrapper.dart, macOSMemoryGraphPage.swift, Windows. Follow-up; this PR keeps the endpoint working for them.backend-listenrunsMEMORY_ENABLED=offwhile Cloud RunbackendrunsMEMORY_ENABLED=on. Not touched here.Per AGENTS.md: "Do not broaden a safe bug-fix PR into an unreviewable migration."