Skip to content

fix(backend): only a genuinely absent state head may unlock the legacy knowledge-graph mutation - #11799

Merged
Git-on-my-level merged 2 commits into
mainfrom
fix/kg-mutation-gate-hardening
Aug 18, 2026
Merged

Git-on-my-level merged 2 commits into
mainfrom
fix/kg-mutation-gate-hardening

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

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 — fix(backend): restore the per-account knowledge-graph mutation gate #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.

Review in cubic

Git-on-my-level and others added 2 commits August 18, 2026 02:07
…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. #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]>
…y graph mutation

#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 (#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]>
@Git-on-my-level
Git-on-my-level merged commit 922b30d into main Aug 18, 2026
44 checks passed
@Git-on-my-level
Git-on-my-level deleted the fix/kg-mutation-gate-hardening branch August 18, 2026 06:41
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