Skip to content

fix(memory): decide evidence identity by source, not capture metadata - #17301

Merged
Git-on-my-level merged 1 commit into
mainfrom
fix/dev-memory-evidence-identity
Sep 23, 2026
Merged

Git-on-my-level merged 1 commit into
mainfrom
fix/dev-memory-evidence-identity

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

Fixes #17296.

Summary

POST /v1/dev/user/memories returns 500 on 20–28% of production calls with MemoryFirestoreApplyError: proposed evidence conflicts with existing evidence identity.

Root cause. Developer API evidence ids are derived from the memory text, so re-sending the same text reuses one evidence document. #13953 (2026-09-15) added seven capture-metadata fields to MemoryEvidence (source_signal, extractor_id, extractor_version, capture_confidence, independence_group, captured_at, attribution). The apply-time identity check compared the whole model minus an exclude list, so those new fields joined the identity automatically. Evidence written before that release stores them as absent; every replay of such a source proposes them populated, and the check reported a conflict for a source that had not changed. The legacy backfill writes evidence in the same stripped shape.

Fix.

  • Every MemoryEvidence field is classified as identity, metadata, or state (models/memory_evidence.py). The check compares only identity fields. The fields compared before Enable memory currency, evidence weighting, and history across Beta #13953 stay identity, so no existing conflict rule is loosened; only the seven capture-metadata fields leave the comparison, plus patch_id/commit_id (never set by any writer) as state.
  • A unit test fails when a new field is unclassified, so the next additive field cannot silently join identity.
  • A genuine identity conflict raises EvidenceIdentityConflict; MemoryService.create_external_memory and create_external_memory_batch return it as 409 rather than 500. This covers the developer API, MCP, and /v3/memories creates.
  • Stored evidence is not rewritten. Absent capture metadata already means "unknown" (see the MemoryEvidence comment), so a backfill would invent provenance rather than recover it.

No request or response shape changes.

Verification

  • Unit (backend/test.sh with test_memory_apply_store.py, test_memory_service_parity.py): 64 passed. The two new replay tests fail against the previous comparison and pass with this change.
  • Firestore emulator, real MemoryService → canonical adapter → apply path, developer-API MemoryDB.from_memory payloads, evidence rewritten into the pre-Enable memory currency, evidence weighting, and history across Beta #13953 shape:
Scenario origin/main 268e04e this branch
A: dev-API create, strip evidence metadata, identical re-POST MemoryFirestoreApplyError: proposed evidence conflicts with existing evidence identity ok, same memory id
B: MCP create, strip metadata, dev-API POST of the same text same error ok, same memory id

This reproduces the production exception on real Firestore transaction semantics and shows the replay is not short-circuited by operation idempotency.

Follow-up (separate PR, announced breaking change): client Idempotency-Key / external_id and server-assigned memory ids for the developer API, so identity stops depending on text at all.

Product invariants affected

  • INV-MEM-1 — no tier change; the apply path still writes the same tiers.
  • INV-MEM-3 — creates still go through MemoryService and the canonical writer; a conflict now fails closed as 409 instead of 500, with no fallback writer.
  • INV-MEM-4 — intake routing, promotion, and receipts are unchanged; only the evidence identity comparison inside the apply transaction changes.

Failure-Class: new

Line-Count-Exception: backend/utils/memory/memory_service.py | 4324 -> 4339 | 409 mapping for evidence identity conflicts at the three external-create write calls

🤖 Generated with Claude Code

Review in cubic

Evidence written before #13953 stores its capture metadata as null, and
the apply-time identity check compared that metadata. Every replay of a
source recorded before that release failed with 'proposed evidence
conflicts with existing evidence identity' and surfaced as a 500 on the
developer memory API (#17296).

Classify every MemoryEvidence field as identity, metadata, or state, and
compare only identity. A test fails on an unclassified field. A genuine
identity conflict now raises a typed error that memory creates return
as 409.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Git-on-my-level
Git-on-my-level merged commit 79e340a into main Sep 23, 2026
67 checks passed
@Git-on-my-level
Git-on-my-level deleted the fix/dev-memory-evidence-identity branch September 23, 2026 11:01
Git-on-my-level added a commit that referenced this pull request Sep 23, 2026
…API breaks (#17321)

Follow-up to #17301 for #17296. No behavior change: this publishes the
contract #17301 made work, and adds a CI gate so the next Developer API
change cannot break consumers silently.

## Summary

**Dedupe contract, now documented** (`POST /v1/dev/user/memories`,
`/batch`, route docstrings → OpenAPI, and
`docs/doc/developer/api/memories.mdx`):

| Request | Result |
|---|---|
| Text the user does not have yet | A new memory |
| Text the user already has | `200` with the existing memory; nothing
new is stored |
| Same text, different `category`/`visibility`/`tags` | `200` with the
existing memory as stored; new fields are not applied (use `PATCH`) |
| Same text after a delete | A new memory with a new id |

Matching trims surrounding whitespace and is case-sensitive. In a batch,
duplicates return the existing memory at their position; `created_count`
is the number of memories returned.

Every row of that table was measured on the Firestore emulator through
the real developer routes, `MemoryService`, and canonical apply on
`main` (auth and categorizer patched only).

**Why dedupe rather than server-assigned ids:** the only client that
produced the #17296 500s (one `Python-urllib/3.12` integration, 254 500s
+ 1,022 429s in 12 h, zero successes) re-sends the same text. Under
dedupe its retries now return the existing memory; under random ids each
accepted retry would have become a duplicate.

**Future changes stay graceful:** `openapi-contract.yml` now runs the
existing directional compatibility checker against the public Developer
API contract (`docs/api-reference/openapi.json`), not just the
app-client contract. Removing an endpoint, dropping a required response
field, or adding a required request field fails the PR (additive
changes, including dropping an optional response field, still pass). The
checker gains a `--label` so its messages name the contract.

## Verification

- `test_dev_api_memory_dedupe.py` (new): same text → one memory id and
one evidence id, including padded text and changed tags/visibility;
different case → a different memory; batch duplicates share one id.
- `test_app_client_openapi_compatibility.py`: wiring test now requires
the Developer API step. `test_developer_memory_adapter.py`,
`test_dev_api_canonical_grant_ordering.py` pass.
- `check_app_client_openapi_compatibility.py --head-spec
docs/api-reference/openapi.json --label 'Developer API' --base-ref
origin/main`: passes. The same check against a copy with
`/v1/dev/user/memories/batch` removed fails with `released endpoint was
removed`; a copy that makes `tags` a required request field fails on
both create routes.
- `openapi.json` and `app-client-openapi.json` regenerated (docstring
text only); Dart/TS/Swift generators `--check` clean.

Line-Count-Exception: backend/routers/developer.py | 2567 -> 2576 |
route docstrings state the published dedupe contract

🤖 Generated with [Claude Code](https://claude.com/claude-code)


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/17321?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. -->
Git-on-my-level added a commit that referenced this pull request Sep 23, 2026
…entity (#17326)

Follow-up to #17301 / #17321 for #17296.

## Summary

After #17301 reached prod (`backend-79e340a-35852459809-1`), the
evidence conflict in front of the developer memory write was gone, and
the same client's resends started failing one step later: 15 ×
`RuntimeError: canonical write failed: ApplyStatus.invalid_patch (add
patch new_memory_id already exists)` between 12:03 and 12:05Z.

**Cause.** External memory ids are derived from the submitted text, but
a row keeps its id when it is edited (`PATCH`), superseded by
consolidation, or rejected by the user. Re-sending the original text
proposes an add for that id. `_existing_identical_add_row` correctly
refuses to treat an edited/inactive/rejected row as the same memory, so
the add fails on every retry.

**Fix.** `write_canonical_external_memory` probes the text-derived id
before writing:
- absent → write it;
- an active, unrejected row holding the same text → reuse it (the
published dedupe contract);
- otherwise → a deterministic reissued id
(`canonical-external-memory-occupied-reissue`, bounded at 25 probes),
exactly as a re-add after delete already works. A retry of the resend
lands on the same new row.

Only ids derived from the exact submitted text may move. A
caller-supplied id reused for different text still fails
(`test_reusing_a_row_id_for_different_content_still_fails` unchanged and
passing).

This matches the published contract from #17321: text the user does not
have (any more) becomes a new memory.

## Verification

- Firestore emulator, real developer route → `MemoryService` → canonical
apply, on `main` before this change: edited, superseded, and rejected
resends each reproduce the exact prod error. With this change each
creates one new memory and a retry returns the same id; the edited
original keeps its edited text; a plain duplicate still returns the
existing memory.
- Unit: `test_external_memory_resend_identity.py` (new: derived id kept,
live identical row reused, edited/superseded/rejected rows reissue to
one stable id, retry after commit resolves to the reissued row, occupied
candidates skipped); `test_ws_j_delete_privacy.py` gains the
edited-resend regression through `write_canonical_external_memory`. All
34 unit files importing `canonical_memory_adapter` pass.

## Product invariants affected

- INV-MEM-1 — no tier change.
- INV-MEM-3 — writes still go through `MemoryService` and the canonical
writer, with no fallback writer.
- INV-MEM-4 — intake routing, promotion, and receipts are unchanged;
only which row id an external create targets changes when its
text-derived id is occupied by a row that no longer holds that text.

Failure-Class: FC-content-derived-identity-retired-by-deletion

Line-Count-Exception: backend/utils/memory/canonical_memory_adapter.py |
4121 -> 4166 | occupied text-derived id reissue beside the existing
tombstone reissue it mirrors

🤖 Generated with [Claude Code](https://claude.com/claude-code)


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/17326?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 Sep 23, 2026
…entity

External memory ids are derived from the submitted text, but a row keeps
its id when it is edited, superseded, or rejected. Re-sending the
original text then collided with that row, the duplicate-add resolution
correctly refused to treat it as the same memory, and every retry failed
with 'canonical write failed: invalid_patch (add patch new_memory_id
already exists)'. After BasedHardware#17301 removed the evidence conflict in front of
it, this is what the BasedHardware#17296 client hit in prod.

The user no longer has that text, so the resend is a new memory: the
write now probes the derived id and moves to a deterministic reissued id,
as a re-add after delete does. Retrying lands on the same new row. Only
ids derived from the exact text move; a caller-supplied id reused for
different text still fails.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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.

Developer API POST /v1/dev/user/memories returns 500 on ~20–28% of calls (evidence identity conflict)

1 participant