Skip to content

fix(backend): fail privacy deletion open when the vector store is unconfigured - #15097

Merged
kodjima33 merged 3 commits into
BasedHardware:mainfrom
aryanorastar:fix/desktop-memory-delete-unprovisioned-vectors
Sep 20, 2026
Merged

kodjima33 merged 3 commits into
BasedHardware:mainfrom
aryanorastar:fix/desktop-memory-delete-unprovisioned-vectors

Conversation

@aryanorastar

@aryanorastar aryanorastar commented Sep 20, 2026 •

Copy link
Copy Markdown
Collaborator

What changed and why

Every API service runs without a vector store: backend/deploy/runtime_env.yaml binds PINECONE_API_KEY only to the dev pusher and to the notifications-job and memory-maintenance-job Cloud Run jobs in dev and prod, and .github/workflows/desktop_backend_prod.yml deploys with --remove-secrets=PINECONE_API_KEY,PINECONE_HOST. So vector_db.index is None on the request path.

Since the fail-closed hardening, delete_canonical_memory_vectors returned False there and HistoricalMemoryAdapter.cleanup(required=True) turned that into 503 Historical memory privacy cleanup unavailable — every DELETE /v3/memories/{memory_id} failed on desktop, while deleting a conversation still worked because a non-cascade conversation delete never reaches the vector store. That is exactly the split two reporters describe on desktop beta 0.12.364: conversations delete, memories do not.

Deleting the user's data is the privacy-preserving direction: with no configured vector store there is nothing to purge, so cleanup completes; a configured store that errors still fails closed.

Both commits come from #14691, cherry-picked with -x and otherwise unchanged. That PR also restores the 204 delete contract on DELETE /v1/conversations/{conversation_id} for the released mobile client; those commits are deliberately not here, because I am not working mobile-side contracts. The two changes are independent, but if #14691 lands first this PR is redundant and should be closed.

Product invariants affected

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

The behavior change preserves them: deletion completes where no derived store exists, instead of erroring.

How it was verified

Both halves of the fix were pinned against unpatched origin/main (094514c) in a separate worktree, by copying only the new tests over and running them there:

Test origin/main This branch
test_delete_canonical_memory_vectors_confirms_absence_when_index_unconfigured FAILED passed
test_required_historical_cleanup_completes_when_vector_store_unconfigured FAILED passed
test_conversation_delete_cascade_completes_without_vector_store passed passed

The third is characterization rather than a guard — it passes either way, matching the file's own description as a cascade characterization matrix.

Whole files on this branch, through BACKEND_UNIT_TEST_FILE_LIST bash test.sh: test_canonical_memory_vectors.py 20 passed, test_ws_j_delete_privacy.py 44 passed, test_universal_memory_service.py 106 passed.

The deployment statements above are read from main (runtime_env.yaml, desktop_backend_prod.yml), not from live deployed state.

Not verified

I did not exercise DELETE /v3/memories/{memory_id} over HTTP. The offline harness needs Docker and a Typesense runtime this machine does not have — PROVIDER_MODE=offline make dev-up stops at that prerequisite — so the evidence here is the code path, the deploy config and those suites. #14691 records an end-to-end run of the route against a local uvicorn.

Tests

The two guard tests above are the regression tests: each fails on origin/main with the exact pre-fix behavior (delete_canonical_memory_vectors reporting failure on an unconfigured index, and required historical cleanup raising 503) and passes here.

Failure class (fixes)

Failure-Class: new

Failure-class transition narrative (only when needed)

FC-privacy-delete-fails-on-unprovisioned-derived-store is added in this change, authored in #14691. Violated contract: a privacy deletion must not fail closed because a derived, rebuildable store was never provisioned — absence of that store means there is nothing to purge, while a configured store that errors must still fail closed. Canonical prevention: the deletion path treats an unconfigured derived store as confirmed absence, pinned by the two guard tests above.

Line-Count-Exception: backend/utils/memory/memory_service.py | 4310 -> 4312 | The gate that must stop failing closed is HistoricalMemoryAdapter.cleanup, the adapter's own privacy-cleanup boundary; the two added lines are the comment recording why an unconfigured derived store is nothing to purge.

Review in cubic

ampagent and others added 3 commits September 20, 2026 09:42
…onfigured

