Repository navigation
Add fenced canonical graph enrichment - #11095
Conversation
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a341ffb0ff
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| and not extra_item_updates | ||
| and promotion_metadata is None |
There was a problem hiding this comment.
Preserve promotion metadata during graph enrichment
When a graph_enrichment operation supplies a promotion_audit that differs from existing_item.promotion beyond the new graph plan/receipt fields, this validation still passes and _apply_update_memory_item replaces the entire promotion dict. That lets a graph-only enrichment silently flip fields such as user_review, required, processing_status, or route, which affect projection/default-read eligibility even though this path is meant to attach only a fenced graph assertion without changing Long-term semantics. Require the submitted promotion audit to equal the existing promotion plus the enrichment fields before committing.
Useful? React with 👍 / 👎.
| if item.graph_ready: | ||
| try: | ||
| current_plan = _coerce_plan((item.promotion or {}).get("graph_plan", {})) | ||
| except GraphEnrichmentError: |
There was a problem hiding this comment.
Accept stored promotion graph plans when skipping enrichment
For an item that is already graph_ready, this branch reads the stored promotion graph_plan dict, but those plans are stored as PromotionGraphPlan payloads with schema_version='canonical_memory_graph_plan.v1' (including the ones written by this helper below). _coerce_plan() validates dicts as GraphEnrichmentPlan, whose literal schema is canonical_memory_graph_enrichment_plan.v1, so normal already-enriched items are reported as graph_assertion_invalid instead of returning already_enriched; a future enrichment worker would keep treating valid graph-backed memories as failures rather than idempotent skips.
Useful? React with 👍 / 👎.
| if not item.subject_entity_id or checked_plan.subject_entity_id != item.subject_entity_id: | ||
| return _blocked("subject_overwrite", "graph enrichment cannot overwrite or invent the existing subject") |
There was a problem hiding this comment.
Block semantic rewrites before returning a ready plan
When the proposed plan keeps the same subject but changes the existing Long-term predicate or arguments, prepare_graph_enrichment() still returns ready and hands callers an operation/payload it says has been validated; the apply transaction later rejects it as an invalid semantic change. A bounded enrichment worker using this validation seam would enqueue doomed operations for any misplanned historical row instead of classifying the row as blocked before writing an operation, so this check should also require the plan predicate and arguments to match the item before building the receipt.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
4 issues found and verified against the latest diff
Confidence score: 3/5
- In
backend/models/memory_apply.py, graph enrichment can reorder multi-evidence long-term items while keeping the old order-sensitivecontent_hash, which can make the content/evidence assertion fence inconsistent and trigger incorrect apply behavior — compare evidence lists in order and recompute/validate the hash after enrichment ordering changes. - In
backend/utils/memory/graph_enrichment.py, retry flow for already-enriched memories can be blocked because_coerce_planrejects the storedPromotionGraphPlanshape on this branch, causing recoverable operations to fail — accept the persistedPromotionGraphPlanschema in this path so retries can proceed. - Validation coverage is incomplete across
backend/models/memory_apply.pyandbackend/utils/memory/graph_enrichment.py: checks focus onpromotion_auditgraph fields (and only subject for not-yet-ready items) without verifying other promotion fields and full plan equivalence, so mismatched state can be markedreadyand patched incorrectly — add full-field parity checks (user_review/required/processing_status/route plus predicted-plan details) before returningreadyor building patch payloads.
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/models/memory_apply.py">
<violation number="1" location="backend/models/memory_apply.py:766">
P2: The graph_enrichment validation only checks the graph_plan/receipt fields inside promotion_audit but never verifies the remaining promotion fields (user_review, required, processing_status, route, etc.) match existing_item.promotion. Since the entire promotion dict is later replaced with promotion_audit, this allows a graph-only enrichment to silently flip non-graph promotion fields that affect projection/default-read eligibility. Consider requiring promotion_audit to equal existing promotion plus only the new graph fields before committing.</violation>
<violation number="2" location="backend/models/memory_apply.py:809">
P2: Graph enrichment can reorder a multi-evidence Long-term item while retaining its old, order-sensitive `content_hash`, leaving the assertion's content/evidence fence inconsistent. Comparing the evidence lists in order (or rejecting when the canonical hash does not match) would keep the graph-only mutation from changing this bound state.</violation>
</file>
<file name="backend/utils/memory/graph_enrichment.py">
<violation number="1" location="backend/utils/memory/graph_enrichment.py:312">
P2: Retries for an already enriched memory are incorrectly blocked because the stored promotion plan cannot be parsed by `_coerce_plan` in this branch; accepting the stored `PromotionGraphPlan` schema here would preserve idempotent `already_enriched` behavior.</violation>
<violation number="2" location="backend/utils/memory/graph_enrichment.py:320">
P2: For items that aren't yet graph_ready, this only checks that the plan's subject matches the item's subject before returning `ready` and constructing the operation/patch payload — it never compares `checked_plan.predicate`/`arguments` against the item's current `predicate`/`arguments`. The apply transaction later rejects any predicate/argument mismatch as an invalid semantic change, so a caller relying on this validation seam would enqueue a doomed operation instead of getting a `blocked` result up front. Consider requiring `checked_plan.predicate == item.predicate` and `checked_plan.arguments == item.arguments` here before returning `ready`.</violation>
</file>
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
| and sorted(record.evidence_id for record in evidence) | ||
| == sorted(record.evidence_id for record in existing_item.evidence) |
There was a problem hiding this comment.
P2: Graph enrichment can reorder a multi-evidence Long-term item while retaining its old, order-sensitive content_hash, leaving the assertion's content/evidence fence inconsistent. Comparing the evidence lists in order (or rejecting when the canonical hash does not match) would keep the graph-only mutation from changing this bound state.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/models/memory_apply.py, line 809:
<comment>Graph enrichment can reorder a multi-evidence Long-term item while retaining its old, order-sensitive `content_hash`, leaving the assertion's content/evidence fence inconsistent. Comparing the evidence lists in order (or rejecting when the canonical hash does not match) would keep the graph-only mutation from changing this bound state.</comment>
<file context>
@@ -678,6 +761,60 @@ def apply_long_term_patch_transaction(
+ and patch.predicate == graph_plan.predicate == existing_item.predicate
+ and bool(_GRAPH_PREDICATE_RE.fullmatch(graph_plan.predicate))
+ and patch.arguments == graph_plan.arguments == existing_item.arguments
+ and sorted(record.evidence_id for record in evidence)
+ == sorted(record.evidence_id for record in existing_item.evidence)
+ ):
</file context>
| and sorted(record.evidence_id for record in evidence) | |
| == sorted(record.evidence_id for record in existing_item.evidence) | |
| and [record.evidence_id for record in evidence] | |
| == [record.evidence_id for record in existing_item.evidence] |
| return _blocked(exc.code, exc.message) | ||
| if item.graph_ready: | ||
| try: | ||
| current_plan = _coerce_plan((item.promotion or {}).get("graph_plan", {})) |
There was a problem hiding this comment.
P2: Retries for an already enriched memory are incorrectly blocked because the stored promotion plan cannot be parsed by _coerce_plan in this branch; accepting the stored PromotionGraphPlan schema here would preserve idempotent already_enriched behavior.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/utils/memory/graph_enrichment.py, line 313:
<comment>Retries for an already enriched memory are incorrectly blocked because the stored promotion plan cannot be parsed by `_coerce_plan` in this branch; accepting the stored `PromotionGraphPlan` schema here would preserve idempotent `already_enriched` behavior.</comment>
<file context>
@@ -0,0 +1,405 @@
+ return _blocked(exc.code, exc.message)
+ if item.graph_ready:
+ try:
+ current_plan = _coerce_plan((item.promotion or {}).get("graph_plan", {}))
+ except GraphEnrichmentError:
+ return _blocked("graph_assertion_invalid", "graph_ready item has no valid current graph plan")
</file context>
| ) | ||
| graph_enrichment = operation.operation_type == MemoryOperationType.graph_enrichment | ||
| if graph_enrichment: | ||
| raw_graph_plan = promotion_audit.get("graph_plan") if isinstance(promotion_audit, dict) else None |
There was a problem hiding this comment.
P2: The graph_enrichment validation only checks the graph_plan/receipt fields inside promotion_audit but never verifies the remaining promotion fields (user_review, required, processing_status, route, etc.) match existing_item.promotion. Since the entire promotion dict is later replaced with promotion_audit, this allows a graph-only enrichment to silently flip non-graph promotion fields that affect projection/default-read eligibility. Consider requiring promotion_audit to equal existing promotion plus only the new graph fields before committing.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/models/memory_apply.py, line 766:
<comment>The graph_enrichment validation only checks the graph_plan/receipt fields inside promotion_audit but never verifies the remaining promotion fields (user_review, required, processing_status, route, etc.) match existing_item.promotion. Since the entire promotion dict is later replaced with promotion_audit, this allows a graph-only enrichment to silently flip non-graph promotion fields that affect projection/default-read eligibility. Consider requiring promotion_audit to equal existing promotion plus only the new graph fields before committing.</comment>
<file context>
@@ -678,6 +761,60 @@ def apply_long_term_patch_transaction(
)
+ graph_enrichment = operation.operation_type == MemoryOperationType.graph_enrichment
+ if graph_enrichment:
+ raw_graph_plan = promotion_audit.get("graph_plan") if isinstance(promotion_audit, dict) else None
+ raw_receipt = promotion_audit.get("graph_enrichment_receipt") if isinstance(promotion_audit, dict) else None
+ try:
</file context>
| ): | ||
| return _blocked("graph_assertion_invalid", "graph_ready item lacks an exact current graph assertion") | ||
| return GraphEnrichmentResult(status=GraphEnrichmentStatus.already_enriched, plan=current_plan) | ||
| if not item.subject_entity_id or checked_plan.subject_entity_id != item.subject_entity_id: |
There was a problem hiding this comment.
P2: For items that aren't yet graph_ready, this only checks that the plan's subject matches the item's subject before returning ready and constructing the operation/patch payload — it never compares checked_plan.predicate/arguments against the item's current predicate/arguments. The apply transaction later rejects any predicate/argument mismatch as an invalid semantic change, so a caller relying on this validation seam would enqueue a doomed operation instead of getting a blocked result up front. Consider requiring checked_plan.predicate == item.predicate and checked_plan.arguments == item.arguments here before returning ready.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/utils/memory/graph_enrichment.py, line 321:
<comment>For items that aren't yet graph_ready, this only checks that the plan's subject matches the item's subject before returning `ready` and constructing the operation/patch payload — it never compares `checked_plan.predicate`/`arguments` against the item's current `predicate`/`arguments`. The apply transaction later rejects any predicate/argument mismatch as an invalid semantic change, so a caller relying on this validation seam would enqueue a doomed operation instead of getting a `blocked` result up front. Consider requiring `checked_plan.predicate == item.predicate` and `checked_plan.arguments == item.arguments` here before returning `ready`.</comment>
<file context>
@@ -0,0 +1,405 @@
+ ):
+ return _blocked("graph_assertion_invalid", "graph_ready item lacks an exact current graph assertion")
+ return GraphEnrichmentResult(status=GraphEnrichmentStatus.already_enriched, plan=current_plan)
+ if not item.subject_entity_id or checked_plan.subject_entity_id != item.subject_entity_id:
+ return _blocked("subject_overwrite", "graph enrichment cannot overwrite or invent the existing subject")
+ receipt = GraphEnrichmentReceipt(
</file context>
… dedup re-ported 22 upstream commits. New pure-logic module utils/memory/graph_enrichment.py (fenced canonical graph enrichment BasedHardware#11095) — no storage, no port needed. Two conflicts resolved keeping product logic verbatim, storage delta preserved: - database/user_usage.py: upstream's single-read all-time dedup (BasedHardware#11062) — _read_all_time_usage building total + yearly history in one pass — re-expressed on the store port (_store().query), not raw db.collection().stream(). - utils/memory/canonical_graph.py (auto-merged): upstream's catalog_nodes boundary (BasedHardware#11089) kept; storage stays document_store.query_collection (our delta). 0 raw firestore. Tests re-expressed on the neutral seam (no db_client, ADR-0028), no test removed: - test_knowledge_graph_canonical_pagination: adopts upstream's linked/unlinked catalog_nodes assertions via _fake_db_for (dropped the raw db_client _FakeDB setup). - test_user_usage: the all-time dedup test moved from the mock_db raw-Firestore fixture to the FakeDocumentStore store seam; kept the single-read invariant (record_firestore_read once, count 2), dropped the raw .stream() assertion. Audit ADR-0030: guard 0 · storage port byte-identical (empty diff on database/store/ + document_store.py) · sweep file-isolated 64/64 green · contract dual-backend 66 passed (Firestore emulator + Mongo real).
What changed
Adds a graph-enrichment operation that attaches a version-, evidence-, and generation-fenced canonical graph assertion to eligible Long-term memories through the existing atomic apply ledger.
Why
Historical canonical rows can predate the assertion contract. This creates the safe write boundary needed to enrich only already-established memory semantics without using synthetic graph nodes or direct graph writes.
User impact
Enables a future bounded enrichment worker to restore connected, evidence-backed canonical graph records for historical memories.
Validation
backend/.venv/bin/pytest -q backend/tests/unit/test_atomic_apply.py backend/tests/unit/test_knowledge_graph_canonical_pagination.pypre-commit run ruff --files backend/models/memory_apply.py backend/models/memory_operations.py backend/utils/memory/graph_enrichment.py backend/tests/unit/test_atomic_apply.pyProduct invariants affected