Skip to content

feat(backend): add durable conversation mutation receipts - #12472

Merged
undivisible merged 4 commits into
BasedHardware:mainfrom
aryanorastar:codex/9355-conversation-mutation-contract
Sep 7, 2026
Merged

undivisible merged 4 commits into
BasedHardware:mainfrom
aryanorastar:codex/9355-conversation-mutation-contract

Conversation

@aryanorastar

@aryanorastar aryanorastar commented Aug 31, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Part of #9355.

This adds the first backend contract slice for reliable conversation sync:

  • add an authenticated POST /v1/conversations/{conversation_id}/mutations endpoint
  • support strict, typed set_title and set_starred operations
  • atomically persist each mutation result as a compact Firestore receipt
  • replay the exact original response when a client retries the same mutation ID
  • return typed conflicts for stale base revisions, reused mutation IDs, and unavailable revisions
  • publish the contract through OpenAPI and regenerate the macOS, Windows, and web clients
  • register the endpoint in the reviewed route-policy manifest

Why

Desktop clients can lose a response after the backend has already committed a write. Retrying a normal update is ambiguous: the client cannot tell whether it is applying the same intent once or a second time against newer state.

The durable receipt makes the mutation ID an idempotency boundary. A retry gets the originally committed result even if conversation processing or locking changed afterward. Reusing the same ID for different intent is rejected without mutating state.

Correctness guarantees

  • The receipt and conversation are read before any transaction writes.
  • A state-changing conversation write and its receipt share one Firestore transaction.
  • The response revision comes from the committed Firestore document metadata, avoiding timestamp precision loss.
  • A no-op preserves the existing conversation revision.
  • Exact retries are resolved before rechecking later lock or processing state.
  • A missing conversation cannot create an orphan receipt.
  • Locked conversations reject new mutations while still allowing exact replay.
  • Stale revisions return compact canonical user-owned state for reconciliation.
  • Receipts contain mutation metadata and compact sync state only; transcripts are not duplicated.
  • Existing Firebase authentication remains the authorization boundary.

Scope

This is intentionally the first slice of #9355, not the whole epic. It establishes the durable mutation and conflict contract for title/starred changes. Folder mutations, the desktop outbox, change feed, and tombstones remain follow-up slices because their atomicity and derived folder-count behavior need separate treatment.

Test proof

  • 12 passed — new mutation contract suite, covering changed/no-op writes, exact replay, replay after later state and lock changes, reused IDs, stale revisions, missing revisions, locked/missing conversations, HTTP 409 shape, and strict operation validation
  • 40 passed, 53 deselected — focused conversation regression suite
  • 27 passed — route policy inventory
  • Pyright: 0 errors
  • backend preflight: 18 passed, 0 failed (8 optional environment warnings)
  • OpenAPI compatibility and freshness checks passed
  • generated Dart/TypeScript/Swift client freshness checks passed
  • web: 72 files / 415 tests passed, plus 5/5 Moonshine tests
  • macOS: 714 suites passed
  • repository pre-push gate passed, including architecture, line-count ratchet, route policy, typecheck, unit tests, generated clients, web, and desktop checks

An exploratory full-backend run also surfaced existing Deepgram retirement expectation failures in unchanged STT test files; the mutation-specific and neighboring conversation suites are green.

No physical-device validation is required for this backend-only contract slice.

Review in cubic

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@aryanorastar
aryanorastar force-pushed the codex/9355-conversation-mutation-contract branch from 240ed99 to 8283cc5 Compare August 31, 2026 12:32
@aryanorastar

Copy link
Copy Markdown
Collaborator Author

Final verification for 8283cc55eb:

  • Backend unit suite: passed — 1,018 test files
  • Backend emulator proofs: passed
  • Backend hermetic E2E + merge gate: passed
  • Public Developer API contract: passed
  • Desktop generated-client contracts: passed
  • Desktop Swift release compile: passed
  • Desktop Swift static + full test contracts: passed
  • Windows typecheck/lint/test, build smoke, Linux helper smoke, web lint/build, formatting, hygiene, and source-closure: passed