BasedHardware#10451 (5fa372e) made Pinecone-unavailable failure handling fail closed:
HistoricalMemoryAdapter.cleanup(required=True) raised 503 when
vector_db.index is None, and delete_canonical_memory_vectors returned False
→ RuntimeError → 503 on cascade retraction. Production never provisions
Pinecone on most releases (backend/deploy/runtime_env.yaml attaches the key
only to llm-gateway releases; desktop_backend_prod.yml explicitly strips it),
so every DELETE /v3/memories/{id} and every cascade
DELETE /v1/conversations/{id}?cascade=true deterministically 503'd — the
desktop app surfaces the error verbatim, and mobile reads the non-200 as a
failed delete, drops the tombstone, and the item resurfaces on refresh
(BasedHardware#10446 recurrence).

Deletion of the user's data is the privacy-preserving direction: when no
derived vector store is configured, there is nothing to purge, so cleanup
completes successfully; a configured store that errors still fails closed.

Tests cover the unconfigured-index deletion path, required historical
cleanup completing without a vector authority, and cascade deletion of a
conversation with attributed memories completing without a vector store.

Verified: offline harness — memory delete returned 503 before this change
and 200 afterwards.

Failure-Class: FC-privacy-delete-fails-on-unprovisioned-derived-store
Amp-Thread-ID: https://ampcode.com/threads/T-01a0b590-2123-744a-9e4a-16706295c2d3
Co-authored-by: Max Carter <[email protected]>
(cherry picked from commit c55e69a)
…d-derived-store

Registers the definition for the privacy-delete failure class cited by the
two fixes in this branch.

Failure-Class: none
Amp-Thread-ID: https://ampcode.com/threads/T-01a0b590-2123-744a-9e4a-16706295c2d3
Co-authored-by: Max Carter <[email protected]>
(cherry picked from commit 12e47ac)
The definition listed test_conversation_delete_wire_contract.py, which pins
the 204 delete contract for the released mobile client and ships with that
fix, not with this one. Name the two guards that are here instead: the
unconfigured-index canonical vector delete and required historical cleanup
without a vector authority, plus the module each one guards.

Co-Authored-By: Claude Opus 5 <[email protected]>
@Git-on-my-level

Copy link
Copy Markdown
Member

Verified the deployment premise independently before commenting: parsed backend/deploy/runtime_env.yaml — PINECONE_API_KEY binds only to the dev gke pusher and the dev/prod notifications-job / memory-maintenance-job Cloud Run jobs — and .github/workflows/desktop_backend_prod.yml:317 strips PINECONE_API_KEY,PINECONE_HOST. So the API request path genuinely runs with vector_db.index is None, and on main every DELETE /v3/memories/{id} and cascade conversation delete deterministically 503s. This fix restores the privacy-preserving behavior.

Per-file notes:

  • backend/database/vector_db.py — index is initialized at import (lines 124-128), so None strictly means "not configured", never a transient provider failure; treating it as trivially-confirmed absence is sound. A configured index that raises still propagates (fail closed preserved).
  • backend/utils/memory/memory_service.py — dropping the required-and-None 503 pre-gate is safe because delete_memory_vector (vector_db.py:655-661) returns without raising when unconfigured, so the failures list stays empty only in the nothing-to-purge case; a configured store that errors still appends "vector" and 503s at the existing gate.
  • backend/tests/unit/test_canonical_memory_vectors.py — direct pin of the True return on the unconfigured path; good.
  • backend/tests/unit/test_universal_memory_service.py — inverting the old 503 test into a completion assertion (delete_vector and delete_content both called) is exactly the right regression pin.
  • backend/tests/unit/test_ws_j_delete_privacy.py — strongest of the three: wires the real production chain (canonical_vector_sync.delete_canonical_memory_vector → vector_db) with index stubbed to None and asserts the cascade retraction completes and the memory is gone from the canonical store.
  • .github/failure-classes/FC-privacy-delete-fails-on-unprovisioned-derived-store.json — matches the existing failure-class convention; the violated_contract description is accurate per the code paths above.

One question for a maintainer: the maintenance jobs that do hold Pinecone credentials share the index, so a keyless API service can ack a delete while a vector written by a credentialed job still exists until the vector repair/purge outbox worker converges it. The outbox is the durable authority (per _run_immediate_privacy_cleanup's docstring and delete_canonical_memories_batch), and the worker (memory_vector_repair_outbox_worker.py) has lease/retry/dead-letter handling — but please confirm the worker is actually deployed in dev and prod (memory_vector_repair_outbox_cloud_deployment_contract.yaml suggests yes).

Since this is a deliberate fail-open semantics change on a privacy deletion path, it needs maintainer sign-off before merge; leaving for human maintainer review rather than approving. Also noting: if #14691 lands first, this PR becomes redundant (the author already flagged this) — the two commits here are a clean cherry-pick of its backend half.

🤖 Automated review on behalf of the maintainers.


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 security-review Touches auth, provider routing, secrets, or security-sensitive surfaces backend Backend Task (python) labels Sep 20, 2026
@aryanorastar

Copy link
Copy Markdown
Collaborator Author

On the outbox question: the worker is not deployed, in dev or prod, and the deployment contract says so itself.

  • backend/docs/epics/memory_vector_repair_outbox_cloud_deployment_contract.yaml opens with Status: disabled-by-default readiness artifact; not applied to any cloud project, then No cloud resources are created by this file, and lists what is still required before enablement (production Firestore IAM proof, deployed rules proof, real Pinecone repair validation in ns2, telemetry and alerting).
  • Neither backend/deploy/runtime_env.yaml nor any workflow in .github/workflows/ mentions vector_repair or memory-vector-repair, so nothing renders or deploys that service.
  • The only deployed memory job is memory-maintenance-job, whose image runs CMD ["python", "memory_maintenance_job.py"] (backend/modal/Dockerfile.memory_maintenance_job:29). That entrypoint runs frame-request retention plus run_canonical_short_term_maintenance_cron; it never touches the outbox.

So the convergence you were counting on does not currently run anywhere. What that means for this PR, stated plainly:

  • Before it, a keyless API service 503s the delete, so the authoritative delete does not happen at all — the memory row and any vector both stay.
  • After it, the authoritative delete completes, and a vector written earlier by one of the credentialed jobs stays until something purges it. Today nothing does.

That is a strict improvement over 503-forever, but it is a real residue rather than a deferred one, and it is the maintainer's call whether to land this before the worker is deployed. Happy to file a tracking issue for the undeployed converger if that is useful — I did not want to open one against someone else's epic without a maintainer saying so.

All checks are green on this branch (22 passing, 19 skipped), and no code change was requested, so I have not pushed anything since opening.

@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.

Privacy-deletion fail-open fix for unconfigured vector store, scoped and well-tested; confirmed #14691 (broader competing PR) still open, not superseded. 5/5.

@kodjima33
kodjima33 merged commit 6a4928c into BasedHardware:main Sep 20, 2026
56 of 57 checks passed
Git-on-my-level added a commit that referenced this pull request Oct 21, 2026
…onfigured

delete_atom_keyword_doc returned False whenever the shared Typesense env was
absent or empty (lazy client construction raises, the generic except swallows
it), so _run_immediate_privacy_cleanup raised 'canonical keyword privacy
cleanup unavailable' and every explicit memory delete failed closed on
deployments that never write the keyword projection — the keyword recurrence
of FC-privacy-delete-fails-on-unprovisioned-derived-store (#15097 classified
the vector-store sibling but not this one). Classify the unconfigured state as
the trivially-confirmed desired absence before any client I/O; a configured
client that raises still fails closed, and empty uid/memory_id still returns
False.

Failure-Class: FC-privacy-delete-fails-on-unprovisioned-derived-store
Git-on-my-level added a commit that referenced this pull request Nov 4, 2026
… the age-gate survivor branch (#24602)

* fix(memory): retry transient store faults on canonical apply control read

A transient Firestore fault on the apply-control read was converted
straight into CanonicalApplyStateUnavailable (memory_system.py:64),
failing the whole apply gate for one blip. _read_snapshot now gives
store faults classified transient by transient_store_error the same
three-attempt backoff budget as the MCP OAuth refresh rotation before
failing closed; permanent faults and exhausted retries keep the
existing fail-closed behavior.

Failure-Class: none

* fix(memory): bound each retry attempt and recheck the deletion fence; add emulator proof

Review feedback on the canonical apply-control transient retry:

- Each attempt now disables the SDK's own (default 300s deadline) retry and
  passes an explicit per-attempt timeout (CANONICAL_APPLY_READ_TIMEOUT_SECONDS,
  default 5s), mirroring the MCP OAuth refresh-rotation boundary that owns its
  three-attempt budget. An exhausted SDK Retry policy would raise RetryError,
  which the transient classifier does not treat as retryable, so the typed
  error must surface at this boundary directly.
- The deletion fence is re-read before the first-write provisioning path: a
  wipe that completes while the retry loop waits can no longer re-enroll a
  wiped account as a fresh generation-1 control document.
- New Firestore-emulator proof (canonical_apply_control_retry_emulator_test.py)
  wired into run-emulator-proofs.sh: fault injection at the client API layer
  proves transient recovery, exhausted fail-closed (3 bounded attempts), the
  deletion race, and that every retried read passes retry=None plus a bounded
  timeout. Hermetic fakes updated to accept the new get() kwargs.

* fix(tests): shared Firestore fakes accept the retry/timeout read kwargs

The apply-control boundary now passes retry=None and a bounded timeout on
every document read; the shared canonical_memory_fakes._DocRef and the
WS-B _Document fake rejected those kwargs, and the resulting TypeError was
swallowed by the production except-Exception fail-closed path, failing 34
tests across five unit shards. Mirror the real SDK get() signature.

* fix(tests): remaining per-file Firestore fakes accept retry/timeout read kwargs

Same fix as the shared fakes for the two per-file fakes CI rounds reach:
canonical_consolidation_apply._FakeDocumentRef and the ws_j_delete_privacy
_DocRef. The apply-control read boundary passes retry=None plus a bounded
timeout on every document read; rejecting those kwargs fails closed through
the swallowed TypeError path.

* fix(memory): recheck fence before existing-state return; bound fence reads; one budget per control read

Review round 2 on the apply-control retry boundary:

- The post-retry deletion-fence recheck now also guards the existing-state
  branch (it previously ran only on the first-write path), so a deletion that
  starts during transient backoff cannot admit work or touch the maintenance
  registry under a running/completed wipe.
- The fence helper threads through optional retry/timeout read kwargs via an
  UNSET sentinel (other callers keep the SDK-default read), and the
  apply-control boundary passes its bounded per-attempt policy to every fence
  read, so the added safety check cannot pin a worker for the default 300 s.
- The exists-branch validates the recovered snapshot directly instead of
  re-reading the control document with a second fresh three-attempt budget;
  the create-race path likewise reads once and validates from that snapshot.
- Emulator proof: module-scope import per the backend import rule; fence stub
  accepts the new read kwargs.

* fix(memory): give fence reads the same transient budget; module-scope test imports

Review round 3:

- With the SDK retry disabled for the bounded fence read, a single transient
  blip on account_deletions/{uid} would fail the whole apply gate — the very
  failure mode this PR fixes. Both fence reads now run through the same
  three-attempt transient budget as the control read (one shared helper).
- Hoist the three retry tests' imports to module scope per the backend
  import rule.

* fix(backend): fail keyword privacy cleanup open when Typesense is unconfigured

delete_atom_keyword_doc returned False whenever the shared Typesense env was
absent or empty (lazy client construction raises, the generic except swallows
it), so _run_immediate_privacy_cleanup raised 'canonical keyword privacy
cleanup unavailable' and every explicit memory delete failed closed on
deployments that never write the keyword projection — the keyword recurrence
of FC-privacy-delete-fails-on-unprovisioned-derived-store (#15097 classified
the vector-store sibling but not this one). Classify the unconfigured state as
the trivially-confirmed desired absence before any client I/O; a configured
client that raises still fails closed, and empty uid/memory_id still returns
False.

Failure-Class: FC-privacy-delete-fails-on-unprovisioned-derived-store

* fix(backend): scope keyword privacy fail-open to fully-unconfigured Typesense

Review repair for #23063: delete_atom_keyword_doc confirmed absence whenever
typesense_configured() was False, i.e. also when exactly one of
TYPESENSE_HOST/TYPESENSE_API_KEY was bound. A partial binding does not prove
the projection absent — backend-listen binds only TYPESENSE_HOST while
backend-sync and memory-maintenance-job hold both against the same cluster —
so a rollout losing one variable would acknowledge the privacy deletion with
plaintext keyword documents still stored. Confirm absence only when neither
binding is present (Cloud Run backend, desktop), let partial bindings fail
closed through the client call, and instrument the fail-open with
record_fallback(reason=unconfigured, outcome=recovered) per the fallback
telemetry contract.

* feat(memory): stale-planner archive restore operator tool (2026-10-22)

Dry-run-first operator tool re-applying incident-archived memory_items as
short_term-visible decisions through the canonical apply ledger
(apply_long_term_patch_firestore) with the remediation=stale-planner-2026-10-22
audit marker, reversible via --revert. Per-user COLLECTION-scope scan with
read budget, keyset cursor, legal-hold/deletion-gate/deleted-user exclusions,
and payload-free count-only output. Registers the two memory_items query
drivers and regenerates the composite-index manifest. Prod writes remain
gated on the plan's explicit GO.

Co-Authored-By: GLM-5.3 <[email protected]>

* fix(conversations): require relevance decisions on terminal rows

Close decision gaps in dead-letter, orphan, BYOK, imports, external text, sync promotion, merge rollback, and legacy restore paths. Preserve calendar, photo, wake-word, rule-keep, and tombstone protections; keep mandatory decisions through terminal size guards.

Failure-Class: FC-contentless-recovery-surfaced-visible

* refactor(conversations): extract terminal storage and relevance labels

Keep the large conversation modules below their existing line budgets by moving snapshot status storage, deferred retry storage, pure terminal payload serialization, and bounded metric vocabulary to their owning modules. Migrate callers and behavioral/static coverage together.

Failure-Class: FC-contentless-recovery-surfaced-visible

* fix(conversations): stamp local fixture capture decisions

Cover the direct batch fixture writer with an explicit fixture-seed policy and bounded telemetry vocabulary. Preserve the local/offline account fence and extract the payload builder to keep its owner below the existing line budget.

Failure-Class: FC-contentless-recovery-surfaced-visible

* fix(conversations): refresh terminal visibility after commit

Invalidate people-stats and refresh search after terminal discards or document-ceiling failures commit. Isolate observer failures and publish no effects on aborted transactions. Document terminal relevance and size behavior in the lifecycle owner guide.

Failure-Class: FC-contentless-recovery-surfaced-visible

* fix(conversations): preserve positive evidence during terminal repair

* fix(conversations): retain recovery provenance when repairing keeps

* fix(conversations): preserve terminal verdicts and bound calendar probes

* fix(conversations): satisfy type checker on terminal decision sites

Narrow prior decision before subscripting, return str-keyed entries from
the preserve path, and expose a public accessor for the post-write search
index convergence instead of touching the private name.

* test: allowlist structural first-test CPU in terminal-decision suites

* test: allowlist the 70-minute narration fixture's first-test CPU

* fix(conversations): compose terminal decisions with wave-2 lifecycle

* style: pin the pinned formatter on test_recovery_rule_skip

* test(sync): align frozen parity with mandatory intake decisions

* fix(memory): invalidate projections on every committed retry

* Reconcile fold interactions with current main contracts

- finalization jobs: thread calendar_probe through the shared dead-letter helper
- sync intake: stamp explicit keep provenance only on newly created rows;
  replays retain their assessed verdict and promotions keep clearing the
  receipt (main's replay/promotion contracts)
- decision triggers: accept main's capture_group trigger
- parity fixture: re-pin frozen sources to the merged live files with a
  documented expectation update
- folded PR tests: point at the recovery module that now owns orphan
  completion, match current helper arities, RULES_VERSION, and the
  real-clock fence liveness window

* Restore origin/main's enrichment recovery emulator script

The refresh merge kept the survivor lineage's real-monotonic clock lines
without the import time that went with them, so the proof died on
NameError: time at line 111. The fold stack does not intentionally
change this script; take origin/main's blob wholesale. No retry or lease
behavior changes.

* Fix CI-red fold interactions against current main contracts

- lifecycle state table: the blocked_byok stock dwell alert is agent tier
  (omi-finalization-byok-dwell-info) since #24595 moved the page to fresh
  cohort dwell; re-point the inventory row and declare the folded writer
  moves (recover_deferred_processing_failure_txn and the dead-letter title
  helpers now live in conversation_terminal_title)
- crash-window orphans: an absent transcript is not evidence the user said
  nothing, so the orphan terminal recovery paths stage the path's policy
  keep as a prior verdict; dead_letter and BYOK abandonment keep their
  calendar-protected rule assessment of content-free audio
- run-emulator-proofs: drop the daily-sweep entry (main retired that proof)
- strict firestore fixture: model the canonical apply control read's
  retry kwarg, and default its per-attempt timeout to the modeled 3s bound
- folded tests: match the folded terminal receipt (replay exhaustion) and
  keep the size-rollover fixtures stamp-agnostic

* Classify the crash-window keep flag in the firestore query driver

* chore: retrigger PR workflows after a missed synchronize event

* Match the folded dead-letter keep receipt in the exhausted-requeue test

* Keep transcription-failed episode members in the home member projection

The size-ceiling terminal's failed-status visibility exclusion is a
conversation-list contract; the episode member surface renders a failed
member with its 'Couldn't transcribe' wire status so the user keeps the
bounded recovery exit. Exempt that surface from the exclusion instead of
weakening the shared predicate.

* Declare the diarization eval lifecycle writers in the site inventory

#24583 landed utils/stt/diarization_eval.py with seven lifecycle write
sites but no inventory entry; declare the reviewed sites so the writer
guard matches the real payload writes.

---------

Co-authored-by: David Zheng <[email protected]>
Co-authored-by: GLM-5.3 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backend Backend Task (python) security-review Touches auth, provider routing, secrets, or security-sensitive surfaces

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants