Repository navigation
fix: settle Pinecone mutations through route contention - #24583
Conversation
Serialize short same-owner admission and finish transactions within each process, and retry confirmed Firestore aborts with fresh transactions and bounded jitter. Keep provider calls outside locks and retain fail-safe uncertainty on exhausted finish. Failure-Class: FC-pinecone-route-document-contention
There was a problem hiding this comment.
1 issue found across 3 files
Confidence score: 4/5
_mutation_transactionduplicates the bounded retry logic infirestore_transaction_retry.py, which could let contention handling drift. Reuse the shared helper if it covers this transaction path.
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="backend/database/pinecone_partition_state.py">
<violation number="1" location="backend/database/pinecone_partition_state.py:131">
P2: `_mutation_transaction` re-implements the bounded fresh-transaction retry that already exists. `run_with_transaction_contention_retry` (firestore_transaction_retry.py) covers the Aborted and ValueError-from-Aborted cases, and `run_transactional(transient=True)` (_client.py) covers the finish transient errors. Route both through those helpers, or justify why they cannot be used, so the retry policy lives in one place.</violation>
</file>
Reply with feedback, questions, or to request a fix.
View guided diff | Turn on auto-fix | Re-trigger cubic
| return client.collection(COLLECTION).document(key.document_id) | ||
|
|
||
|
|
||
| def _mutation_transaction(client: Any, key: PartitionKey, function: Any, *args: Any, finish: bool = False) -> Any: |
There was a problem hiding this comment.
P2: _mutation_transaction re-implements the bounded fresh-transaction retry that already exists. run_with_transaction_contention_retry (firestore_transaction_retry.py) covers the Aborted and ValueError-from-Aborted cases, and run_transactional(transient=True) (_client.py) covers the finish transient errors. Route both through those helpers, or justify why they cannot be used, so the retry policy lives in one place.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/database/pinecone_partition_state.py, line 131:
<comment>`_mutation_transaction` re-implements the bounded fresh-transaction retry that already exists. `run_with_transaction_contention_retry` (firestore_transaction_retry.py) covers the Aborted and ValueError-from-Aborted cases, and `run_transactional(transient=True)` (_client.py) covers the finish transient errors. Route both through those helpers, or justify why they cannot be used, so the retry policy lives in one place.</comment>
<file context>
@@ -123,6 +128,27 @@ def _document(client: Any, key: PartitionKey) -> Any:
return client.collection(COLLECTION).document(key.document_id)
+def _mutation_transaction(client: Any, key: PartitionKey, function: Any, *args: Any, finish: bool = False) -> Any:
+ lock = _mutation_locks[int(key.document_id[:8], 16) % len(_mutation_locks)]
+ for attempt in range(3):
</file context>
Exercise twelve simultaneous same-owner deletes through three independent processes and real Firestore SDK transactions. Assert every namespace write settles, no journal rows remain, and all child processes are collected.
|
Pinecone: merges only in the lead's backend train |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
#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.
… 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]>
… per task (#24653) ## Problem Clearing a whole task section on mobile (`_confirmClearCompleted`, and the unused `clearCompletedItems`) sent one `DELETE /v1/action-items/{id}` per task, all at once. Each request does a Pinecone vector mutation whose begin and finish both write the owner's single route document (`pinecone_partition_state.py`). A 40-task clear became about 80 Firestore transactions on one document across Cloud Run instances, and some failed with `ValueError: Failed to commit transaction in 5 attempts`. The user saw rows reappear with an error. Prod `backend` stderr, counts only (ro-prod), 11-04: bursts of 27 (06–09Z) and 41 (15–18Z). After #24583 went live there was a single burst of 16 at 23:45Z on `backend-c94c934` (contains 43085bb). #24583 reduced these failures but didn't remove them. ## Change - `POST /v1/action-items/batch-delete` already settles many ids as one route mutation, and multi-select delete (`deleteSelectedItems`) already uses it. Section clear and `clearCompletedItems` now use the same path through a shared `_deleteItemsInBulk` helper. - Rollback behaviour is unchanged. If the request fails, every row goes back to its original position. If the server deletes only some rows, only the rejected rows come back. If the session changed mid-request, nothing is restored. Apple Reminders mirroring still fans out per item on the client, as before. - Locked (paid-plan) tasks are left out of a section batch. The batch endpoint refuses the whole request (402) if any id is locked, where a per-task delete refused only that task, so this keeps the old outcome: the rest is deleted, locked tasks stay, and the same failure notice shows. - Requests are sequential chunks of at most 450 ids. The server commits a batch delete in 499-document Firestore batches, so a larger request could fail half done and the client would restore rows the server had already deleted. Each chunk is now all-or-nothing, and a failed chunk restores only its own rows and the unsent rest (Luna R1 P2). A 1,000-task section is 3 requests, still 3 route mutations instead of 2,000 transactions. - Apple Reminders are deleted only for ids the server confirmed. Before, they were deleted before the request, so a rejected batch (including a 402 from a task that became locked after the list loaded) left rows back on screen with their reminders gone (Luna R1 P2). This also applies to multi-select delete, which shares the helper. - Known limit: a task that becomes locked on the server after the list loaded still makes its chunk return 402. The rows come back with the failure notice, and a refresh picks up the lock so the next clear succeeds. - macOS already uses `batch-delete` for bulk deletes (`TasksStore+BulkSelection.swift`). The web app has no bulk fan-out. ## Tried and dropped A larger server-side contention budget (8 fresh transactions inside 20 s) made the real-Firestore-emulator burst proof `test_real_firestore_cross_process_same_owner_deletes_settle` worse. Main passed 2/2 runs; the larger budget passed 1/5. Extra retries add lock pressure on the same document. The structural backend fix for older app versions is to move pending-op bookkeeping off the route document, which is a separate, larger change. ## Verification - `flutter test test/providers/` plus the page tests: 1,452 passed, including the new `action_items_section_clear_test.dart`, which covers one batch call and zero single deletes, full rollback, partial restore, locked tasks left out, an all-locked section sending nothing, 450-id chunking (1,000 tasks becomes 450/450/100), a failed second chunk restoring only its rows, and the empty no-op. Reminder ordering isn't covered by a unit test because reminder deletion is Apple-platform-only. - `flutter analyze` on the changed files: no issues. Formatting uses the pinned Flutter 3.44.5. ## Rollout App-only, no flag. Old app versions keep today's per-item behaviour. The prod signal to watch after this release reaches users is backend stderr `Failed to commit transaction in 5 attempts` on `delete_action_item`. ## Failure-class transition narrative Failure-Class: FC-pinecone-route-document-contention This is a recurrence after #24583. Its bounded retries cut a burst from 27–41 failures to 16, but a client that sends one delete per task still produces one route-document transaction pair per task. The prevention moves upstream: a section delete is one batch mutation, so the burst never forms. The server-side bound from #24583 stays as it is for older app versions. UI-Evidence: none -- no visual change; the confirm dialog, row removal and error toast are the same, only the request behind them changes (covered by provider tests) Line-Count-Exception: app/lib/providers/action_items_provider.dart | 1507 -> 1555 | the two delete paths now share one rollback helper instead of the section path fanning out; splitting the provider is out of scope for this fix 🤖 Generated with [Claude Code](https://claude.com/claude-code)
… per task Clearing completed tasks sent one DELETE per task at once. Every one of those requests writes the same per-owner Pinecone route document on the server (begin and finish of each vector mutation), so a section clear contended on one document across instances and some deletes failed with "Failed to commit transaction in 5 attempts" (prod 11-04: bursts of 27, 41 and, after BasedHardware#24583, 16). The batch-delete endpoint already settles many ids as one route mutation, and multi-select delete already used it. Section clear and clearCompletedItems now use the same path through a shared _deleteItemsInBulk helper, keeping the existing rollback: a failed request puts every row back in place, a partial result restores only the rejected rows. A larger server-side retry budget was tried and dropped: under the real Firestore emulator's 3-process burst proof it made settlement worse (main 2/2 pass, longer budget 1/5), because extra retries add lock pressure on the same document. Older app versions keep the server-side behaviour from BasedHardware#24583. Co-Authored-By: Claude Opus 5.5 <[email protected]>
What changed and why
Bursts of same-owner action-item deletes exhaust Firestore's five internal transaction attempts on the shared Pinecone route document. Short admission and finish transactions now share bounded process-local lock stripes. Cross-process aborts retry up to three fresh transactions with equal jitter, including the SDK's
ValueErrorcaused byAborted. Provider IO stays outside the locks and is never replayed by these retries.The existing batch-delete path already sends chunks through one admission each, so no new batch API is needed. Vector failures still propagate: there is no durable action-item vector repair contract that would justify returning successful deletion after a failed vector delete. Exhausted admission makes no provider call; exhausted finish retains the existing uncertain/pending safety fence. Existing stuck operations and operator/migration behavior are untouched. Ships on with no flag.
The stripes coordinate only within one serving process. Across instances, correctness relies on Firestore transactions and the independent abort retry: at most three fresh transaction chains (each SDK chain keeps its five commit attempts), with two equal-jitter sleeps totaling at most 0.6 seconds. This bounds attempts, not RPC wall time, and does not guarantee success under sustained contention; exhaustion still fails safe. The real emulator proof uses three separate processes with four simultaneous deletes each: 12 deletes, 24 provider acknowledgements, and zero pending/uncertain/journal rows. The scratch proof passed in 98.96 seconds. Earlier 24-delete probes exceeded their 150-second test deadline; no claim is made about that load or production latency.
Product invariants affected
none
How it was verified
BACKEND_UNIT_TEST_FILE_LIST=/Volumes/Ephemeral/scratch/pccontend/tests.txt BACKEND_PYTEST_WORKERS=1 bash backend/test.shthroughomi-heavy run -- nice -n 19: state and owner-index unit suites.backend/test.shwith the state suite's integration marker: 24 concurrent same-owner deletes throughOwnerIndex, both namespace acknowledgements, zero pending/uncertain operations, and no journal leftovers. A provider barrier proves transactions release the stripe before provider IO. Pinecone is a recording fake; no cloud or Pinecone writes.DELETE /v1/action-items/{id}via FastAPI TestClient and the real vector helper/OwnerIndex: 204 after two injected SDK-wrapped finish aborts, exactly two namespace deletes, zero pending/uncertain operations, LSN 42. Task persistence and Pinecone are synthetic, outbound network and notifications blocked. Proof:/Volumes/Ephemeral/scratch/pccontend/test_http_delete.py, run throughbackend/test.sh(1 passed).make preflightthroughomi-heavy run -- nice -n 19: all 36 selected checks passed. Focused unit suites: 143 passed, repeated after the cross-process regression. Firestore emulator integration suite: 6 passed, including the committed three-process proof.1cae9ebb1ab8and delta review atc0cdc011e31eboth returned SHIP, no findings. The delta brief explicitly covered cross-instance contention and bounded retry limits.CI baseline comparison: the final head's emulator job has the same 162 missing-
monotonicAttributeErroroccurrences as main 5164cef. The initial head's unit shard 3 and main's shard 3 fail at the same vendor-client and playback source assertions. Pinecone lead instructed this lane to leave baseline failures to the lead and hand off after review. Remaining final-head checks are still running; GitHub is the current status authority.Tests
test_wrapped_contention_is_bounded_and_never_repeats_providercovers recovered and exhausted begin/finish, multi-ID scope, fresh transactions and jitter bounds.test_finish_lost_ack_then_wrapped_contention_keeps_acknowledged_lsncovers idempotent settlement after a lost response. Ambiguous admission errors are not replayed.test_real_firestore_concurrent_same_owner_deletes_settlecovers real SDK contention/convergence.test_real_firestore_cross_process_same_owner_deletes_settlechecks 12 same-owner deletes across three independent processes, each with its own stripes and registry. It collects or terminates every child under a hard deadline.UI evidence
UI-Evidence: none -- backend persistence fix
Failure class (fixes)
Failure-Class: new
Failure-class transition narrative
Adds FC-pinecone-route-document-contention: serving mutations must survive transient route-document contention without repeating provider writes or weakening migration fences. The prevention is short transaction serialization plus bounded explicit-abort retries, guarded at the provider boundary and with the real Firestore emulator. Production evidence: 24 transaction-exhaustion errors in 17 seconds during concurrent single-item deletes on 2026-11-04; the same signature predates that burst.