Skip to content

fix(memory): preserve explicit user saves after JIT ledger cutover - #12802

Merged
Git-on-my-level merged 2 commits into
mainfrom
codex/jit-ledger-user-write-20260905
Sep 5, 2026
Merged

Git-on-my-level merged 2 commits into
mainfrom
codex/jit-ledger-user-write-20260905

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Sep 5, 2026 •

Copy link
Copy Markdown
Member

Summary

After an admitted account enters ledger mode, POST /v3/memories currently returns 503 because the manual save is classified as a compatibility writer. Route authenticated explicit user facts through the JIT knowledge ledger with a fresh ingress decision and opaque route capability. Keep external and connector writes on required processing, fence mixed or malformed batches before writes, and prevent closed or rejected retries from being reported as current facts.

Product invariants affected

  • INV-MEM-3
  • INV-MEM-4
  • INV-MEM-1

Validation

  • 111 focused backend unit tests passed.
  • Firestore emulator direct-user lifecycle proof passed.
  • Shared backend emulator proof runner passed.
  • Source pyright passed for changed production modules and emulator script.

Failure-Class: new
Line-Count-Exception: backend/utils/memory/canonical_memory_adapter.py | 3705 -> 3742 | direct user ledger retry and lifecycle safety boundary plus emulator proof
Line-Count-Exception: backend/utils/memory/memory_service.py | 3951 -> 4057 | direct user JIT admission and batch preflight boundary

A retry of a closed or rejected content-derived identity returns 503 rather than resurrecting it; explicit reopen remains the lifecycle path. Semantic batch validation occurs before writes, but storage-level batches remain sequential as before. This source change does not enable a cohort or deploy production. It is the manual-write prerequisite for #12546.

Review in cubic

Authenticated manual memory routes now require fresh JIT ingress and the route capability before writing direct ledger facts. Preserve required-processing behavior for external/system writes, preflight manual batches, and reject closed or rejected duplicate retries.

Failure-Class: new
Record the compatibility-writer cutover failure and point the class at the real API emulator proof used by this change.

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.

6 issues found across 11 files

Confidence score: 3/5

  • backend/utils/memory/memory_service.py can drop product metadata such as category and tags on direct /v3/memories ledger writes, causing data loss; preserve the MemoryDB metadata through the ledger write/projection path.
  • backend/utils/memory/memory_service.py reports mixed manual/external batches as a 503 and the router masks the request-shape error as a generic temporary outage, making client correction and diagnosis harder; use an appropriate client-error response and preserve the validation message.
  • backend/tests/unit/test_memory_service_parity.py does not cover the three false gates for _direct_user_ledger_admitted, while backend/scripts/jit_ledger_user_write_emulator_test.py does not verify rejected retries leave the ledger unchanged; add negative-path and no-duplicate assertions before relying on this admission behavior.
  • backend/tests/unit/test_firestore_emulator_harness_wiring.py only checks source strings rather than executing the emulator proof, and .github/failure-classes/FC-compatibility-writer-survives-ledger-cutover.json omits backend/utils/memory/canonical_memory_adapter.py; run the harness and include the adapter in the prevention artifact.
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=".github/failure-classes/FC-compatibility-writer-survives-ledger-cutover.json">

<violation number="1" location=".github/failure-classes/FC-compatibility-writer-survives-ledger-cutover.json:6">
P3: canonical_prevention_artifact omits backend/utils/memory/canonical_memory_adapter.py even though the opaque direct-user route capability the class requires lives there (mint_direct_user_write_authority / is_direct_user_write_authority), and the PR's own line-count exception names that file as the guard boundary. The artifact list instead references knowledge_ledger.py and memory_service.py. For canonical-prevention traceability (what file owns the guard primitive), add canonical_memory_adapter.py so the artifact set covers the file that actually enforces the opaque capability named in canonical_prevention.</violation>
</file>

<file name="backend/utils/memory/memory_service.py">

<violation number="1" location="backend/utils/memory/memory_service.py:3353">
P2: When a manual `/v3/memories` request includes product metadata such as `category` or `tags`, the direct ledger branch drops it before canonical apply. Preserve the `MemoryDB` product metadata in the ledger write/projection, or the cutover changes the returned/UI memory from the submitted metadata.</violation>

<violation number="2" location="backend/utils/memory/memory_service.py:3985">
P3: A mixed manual/external batch is a deterministic request-shape error, but it is raised as 503 and then re-wrapped by the router's blanket `except Exception` into the generic "Service temporarily unavailable", discarding the specific detail. Clients cannot distinguish a permanent mixed-batch rejection from a transient failure and will retry. Consider using a 4xx-class error so the rejection is not retried as unavailable.</violation>
</file>

<file name="backend/tests/unit/test_memory_service_parity.py">

<violation number="1" location="backend/tests/unit/test_memory_service_parity.py:252">
P2: This is the only test of `_direct_user_ledger_admitted` in the suite, yet it only exercises the combined-positive path and asserts True. The three gates that return False — non-route authority, ingress not permitting work, and non-ledger control writer_mode — are never tested, even though the PR's invariant that a retry of a closed or rejected identity returns 503 rests on those branches. Add negative assertions: non-authority object and permits_work=False must yield False (and must not reach ensure_canonical_apply_control_state), and a non-ledger writer_mode must yield False.</violation>
</file>

<file name="backend/scripts/jit_ledger_user_write_emulator_test.py">

<violation number="1" location="backend/scripts/jit_ledger_user_write_emulator_test.py:223">
P2: The rejected-retry assertion only checks that status is 503; unlike the closed-retry check above it, it does not assert the item count is unchanged. If the retry both raised 503 and wrote a second/duplicate ledger row (the same partial-write hazard the closed case guards against), this proof would pass while the behavior the PR claims to prevent — "prevent closed or rejected retries" from resurrecting/duplicating a row — is violated. Capture the item count before the retry and assert it is unchanged, mirroring the closed branch.</violation>
</file>

<file name="backend/tests/unit/test_firestore_emulator_harness_wiring.py">

<violation number="1" location="backend/tests/unit/test_firestore_emulator_harness_wiring.py:26">
P3: This new test only asserts substrings exist in the proof script and a fixed prefix in the package.json command; it never runs the proof or the emulator. Per AGENTS.md, source-string membership is a static tripwire, not behavioral coverage — it passes even if the proof's behavioral assertions are weakened. Label it explicitly as a static wiring check (e.g., in the test name/docstring) rather than implying it verifies the harness is wired to the API and apply adapter.</violation>
</file>

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

Re-trigger cubic

) -> MemoryDB:
"""Persist one explicitly typed memory through the ledger fact seam."""
provenance = self._direct_user_fact_provenance(memory_db, consumer=consumer)
memory_id = save_fact(

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: When a manual /v3/memories request includes product metadata such as category or tags, the direct ledger branch drops it before canonical apply. Preserve the MemoryDB product metadata in the ledger write/projection, or the cutover changes the returned/UI memory from the submitted metadata.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/utils/memory/memory_service.py, line 3353:

<comment>When a manual `/v3/memories` request includes product metadata such as `category` or `tags`, the direct ledger branch drops it before canonical apply. Preserve the `MemoryDB` product metadata in the ledger write/projection, or the cutover changes the returned/UI memory from the submitted metadata.</comment>

<file context>
@@ -3320,6 +3326,74 @@ def _canonical_write(self, uid: str, data: Dict[str, Any], *, source_surface: st
+    ) -> MemoryDB:
+        """Persist one explicitly typed memory through the ledger fact seam."""
+        provenance = self._direct_user_fact_provenance(memory_db, consumer=consumer)
+        memory_id = save_fact(
+            uid,
+            memory_db.content,
</file context>

lambda uid, *, db_client: SimpleNamespace(writer_mode=service_mod.WriterMode.ledger),
)

assert service._direct_user_ledger_admitted("uid-test", authority) is True

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: This is the only test of _direct_user_ledger_admitted in the suite, yet it only exercises the combined-positive path and asserts True. The three gates that return False — non-route authority, ingress not permitting work, and non-ledger control writer_mode — are never tested, even though the PR's invariant that a retry of a closed or rejected identity returns 503 rests on those branches. Add negative assertions: non-authority object and permits_work=False must yield False (and must not reach ensure_canonical_apply_control_state), and a non-ledger writer_mode must yield False.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/tests/unit/test_memory_service_parity.py, line 252:

<comment>This is the only test of `_direct_user_ledger_admitted` in the suite, yet it only exercises the combined-positive path and asserts True. The three gates that return False — non-route authority, ingress not permitting work, and non-ledger control writer_mode — are never tested, even though the PR's invariant that a retry of a closed or rejected identity returns 503 rests on those branches. Add negative assertions: non-authority object and permits_work=False must yield False (and must not reach ensure_canonical_apply_control_state), and a non-ledger writer_mode must yield False.</comment>

<file context>
@@ -207,6 +208,51 @@ def test_canonical_failure_does_not_fall_back_to_historical_writer(monkeypatch,
+        lambda uid, *, db_client: SimpleNamespace(writer_mode=service_mod.WriterMode.ledger),
+    )
+
+    assert service._direct_user_ledger_admitted("uid-test", authority) is True
+    assert calls == [("uid-test", service_mod.JITDecisionStage.INGRESS, True)]
+
</file context>

rejected_id = rejected_items[0].get("memory_id") or rejected_items[0].get("id")
if isinstance(rejected_id, str):
update_canonical_memory_review(UID, rejected_id, False, db_client=db_client)
rejected_retry = client.post(

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 rejected-retry assertion only checks that status is 503; unlike the closed-retry check above it, it does not assert the item count is unchanged. If the retry both raised 503 and wrote a second/duplicate ledger row (the same partial-write hazard the closed case guards against), this proof would pass while the behavior the PR claims to prevent — "prevent closed or rejected retries" from resurrecting/duplicating a row — is violated. Capture the item count before the retry and assert it is unchanged, mirroring the closed branch.

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

<comment>The rejected-retry assertion only checks that status is 503; unlike the closed-retry check above it, it does not assert the item count is unchanged. If the retry both raised 503 and wrote a second/duplicate ledger row (the same partial-write hazard the closed case guards against), this proof would pass while the behavior the PR claims to prevent — "prevent closed or rejected retries" from resurrecting/duplicating a row — is violated. Capture the item count before the retry and assert it is unchanged, mirroring the closed branch.</comment>

<file context>
@@ -0,0 +1,379 @@
+                rejected_id = rejected_items[0].get("memory_id") or rejected_items[0].get("id")
+                if isinstance(rejected_id, str):
+                    update_canonical_memory_review(UID, rejected_id, False, db_client=db_client)
+                    rejected_retry = client.post(
+                        "/v3/memories",
+                        json={"content": REJECTED_CONTENT, "category": "manual"},
</file context>

"id": "FC-compatibility-writer-survives-ledger-cutover",
"violated_contract": "When an authenticated explicit user fact reaches an account with fresh JIT ingress and stable ledger mode, the write route must select the canonical knowledge-ledger writer. Leaving that route on the compatibility writer reports an unavailable service and prevents the user's fact from becoming durable canonical state even though the account has completed cutover.",
"canonical_prevention": "Require an opaque direct-user route capability together with a fresh per-account JIT ingress decision and stable ledger control before selecting the direct ledger writer; preserve required-processing behavior for external, connector, and system writes. Prove the route through a real Firestore emulator with a manual POST that creates and reads back a ledger fact, plus fail-closed kill, unknown, mixed-batch, malformed-batch, forged-authority, and lifecycle cases.",
"canonical_prevention_artifact": [

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: canonical_prevention_artifact omits backend/utils/memory/canonical_memory_adapter.py even though the opaque direct-user route capability the class requires lives there (mint_direct_user_write_authority / is_direct_user_write_authority), and the PR's own line-count exception names that file as the guard boundary. The artifact list instead references knowledge_ledger.py and memory_service.py. For canonical-prevention traceability (what file owns the guard primitive), add canonical_memory_adapter.py so the artifact set covers the file that actually enforces the opaque capability named in canonical_prevention.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At .github/failure-classes/FC-compatibility-writer-survives-ledger-cutover.json, line 6:

<comment>canonical_prevention_artifact omits backend/utils/memory/canonical_memory_adapter.py even though the opaque direct-user route capability the class requires lives there (mint_direct_user_write_authority / is_direct_user_write_authority), and the PR's own line-count exception names that file as the guard boundary. The artifact list instead references knowledge_ledger.py and memory_service.py. For canonical-prevention traceability (what file owns the guard primitive), add canonical_memory_adapter.py so the artifact set covers the file that actually enforces the opaque capability named in canonical_prevention.</comment>

<file context>
@@ -0,0 +1,20 @@
+  "id": "FC-compatibility-writer-survives-ledger-cutover",
+  "violated_contract": "When an authenticated explicit user fact reaches an account with fresh JIT ingress and stable ledger mode, the write route must select the canonical knowledge-ledger writer. Leaving that route on the compatibility writer reports an unavailable service and prevents the user's fact from becoming durable canonical state even though the account has completed cutover.",
+  "canonical_prevention": "Require an opaque direct-user route capability together with a fresh per-account JIT ingress decision and stable ledger control before selecting the direct ledger writer; preserve required-processing behavior for external, connector, and system writes. Prove the route through a real Firestore emulator with a manual POST that creates and reads back a ledger fact, plus fail-closed kill, unknown, mixed-batch, malformed-batch, forged-authority, and lifecycle cases.",
+  "canonical_prevention_artifact": [
+    "backend/scripts/jit_ledger_user_write_emulator_test.py",
+    "backend/utils/memory/memory_service.py",
</file context>

assert direct_user_authority is not None
if not all(memory.manually_added for memory in memory_dbs):
raise HTTPException(
status_code=503,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: A mixed manual/external batch is a deterministic request-shape error, but it is raised as 503 and then re-wrapped by the router's blanket except Exception into the generic "Service temporarily unavailable", discarding the specific detail. Clients cannot distinguish a permanent mixed-batch rejection from a transient failure and will retry. Consider using a 4xx-class error so the rejection is not retried as unavailable.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/utils/memory/memory_service.py, line 3985:

<comment>A mixed manual/external batch is a deterministic request-shape error, but it is raised as 503 and then re-wrapped by the router's blanket `except Exception` into the generic "Service temporarily unavailable", discarding the specific detail. Clients cannot distinguish a permanent mixed-batch rejection from a transient failure and will retry. Consider using a 4xx-class error so the rejection is not retried as unavailable.</comment>

<file context>
@@ -3889,9 +3973,31 @@ def create_external_memory_batch(
+                assert direct_user_authority is not None
+                if not all(memory.manually_added for memory in memory_dbs):
+                    raise HTTPException(
+                        status_code=503,
+                        detail="Mixed explicit-user and external memory batch is not admitted in ledger mode",
+                    )
</file context>

_JIT_LEDGER_USER_WRITE_SCRIPT = _REPO_ROOT / "backend" / "scripts" / "jit_ledger_user_write_emulator_test.py"


def test_jit_ledger_user_write_emulator_harness_is_wired_to_api_and_apply():

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: This new test only asserts substrings exist in the proof script and a fixed prefix in the package.json command; it never runs the proof or the emulator. Per AGENTS.md, source-string membership is a static tripwire, not behavioral coverage — it passes even if the proof's behavioral assertions are weakened. Label it explicitly as a static wiring check (e.g., in the test name/docstring) rather than implying it verifies the harness is wired to the API and apply adapter.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/tests/unit/test_firestore_emulator_harness_wiring.py, line 26:

<comment>This new test only asserts substrings exist in the proof script and a fixed prefix in the package.json command; it never runs the proof or the emulator. Per AGENTS.md, source-string membership is a static tripwire, not behavioral coverage — it passes even if the proof's behavioral assertions are weakened. Label it explicitly as a static wiring check (e.g., in the test name/docstring) rather than implying it verifies the harness is wired to the API and apply adapter.</comment>

<file context>
@@ -20,6 +20,32 @@
+_JIT_LEDGER_USER_WRITE_SCRIPT = _REPO_ROOT / "backend" / "scripts" / "jit_ledger_user_write_emulator_test.py"
+
+
+def test_jit_ledger_user_write_emulator_harness_is_wired_to_api_and_apply():
+    assert _JIT_LEDGER_USER_WRITE_SCRIPT.exists()
+    script = _JIT_LEDGER_USER_WRITE_SCRIPT.read_text()
</file context>

@Git-on-my-level
Git-on-my-level merged commit 47bc8d5 into main Sep 5, 2026
44 checks passed
@Git-on-my-level
Git-on-my-level deleted the codex/jit-ledger-user-write-20260905 branch September 5, 2026 20:21
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