Repository navigation
fix(backend): only a genuinely absent state head may unlock the legacy knowledge-graph mutation - #11799
Merged
Conversation
…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]>
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.
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.pyis 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_artifactpaths (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_statecalledget_canonical_knowledge_graphand treated everyCanonicalGraphReadUnavailableas "canonical state is not established".read_memory_v3_trusted_account_generation(backend/utils/memory/v3/account_generation_source.py) swallows every head-get exception intoREAD_FAILED, so a Firestore timeout or permission blip onusers/{uid}/memory_state/headwas indistinguishable from an absent document — andPOST /rebuild/DELETE /v1/knowledge-graphthen deleted the user's legacyknowledge_nodes/knowledge_edges.GETmay fail open on any unavailable canonical read (#11623): worst case is a stale view. These routes destroy the storeGETwould have shown. Copying the catch-all onto the mutation side was the miss.New
canonical_graph.probe_canonical_graph_statereturns a tri-state keyed on the typedV3AccountGenerationFailureReasonenum, not on strings:ESTABLISHEDMISSING_STATE_HEADUNESTABLISHEDREAD_FAILED,MALFORMED_STATE_HEAD,UNSUPPORTED_SCHEMA,UID_MISMATCH,SOURCE_MISMATCH,MALFORMED_ACCOUNT_GENERATIONINDETERMINATEINDETERMINATE_rebuild_graph_taskre-runs the same decision and stops on anything other thanALLOWED, 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 onMEMORY_V3_CURSOR_SECRETand on the atlas composite index — a missing cursor secret came back asmissing_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_revisionand the probe share_revision_from_trustedso the two cannot drift on what counts as a well-formed head.test_the_probe_needs_no_cursor_secret_and_no_atlas_querypins 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_conflictsstubbed a page with non-emptynodes, so a production body wrongly written asreturn 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_assertionsis 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_HEADreasons; 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.tests/unit/test_canonical_graph_state_probe.pycovers the probe directly, includingtest_a_thrown_head_read_is_classified_as_read_failed_not_absent, which drives a client that raisesTimeoutErrorso 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:UNESTABLISHED(the pre-fix semantics)test_an_unanswered_canonical_probe_must_not_delete_the_legacy_graph[read_failed]assert ['uid-arbitra...rary-account'] == []test_rebuild_task_is_a_noop_when_the_canonical_probe_is_unansweredAssertionError: legacy rebuild ran while canonical state was unverifiedtest_every_other_failure_reason_is_indeterminate[read_failed](+5 params)assert <CanonicalGraphState.UNESTABLISHED> is <CanonicalGraphState.INDETERMINATE>test_a_thrown_head_read_is_classified_as_read_failed_not_absenttest_an_established_head_with_zero_assertions_still_conflictsAssertionError: an established head must decide the gate on its ownrecord_fallbacktest_the_legacy_fail_open_reports_shared_fallback_telemetryassert 0 == 1record_fallbackfires on every call, conflicts includedtest_a_conflicting_account_reports_no_fallbackassert [{'component'...}] == []ESTABLISHEDtest_a_head_without_a_usable_revision_fence_is_indeterminateassert <ESTABLISHED> is <INDETERMINATE>test_the_probe_needs_no_cursor_secret_and_no_atlas_queryAssertionError: the state probe paged the canonical atlasNegative control: under mutation A,
test_an_established_head_with_zero_assertions_still_conflictsandtest_the_legacy_fail_open_reports_shared_fallback_telemetryboth 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) perAGENTS.mdanddocs/agents/fallback-telemetry.md. No new counter:knowledge_graphwas added toALLOWED_COMPONENTSandunmigrated_principaltoALLOWED_REASONSinutils/observability/fallback.py, so it lands on the existingomi_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" — useget_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 toget_firestore_client().5. Known gap, documented not fixed: rebuild deletes before it rebuilds
POST /rebuildcallskg_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_taskre-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-5724a10084contract, 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
UNVERIFIEDarm 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/mainat494edbb7f8(contains #11783). Python 3.11.15.backend/test.shruns 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.pywhich itself logs7 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
CANONICAL_GRAPH_STATE_UNVERIFIEDstring deserves a look from someone with the app in front of them.INDETERMINATEwill actually fire in production. If head reads flap, users will see 503s where they previously (silently, destructively) succeeded. The newrecord_fallbackgives the denominator for the fail-open arm but not for the 503 arm.record_fallbackoutput not observed in a running service — asserted at the call site only; the Prometheus counter itself was not scraped.backend/test.shwas not run end to end locally; selection above plusmake preflightis the evidence.