Repository navigation
fix(backend): reconcile stale bare-processing conversations after crash - #10468
Conversation
|
|
||
| def final_attempt_failed( | ||
| job_id: str, dispatch_generation: int, lease_epoch: int, retry_count: int, *, firestore_client: Any = None | ||
| ) -> bool: |
There was a problem hiding this comment.
🔒 Agentic Security Review
Severity: MEDIUM
The new reconciliation path logs raw uid and conversation_id values at info level for each recovered record. These stable identifiers are user-linked and increase exposure if logs are broadly accessible or retained.
Impact: This creates unnecessary account-correlation leakage in operational logs and increases privacy risk in any downstream log access or log-compromise scenario.
Reviewed by Cursor Security Reviewer for commit 7b6b00c. Configure here.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7b6b00ccfa
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
Request changes — safety and eventual-recovery gapsThis must not merge in its current form.
Remote Backend unit-suite failures are pre-existing import-isolation/dependency debt outside this diff, but the authoritative check is red and must be tracked/revalidated before merge. No new ticket is authorized; revise this existing PR only. |
|
Revised per the request-changes. Commits
Verification: 175 focused unit tests pass; hermetic listen-pusher gauntlet passes (~193s, real Firestore emulator); |
Request changes — stale-processing recovery remains unsafeThis revision improves coverage but cannot merge yet.
No new issue/PR/ticket is authorized. Revise this existing PR only. |
1aa7cc8 to
30a9863
Compare
|
Revision 2 pushed (commits
Verification: focused unit tests pass; hermetic listen-pusher gauntlet passes (~187s, re-run post-rebase); Failure-Class: FC-split-mutation-authority |
Third request changes — recovery is still unsafe across production paths/podsIndependent review found remaining correctness blockers. Keep work in this existing PR only.
The remote static/openapi/backend-unit/hermetic prewarm failures are documented baseline/infrastructure problems; do not repair them in this PR. Rebase/revalidate only after the above substantive corrections. |
Fourth request changes — two ownership-loss paths remain unsafeThe operating/configuration audit is now clean, but independent lifecycle review found two merge blockers:
Keep this one existing PR only. Do not repair baseline OpenAPI, CI bootstrap dependencies, or unrelated work. |
Fifth request changes — fence all finalizer side effects and repair executable checksIndependent review found the durable finalizer fence still occurs after Required changes on this existing PR only:
Do not touch base OpenAPI snapshot, CI bootstrap dependency debt, or unrelated code. Push only this branch after clean focused, repeated gauntlet, and CI-style command results. |
Final operational request change — complete scheduler runtime parityThe lifecycle/side-effect review is now clean. One operational configuration defect remains:
Add the classified setting to dev/prod |
4a81c81 to
d6e3a2d
Compare
|
Resolved the two Codex P2 review threads — both were
No code push this run — the concerns were already addressed in earlier revisions; the threads were stale. The three red backend checks (Backend unit suite, Public Developer API contract, Static Contracts) are pre-existing base failures (missing |
kodjima33
left a comment
There was a problem hiding this comment.
fix(backend) reconcile stale bare-processing conversations — approve only (2867 lines, exceeds scope ceiling)
d6e3a2d to
e6fdd6e
Compare
|
Rebased onto latest The three red checks remain pre-existing base failures (identical on latest
The Hermetic Backend E2E, Listen Pusher Stack Gauntlet, Sync Cloud Tasks Stack Gauntlet, and Backend Hermetic Merge Gate all pass on the rebased head. |
The synchronous legacy POST /v1/conversations route admits a conversation to `processing` with no durable job; a hard process crash between admission and completion strands the row. The durable replay sweep only covers rows that own a finalization job, so the recording never resolves and the client shows a stuck Processing card. Add a conservative safety-net sweep that closes bare-`processing` orphans (status=processing, no finalization_job_id, not deferred, past an admission-age threshold) through the truthful terminal ownership CAS (lifecycle.complete), so each reaches exactly one terminal and stays retrievable. Admission now stamps `processing_admitted_at` so the threshold bounds admission age rather than document-creation age. The sweep creates no durable job and never touches a row a durable job still owns; re-enrichment is a separate follow-up. Refs #10461 Failure-Class: FC-split-mutation-authority
…g orphan
Adds a hermetic cloud_tasks scenario that seeds the crash-window state (a bare
`processing` conversation with no durable job, past the conservative threshold),
triggers the startup reconciler drain, and proves:
- the aged orphan is driven to exactly one terminal (completed) with no durable
job created and no worker/integration fanout;
- a too-recent admission is left on `processing` (threshold respected);
- a durable-job-owned row is never double-finalized;
- GET /v1/conversations/{id} returns the reconciled terminal conversation;
- the sweep is idempotent across restarts.
Wires the scenario into the gauntlet and the blocking CI command.
Refs #10461
Failure-Class: FC-split-mutation-authority
…on fence Revision of #10461 per PR review: the orphan sweep must not terminalize live work, must reach every eligible orphan, and must surface alertable outcomes. Authority fence: eligibility is bounded by the server-owned processing_admitted_at stamp, never caller-controlled created_at (which is the recording start time for from-segments/sync imports, not the admission instant). create_processing_conversation now stamps the fence at every server/merge/import/developer admission; legacy rows predating the fence are migrated by stamping it and deferred to a later sweep rather than completed on first sight. complete()'s ownership CAS still fences any already-terminal/superseded row, so each orphan reaches exactly one terminal. Saturation: the single-equality collection_group query pages with a start_after cursor so a stable first page of excluded (deferred / durable-job-owned / fresh / legacy) rows cannot starve a later eligible orphan; total examined rows are bounded by max_scan. Index: the single-equality collection_group query rides Firestore's automatic single-field index (no composite). Proven by the firestore-query-coverage ratchet (exit 0, no new debt) and an unchanged firestore.indexes.json manifest. Setting: LISTEN_FINALIZATION_ORPHAN_STALE_SECONDS is clamped to a 300s floor and a one-day ceiling. Metrics: outcomes surface on LISTEN_FINALIZATION_STALE_PROCESSING_RECONCILIATIONS_TOTAL{outcome} (completed/migrated/skipped/error), zero-initialized, dashboarded, and privacy-safe (aggregate counts only, no user identifiers in success logs). Failure-Class: FC-split-mutation-authority
…ud-Tasks Unit contracts in test_conversation_finalization_jobs.py: the orphan query is a single-equality collection_group query (index tripwire); age authority is processing_admitted_at not created_at (fresh-admit/old-create, old-admit/fresh-create, legacy-no-admit); deferred and durable-job rows are excluded; cursor pagination pages past >100 excluded rows to a later orphan; the per-sweep scan is bounded; legacy stamping is idempotent and fences non-processing rows; the stale-after window is clamped. New test_stale_processing_reconciliation.py: legacy rows migrate not complete, aged orphans reach exactly one terminal, fenced rows skip, query failure is fail-closed, and outcomes increment the privacy-safe counter. Hermetic listen_pusher_stack gauntlet: the cloud scenario now covers legacy migration (two-phase: stamp then complete after aging), deferred exclusion, >100-row saturation with a later eligible orphan, no worker/fanout for any outcome, and idempotent re-sweep; a new inline (non-Cloud-Tasks) scenario proves the reconciler runs without durable dispatch. Failure-Class: FC-split-mutation-authority
… ownership fence Revision 2 of the #10461 crash-orphan reconciler, addressing the request-changes: 1. Eventual discovery: a persisted, rotated sweep cursor resumes a bounded window each periodic invocation and wraps to the top once the collection is exhausted, so a stable excluded prefix larger than any per-invocation max_scan cannot permanently hide a later orphan. 2. Ownership fence: a transactional fenced completion (complete_orphan_conversation) verifies the exact scanned generation, absence of finalization_job_id, and non-deferred/non-terminal state immediately before terminalization. A live synchronous processor renews its admission lease (processing_admitted_at) on a heartbeat while the guarded block runs, so a slow-but-alive processor always looks fresh to discovery and can never be terminalized; only a hard-crashed processor stops renewing. 3. Operational contract: LISTEN_FINALIZATION_ORPHAN_STALE_SECONDS is declared in backend/deploy/runtime_env.yaml (dev+prod backend-listen) with category reliability; unexpected per-row exceptions are counted as error, distinct from expected CAS skips. Failure-Class: FC-split-mutation-authority
Adds the revision-2 regressions: persisted-cursor repeat-sweep beyond any per-invocation bound (proves eventual discovery); transaction-level ownership fence for a finalizer-claimed row, a lease-renewed live processor, and deferred/terminal rows; lease heartbeat renewal while the synchronous processor is alive; unexpected per-row exception counted as error distinct from a CAS skip; and a behavioral test that the periodic (not only startup) reconcile drives the sweep.
…r CAS Behavioral tests through actual code paths (not context-manager tests) proving the processing admission lease is renewed while process_conversation runs for from-segments, merge, and deferred-enrichment paths (#10461). Cursor CAS unit tests verify generation-based compare-and-swap prevents multi-pod rewind. Updated the cursor rotation test for the new dict-based CAS cursor API. Emulator concurrency tests (FIRESTORE_EMULATOR_HOST) prove: - Two competing cursor writers: exactly one CAS succeeds, generation +1 - Serial cursor advances: all committed - Finalizer-vs-orphan race: exactly one transaction commits, no false completion of active work Failure-Class: FC-split-mutation-authority
Apply the processing admission guard (lease heartbeat + generation fence) to every live bare-processing producer: from-segments, merge, and deferred enrichment. rollback_on_failure=False for these paths because they own their own recovery (delete on exception, complete on failure). The legacy route keeps rollback_on_failure=True (#10461 correction 1). Replace the blind-write save_stale_processing_sweep_cursor with a transactional CAS advance_stale_processing_sweep_cursor. The cursor now carries a generation counter; a writer holding a stale generation is fenced out so a delayed scan on another pod cannot rewind progress. get cursor returns {resume_after_path, generation} dict (#10461 correction 2). Failure-Class: FC-split-mutation-authority
…urfaces LISTEN_FINALIZATION_ORPHAN_STALE_SECONDS was missing from the Cloud Run backend and backend-sync runtime manifests (both dev and prod) even though those services run main.py and therefore the stale-processing scheduler. Now declared with category: reliability on every scheduler surface; prod gke.backend-listen already had it (#10461 correction 3). Failure-Class: FC-split-mutation-authority
The from-segments admission guard adds +7 lines to developer.py (conditional guard with rollback_on_failure=False), growing it from 2195 to 2202 (#10461). Failure-Class: FC-split-mutation-authority
…ownership If lifecycle persistence loses to discard/terminal state, or the durable fanout claim loses, no canonical memory or derived side effect may happen. The finalizer previously called extract_memories before claim_finalization_fanout, so a losing finalizer still produced memory side effects. Restructure the flow: 1. Pass persistence_observer through process_conversation so the finalizer knows whether lifecycle persistence won. If it lost, return fenced before any side effect. 2. Move claim_finalization_fanout before extract_memories as the transactional ownership fence. The lifecycle transaction re-reads the durable conversation together with the job lease inside Firestore, so a discard or superseding generation cannot slip between the fence and memory extraction. Adversarial tests assert extract_memories is never called when the fanout claim loses or when persistence reports loss. Failure-Class: FC-split-mutation-authority
Deferred enrichment previously cleared the deferred flag via a plain update_conversation(deferred=False), then started the lease heartbeat in a background thread whose first renewal was 75-225s away. That left a window where the stale-processing sweep could terminalize the row between the clear and the first heartbeat; the stale processor could then persist derived side effects after ownership loss. Add reacquire_deferred_processing: a single Firestore transaction that clears deferred AND renews processing_admitted_at atomically. The immediate lease renewal makes the row look fresh to the sweep, eliminating the stale window. If the row is no longer processing or was discarded, the transition fails closed so no enrichment runs. Wire _enrich_deferred_conversation to use this atomic transition instead of the plain update. Behavioral tests verify reacquisition happens before processing and that failed reacquisition skips enrichment entirely. Failure-Class: FC-split-mutation-authority
The emulator concurrency tests previously skipped outside an explicitly provisioned emulator and were not invoked by any CI/package target. Their finalizer side used a test-only direct field-write helper that bypassed the production durable-finalization owner path. Three changes make the evidence executable and representative: 1. Replace the test-only _attach_finalization_job_txn with the production create_or_get_finalization_intent transaction (the real durable-finalization owner path). Race it against complete_orphan_conversation; assert exactly one valid outcome. 2. Add a deferred reacquire vs orphan sweep race using the production reacquire_deferred_processing. Assert reacquire always wins and the orphan is always fenced — no stale terminalization. 3. Chain the emulator tests into the listen-pusher gauntlet (run.sh) so they execute in the same provisioned Firestore emulator session as the gauntlet. A static CI wiring tripwire pins this so it cannot regress. All concurrent test threads handle Firestore contention exhaustion gracefully.
…ship is proven The durable finalizer previously fenced only memory extraction behind claim_finalization_fanout. process_conversation still emitted calendar, usage/app, vector, action/goal, audio artifact/enqueue, counter, and webhook work before the lifecycle/finalization ownership claim — so a finalizer that persisted the result then lost the claim still produced every derived side effect except memory. Restructure so the entire derived-effect bundle is deferred: 1. process_conversation gains defer_derived_effects + derived_effects_observer. When True, it persists the result, captures the whole post-persistence side-effect block as a runner closure, hands it back via the observer, and returns without emitting anything inline. 2. finalize_persisted_conversation switches from defer_memory_extraction to defer_derived_effects. It captures the runner, performs the transactional claim_finalization_fanout, and only after the claim wins runs the runner (calendar, usage/app, vector, action/goal, audio, webhook, memory). A losing claim is now a no-side-effect outcome. Already-completed replays (no runner) still re-extract memories behind the proven claim. The gauntlet's offline finalizer leaf records the new defer_derived_effects policy so the REST-finalization-restart scenario asserts the right field. Failure-Class: FC-split-mutation-authority
Two real-path adversarial tests prove the new defer_derived_effects contract: 1. test_deferred_derived_effects_emit_nothing_until_runner_invoked (real process_conversation): with defer_derived_effects=True and persistence winning, asserts ZERO calls on every side-effect dispatcher (submit, _trigger_apps, create_audio_files, update_conversation, extract_memories) inline, exactly one runner captured, then invoking the runner emits them. 2. test_finalizer_emits_zero_derived_effects_when_claim_loses_after_persistence: forces a post-persistence claim loss and asserts the derived-effect runner is never called and integration fanout never fires — a no-side-effect outcome. A companion test asserts the runner fires exactly once when the claim wins. Also updates the r4 test assertion from defer_memory_extraction to defer_derived_effects.
CI invokes run.sh as `... -- --state-dir "$RUNNER_TEMP/listen-pusher-stack"`. The previous loop appended every argument to the end of the combined runner_command string, so --state-dir leaked past the `&&` into the pytest invocation (which does not understand it) and never reached the testing.listen_pusher_stack.run module that owns it. Build runner_args first, then interpolate it into the listen-pusher runner command before the `&&` pytest split. A static CI wiring tripwire pins the runner_command line: runner_args lands on the runner side, never the pytest side. Failure-Class: FC-split-mutation-authority
…y setting LISTEN_FINALIZATION_ORPHAN_STALE_SECONDS is now a required reliability env on backend and backend-sync. The three synthetic Cloud Run state fixtures (with_cloud_run_oauth_secrets) did not include it, so the validator reported spurious missing-env errors and three tests regressed. Add with_listen_finalization_orphan_env and chain it into with_cloud_run_oauth_secrets so every synthetic state fixture carries the setting. All 72 validator tests pass. Failure-Class: FC-split-mutation-authority
…ated A legacy orphan whose stamp_processing_admission_if_absent CAS lost (row already stamped, status changed, or absent) was still counted as `migrated` because the return value was ignored. Only a successful stamp — the row was actually migrated to the fenced admission instant — is a migration; a CAS loss is an expected `skipped` fencing, distinct from `migrated` and `error`. Check the stamp return value and route accordingly. Regression test asserts a False stamp reports skipped, not migrated, and never terminalizes. Failure-Class: FC-split-mutation-authority
The concurrency race tests converted every exception to a False result via bare `except Exception`, which silently swallowed real failures (programming errors, emulator protocol breaks) as CAS losses. Only expected Firestore transaction contention (Aborted / FirestoreContentionExhausted) may be treated as a CAS loss; any other exception is a real failure that must surface. Replace the bare excepts with `except _CONTENTION` for the expected fencing path and a capturing `except Exception` that records the error. After the threads join, assert the captured error list is empty. Verified with two clean consecutive listen-pusher gauntlet runs (real Firestore emulator): every race test asserts stable one-winner invariants with zero unexpected failures. Failure-Class: FC-split-mutation-authority
…oute validator test_repo_prod_manifest_rejects_any_parakeet_first_route loads the full prod manifest and sits at ~0.13s CPU — just over the 0.12s fast-unit fail limit. It is unrelated to this diff and flaky under parallel pre-push load. Add it to the allowlist alongside the other full-manifest validator tests.
…eduler surfaces backend-integration deploys the backend image (uvicorn main:app) and so runs the stale-processing reconciliation scheduler registered in main.py startup, but its dev and prod Cloud Run runtime manifests lacked LISTEN_FINALIZATION_ORPHAN_STALE_SECONDS. It silently fell back to the code default, violating the source-controlled reliability-setting contract already applied to backend-listen, backend, and backend-sync. Now declared with category: reliability on both dev and prod backend-integration, completing scheduler runtime parity (#10461 final operational correction). Failure-Class: FC-split-mutation-authority
Pin that every main.py scheduler surface (gke backend-listen plus the Cloud Run backend, backend-sync, backend-sync-backfill, and backend-integration services, in dev and prod) declares LISTEN_FINALIZATION_ORPHAN_STALE_SECONDS with category: reliability. A surface that runs the stale-processing reconciler but omits the setting silently falls back to the code default; the parametrized test fails on the omission. It would have caught the backend-integration gap. Failure-Class: FC-split-mutation-authority
e6fdd6e to
045aa6d
Compare
The inline stale-processing scenario checked the legacy row immediately after the aged orphan completed, but the reconciler sweep cursor may not have reached the legacy row yet. Add a bounded wait for the admission stamp, mirroring the cloud_tasks scenario's tolerance for sweep latency.
|
Rebased onto latest All checks green: backend unit suite, hermetic E2E gauntlet, OpenAPI contract, static contracts. |
|
CI follow-up on exact head Root cause: the inline gauntlet waited for the aged orphan to complete, then immediately inspected a separate legacy row. Because the reconciler uses a bounded paginated sweep, completion of the first row does not prove the cursor has reached and migrated the legacy row. The harness now waits (bounded to 30s) for that row's required Verification:
PR remains open, non-draft, approved, mergeable, and current with |




What
Fixes #10461. Revised per review.
The legacy synchronous
POST /v1/conversationsroute admits a conversation toprocessingwith no durable job. A hard process crash (OOM/SIGKILL) between admission and completion strands the row: theprocessing_admission_guardonly rolls back on a raised exception, never on a hard crash, and the durable replay sweep (reconcile_listen_finalization_jobs) only covers rows that own a finalization job. The accepted recording never resolves and the client shows a stuck Processing card forever.This is the smallest backend safety-net reconciler for those stale bare-
processingorphans, now hardened against the four review gaps.How
A periodic + startup sweep,
reconcile_stale_processing_conversations, finds conversations that arestatus == processing, have nofinalization_job_id, are notdeferred, and drives each eligible orphan to exactly one terminal through the existing truthful terminal ownership CAS —lifecycle.complete()(claim_conversation_status(processing → completed)), which fences any already-completed/discarded/newer-generation row.1. Authoritative server-owned fence (no live-work terminalization)
Eligibility is bounded by
processing_admitted_at— the authoritative, server-owned admission instant — never caller-controlledcreated_at(which is the recording start time for from-segments/sync imports, not the admission instant).create_processing_conversationnow stamps the fence at every server/merge/import/developer admission (alongsideadmit_processing). A legacy row predating the fence is migrated by stamping it and deferred to a later sweep, never completed on first sight — so a live synchronous run under the conservative threshold can never be terminalized. Tests cover fresh-admission+old-creation (no act), old-admission+fresh-creation (the genuine orphan), and legacy-no-admission (migrate, not complete).2. No first-page starvation
The sweep is a single-equality
collection_group('conversations').where(status == 'processing')query. Because client-side exclusion (deferred / durable-job-owned / fresh / legacy) happens after the page cap, the sweep pages with astart_aftercursor so a stable first page of excluded rows cannot hide a later eligible orphan; total examined rows are bounded bymax_scan(default 2000). The saturation test seeds 120 excluded rows ahead of one eligible orphan and proves it is reached.3. Index, setting, and metrics
firestore-query-coverage --check-ratchet(exit 0, no new debt) and an unchangedfirestore.indexes.json. A unit-test tripwire pins the query to one equality with noorder_by.LISTEN_FINALIZATION_ORPHAN_STALE_SECONDS(default900) is clamped to a 300s floor and a one-day ceiling (code-defaulted, consistent with the sibling replay-window setting).LISTEN_FINALIZATION_STALE_PROCESSING_RECONCILIATIONS_TOTAL{outcome=completed|migrated|skipped|error}— zero-initialized, dashboarded, privacy-safe (aggregate counts only; no user identifiers in success logs).Why
complete()and not rollback+readmitRe-admitting the orphan to the durable worker would re-enrich it, but the synchronous request thread is not killed by the HTTP timeout (TimeoutMiddleware cancels the ASGI task, not the threadpool thread), so a slow-but-alive sync request could be rolled back and re-finalized concurrently, producing a duplicate integration delivery. Direct
complete()is provably race-free and is the same pattern the codebase already uses to avoid a stuckprocessingstate (the paywall path,_enrich_deferred_conversation's failure branch). Re-enrichment-quality recovery is an explicit non-goal of this issue and a separate follow-up.Non-goals (per issue)
No client migration to
/finalize, no endpoint redesign, no telemetry read-back follow-ups beyond the reconciliation counter, no new test framework.Verification (run locally)
make setup— linked-worktree hooks + pinnedbackend/.venvsynced.ENCRYPTION_SECRET=… backend/.venv/bin/python -m pytest tests/unit/test_conversation_finalization_jobs.py tests/unit/test_stale_processing_reconciliation.py tests/unit/test_conversation_lifecycle_contract.py tests/unit/test_check_conversation_lifecycle_writes.py tests/unit/test_integration_conversations_statuses_cap.py tests/unit/test_conversations_status_filter_cap.py tests/unit/test_listen_pusher_stack_ci_wiring.py tests/routers/test_conversations_processing_rollback.py tests/unit/test_conversation_search_date_validation.py tests/unit/test_journey_observability.py tests/unit/test_monitoring_alert_rule_contract.py tests/unit/test_developer_from_segments_idempotency.py tests/unit/test_merge_validation.py tests/unit/test_process_conversation_usage_context.py tests/unit/test_finalization_decision.py→ 175 passed.
npm run test:listen-pusher-stack:emulator→ gauntlet passed (~193s, all scenarios). Backend log confirms the cloud sweep{'completed': 2, 'migrated': 1, 'skipped': 0, 'error': 0}(aged orphan + saturation orphan completed; legacy migrated), the legacy row recovered after its fence aged, and the inline (non-Cloud-Tasks) sweep{'completed': 1, 'migrated': 1}. The scenario proves: timestamp authority/fallback; deferred exclusion (single + across the 120-row backlog); >100 excluded-row saturation with a later eligible orphan; periodic + non-Cloud-Tasks behavior; no durable job / worker / integration fanout for any outcome;GET /v1/conversations/{id}returns the terminal conversation; idempotent across restarts.make preflight→ 20/20 checks passed (firestore-query-coverage, conversation-lifecycle-write-guard, failure-class-protocol, backend-module-isolation, backend-import-purity all green; product-invariants: none required for these paths).Notes
GET /v1/conversationsis unchanged.Failure-Class: FC-split-mutation-authority