Focused local proof remains 12/12 mutation tests, 40 focused conversation tests, 27 route-policy tests, pyright with 0 errors, generated OpenAPI/client checks current, and the repository pre-push gate green. This slice is backend/API-contract only, so no physical-device validation is required. It intentionally implements the durable idempotent title/starred mutation foundation as part of #9355; feed, tombstones, folders, and desktop outbox wiring remain follow-up slices.

@Git-on-my-level

Copy link
Copy Markdown
Member

Thanks @aryanorastar — this is a well-constructed first slice of the #9355 mutation contract. Notes from review, then two decisions that should get maintainer sign-off before merge.

What looks right:

  • backend/database/conversation_mutations.py — reads both the receipt and the conversation before any write, commits the conversation patch and its receipt in one Firestore transaction, and resolves exact retries before re-checking lock state, so a committed mutation keeps replaying even after the conversation is later locked or further processed. Receipt ids are the SHA-256 of client_mutation_id, keeping arbitrary client strings out of document paths, and receipts store only the compact user-owned projection (the tests assert transcript_segments never land in a receipt).
  • backend/routers/conversation_mutations.py — thin and consistent with existing conversation routes: Firebase auth via get_current_user_uid, 402 with the same paid-plan detail as _get_valid_conversation_by_id, a typed 409 body instead of a detail envelope, and 503 when a committed receipt cannot be read back — fail-closed, and a retry then replays the committed result rather than double-applying.
  • backend/models/conversation.py — strict contract: extra: 'forbid' on both operations, discriminated union on type, title bounded 1–256, and a constrained mutation-id charset/length. The smuggled-field test (422 on {'type': 'set_starred', 'starred': 'yes', 'title': 'smuggled'}) is exactly the right check.
  • backend/database/conversation_revisions.py / conversations.py — clean extraction of the revision helpers with behavior preserved and no other callers of the old private names.
  • The set_title patch ({'structured.title', 'user_title'}) matches update_conversation_title exactly, and processing-side writes already preserve user_title, so field-ownership semantics are unchanged.
  • The unit suite's fake Firestore enforces reads-before-writes ordering and covers replay-after-processing-advance, replay-before-lock, lock bypass, orphan receipts, mutation-id reuse, stale-base conflict replay stability, revision-unavailable fail-closed, and the HTTP 409/422 contract — a genuinely thorough set.

Two decisions for a maintainer before merge:

  1. Receipt retention — every unique client_mutation_id creates a permanent receipt document under the conversation, and conflict outcomes (base_revision_mismatch, revision_unavailable) are recorded durably too. There is no TTL/cap/GC. Is unbounded per-conversation receipt growth acceptable, or should this land with a retention policy (e.g. a TTL on mutation_receipts) or an agreed follow-up? Contract subtlety worth confirming on the desktop side: after any conflict, clients must mint a fresh mutation id, because replaying the same id replays the recorded conflict forever (per spec, but the client needs to be built to match).
  2. backend/route_policy_manifest.yaml — the new route is declared with rate_limit: none (consistent with sibling conversation routes) and self-declares review_status: reviewed for a route this PR is itself introducing. Both may be intentional; both deserve a conscious call since this is a new authenticated write surface that also persists a document per unique id.

Everything else (export_openapi.py Developer-API exclusion, regenerated Swift/TS clients, app-client-openapi.json) checks out as consistent regeneration. No correctness or security issues found — human review needed for the data-retention and rate-limit decisions above, not for the implementation.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@Git-on-my-level Git-on-my-level added needs-maintainer-review Needs a human maintainer to sign off before merge backend Backend Task (python) labels Aug 31, 2026

@kodjima33 kodjima33 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Solid backend contract slice (idempotency receipts for conversation mutations), well tested — but this is a new capability, not a bug fix, so approve-only per policy.

@Git-on-my-level Git-on-my-level removed the needs-maintainer-review Needs a human maintainer to sign off before merge label Sep 1, 2026
@Git-on-my-level

Copy link
Copy Markdown
Member

Follow-up on the earlier automated review of this head: the two items it left for maintainer sign-off — (1) receipt retention, since every unique client_mutation_id durably creates a mutation_receipts document (conflict outcomes included) with no TTL/cap today, and (2) the new route's rate_limit: none and self-declared review_status: reviewed in backend/route_policy_manifest.yaml — are covered by @kodjima33's approval on 8283cc5.

No further concerns from automation on this head. The transactional receipt semantics in backend/database/conversation_mutations.py (single-commit conversation patch + receipt, retry-before-lock ordering, fail-closed 503 read-back), the typed conflict contract, and the regenerated clients all hold up under re-verification.

One forward-looking note for the #9355 follow-up slices: if unbounded receipt growth wasn't a conscious accept, it's worth tracking a TTL/cap decision before the desktop outbox wiring lands — that's what will multiply mutation ids per conversation in practice.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

…on-mutation-contract

# Conflicts:
#	backend/route_policy_manifest.yaml
@Git-on-my-level

Copy link
Copy Markdown
Member

Verified the new head 8e04ccb - a merge of main into the previously approved 8283cc5 - and the integration is clean:

  • All five new feature files are byte-identical to the approved head: backend/database/conversation_mutations.py, backend/database/conversation_revisions.py, backend/routers/conversation_mutations.py, backend/tests/unit/test_conversation_sync_mutations.py, and the macOS generated client.
  • The manual conflict resolution in backend/route_policy_manifest.yaml checks out: the manifest parses, the new POST /v1/conversations/{conversation_id}/mutations route appears exactly once, and the merge dropped or duplicated no other route entries.
  • The regenerated artifacts are consistent: docs/api-reference/app-client-openapi.json carries the full strict contract (client_mutation_id charset/length bounds, extra: forbid on both operations, the type discriminator, and the typed 409), and the Windows/admin/app/personas generated clients are identical to each other.
  • Cross-checked one lifecycle seam against current main: delete_conversation recursively purges every subcollection under the conversation document, so mutation_receipts documents are removed with their conversation - no orphan-receipt path.

Two state notes, neither a concern: the earlier approval targets the pre-merge head, so the integrated head needs the usual maintainer confirmation before merge, and Desktop Swift Static & Test Contracts was still running at review time (everything else green).

No new concerns from automation on this head, and nothing needed from you, @aryanorastar - thanks for keeping the slice current with main.


By AI on behalf of David. Routine merge-integration verification - no urgent action requested; normal review queue applies.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

…on-mutation-contract

# Conflicts:
#	desktop/macos/Desktop/Sources/Generated/OmiApi.generated.swift
#	desktop/windows/src/renderer/src/lib/omiApi.generated.ts
#	web/admin/lib/services/omi-api/omiApi.generated.ts
#	web/app/src/lib/omiApi.generated.ts
#	web/personas-open-source/src/lib/omiApi.generated.ts
@aryanorastar

Copy link
Copy Markdown
Collaborator Author

Conflicts resolved on 0832e9e5ce. All five were generated clients, so I regenerated rather than hand-merged.

main added endpoints to the shared OpenAPI surface while this branch added POST /v1/conversations/{conversation_id}/mutations, and the two collided in every generated artifact:

desktop/macos/Desktop/Sources/Generated/OmiApi.generated.swift
desktop/windows/src/renderer/src/lib/omiApi.generated.ts
web/admin/lib/services/omi-api/omiApi.generated.ts
web/app/src/lib/omiApi.generated.ts
web/personas-open-source/src/lib/omiApi.generated.ts

Hand-resolving generated output would have produced files that no generator run reproduces, and the freshness checks would have caught it later at best. Instead I took main's side for all five and re-ran export_openapi.py, generate_ts_openapi_types.py and generate_swift_openapi_types.py, so the endpoint is re-derived from the backend source — which never conflicted — rather than stitched in by hand.

Verified rather than assumed: generate_ts_openapi_types.py --check and generate_swift_openapi_types.py --check both pass, and the mutations path is present in all five clients (the Swift client shows one occurrence because it emits a single path constant, let _path = "/v1/conversations/\(conversationId)/mutations").

Diff against main is back to the same 15 files. test_conversation_sync_mutations.py 12/12, and check_route_policy_baseline.py --base-ref origin/main reports the missing-route baseline current, so the manifest entry survived this merge as it did the last one.

Note on approval state: @kodjima33's approval targeted 8283cc5, two merges back. Nothing PR-owned has changed since — both merges were integration only — but the approval does not automatically carry to this head.

One CI note that is not this PR: Desktop Swift Static & Test Contracts was cancelled after 95 minutes on the previous head, which failed the required Desktop Swift Build & Tests check downstream in 3 seconds. Same budget-overrun shape as the release lane, filed separately as #12735; nothing in this backend slice affects it.

@kodjima33 kodjima33 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

feat(backend): durable conversation mutation receipts — feature not bug fix, stays approve-only per policy; CI all green, mergeStateStatus CLEAN (previously DIRTY, now resolved upstream), diff re-reviewed at new head 0832e9e.

@Git-on-my-level

Copy link
Copy Markdown
Member

Verified the new head 0832e9e - the second main merge - and the integration is clean:

  • The four hand-written feature files are byte-identical to the approved 8283cc5: backend/database/conversation_mutations.py, backend/database/conversation_revisions.py, backend/routers/conversation_mutations.py, and backend/tests/unit/test_conversation_sync_mutations.py. The ConversationSync* block in backend/models/conversation.py is unchanged too; that file's only delta versus 8283cc5 is main-side content (the new Shared* public-share projections).
  • The five generated clients (desktop/macos/.../OmiApi.generated.swift and the four omiApi.generated.ts copies) plus docs/api-reference/app-client-openapi.json were regenerated to resolve real collisions with main-side endpoint additions in the shared OpenAPI surface. The diffs are the expected union: new ConversationSync* schemas alongside main's additions, nothing dropped or hand-edited.
  • backend/route_policy_manifest.yaml still carries exactly one new entry (POST /v1/conversations/{conversation_id}/mutations, rate_limit: none, matching the sibling first-party conversation routes), and backend/scripts/export_openapi.py keeps it out of the Developer API key contract just like the starred/folder PATCHes.

No new concerns from automation on this head; @kodjima33's approval covers it. The earlier forward-looking note stands for the #9355 follow-up slices: settle a receipts TTL/cap decision before the desktop outbox lands and starts multiplying mutation ids per conversation.


by AI on behalf of David (@Git-on-my-level).

@aryanorastar

Copy link
Copy Markdown
Collaborator Author

Tracked the receipts retention question as #12783, since it has now been raised twice and would otherwise disappear when this merges.

I verified the shape rather than restating the concern:

  • No expiry path exists — grep -E "ttl|expire|prune|cap" over conversation_mutations.py matches only the module docstring. Receipts are written to conversation_ref.collection('mutation_receipts'), one per unique client_mutation_id, with conflict outcomes persisted too.
  • No orphans, as you noted: delete_conversation is documented as deleting "a conversation and every subcollection underneath it", so receipts die with their conversation.
  • Documents are small — metadata plus the compact user-owned projection, and the suite asserts transcript_segments never land in one.

So it is growth in document count per live conversation, not leaked storage or payload bloat. Today that is bounded by how often a human renames or stars something; the outbox slice is what changes the rate, because it is the component that mints ids programmatically and retries them. Which is exactly why you flagged it as a before-the-outbox decision, and I agree.

The issue lays out the three options and notes the part that makes it a real decision rather than a chore: a TTL is a correctness boundary, not just cleanup. Once a receipt expires, a retry of that id stops replaying and starts re-applying — so the TTL has to exceed the longest window in which a client might still retry, which the outbox's retry horizon determines. That is why I have not picked a number; it is a data-retention call that should be made deliberately rather than inferred from my preference.

Nothing changes in this PR. The diff is unchanged, and #12783 is a follow-up rather than a blocker — the receipts behaviour here is correct as specified, it just needs a lifecycle decided before the thing that multiplies it arrives.

@Git-on-my-level

Copy link
Copy Markdown
Member

Thanks @aryanorastar — filing #12783 is the right home for the retention question, and the verification you posted holds up against main:

  • delete_conversation in backend/database/conversations.py enumerates conversation_ref.collections() live and calls delete_collection_recursive on each, so mutation_receipts documents are purged together with their parent conversation — no orphaned receipts after deletion.
  • Confirmed there is no expiry/cap path in backend/database/conversation_mutations.py: one receipt document per unique client_mutation_id (conflict outcomes included), so the TTL/cap decision in mutation_receipts grow unbounded per conversation: decide TTL/cap before the #9355 desktop outbox lands #12783 is the remaining open item before the desktop outbox starts building on this endpoint.

Nothing further from automation on this head (0832e9e): the transactional receipt semantics, the fingerprint-checked replay ordering, and the route_policy_manifest.yaml registration were reviewed in earlier passes and are unchanged, and @kodjima33's approval covers this head.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

…on-mutation-contract

# Conflicts:
#	backend/route_policy_manifest.yaml
@aryanorastar

Copy link
Copy Markdown
Collaborator Author

Merged origin/main into the branch on 491c4ac. The PR had gone DIRTY again — one conflict, backend/route_policy_manifest.yaml, for the third time.

The collision is structural rather than semantic, and worth naming since it will keep happening: main added GET /v1/static-map at the same list position where this branch adds POST /v1/conversations/{conversation_id}/mutations. Both entries share the same trailing block — timeout_class: default_method, surface: first_party_app, visibility: first_party, data_domain: conversations — so git matched those lines as common context and interleaved the two items into one mangled entry rather than reporting them as two separate additions. Taking either side would silently drop a route.

Resolved by writing both entries out in full, then verifying the result rather than eyeballing it: parsed the manifest and diffed route keys against main — 149 entries here versus main's 148, exactly one added (http POST /v1/conversations/{conversation_id}/mutations), none dropped, no duplicate keys. check_route_policy_baseline.py --base-ref origin/main reports the missing-route baseline current, so the manifest entry survived this merge as it did the previous two.

The five generated clients and app-client-openapi.json auto-merged this time, but I regenerated them anyway rather than shipping the auto-merge — same reasoning as the last merge here: a generated file that no generator run reproduces is a file whose freshness check passes today and fails on someone else's branch tomorrow. Re-ran export_openapi.py --surface app-client, generate_ts_openapi_types.py and generate_swift_openapi_types.py; all three --check invocations pass, and the endpoint is present in all five clients (Swift shows it once, as the single path constant let _path = "/v1/conversations/\(conversationId)/mutations").

Verified nothing PR-owned moved: conversation_mutations.py, conversation_revisions.py, routers/conversation_mutations.py and test_conversation_sync_mutations.py are byte-identical to the approved 8283cc5, and the diff against main is back to the same 15 files, +1,434/−50.

Proof on this head: 12/12 mutation contract tests, 32/32 route-policy tests (test_route_policy_inventory.py + test_route_policy_preflight.py), route-policy baseline current, generated-client and OpenAPI freshness checks green, and the repository pre-push gate passed.

Approval state, same caveat as before: the approval targets 0832e9e, and both intervening changes were integration only — but it does not carry to this head automatically.

@undivisible
undivisible merged commit 46bea19 into BasedHardware:main Sep 7, 2026
35 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backend Backend Task (python) positive-signal Automation verified a genuine fix/quality contribution

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants