Skip to content

fix(backend): reconcile stale bare-processing conversations after crash - #10468

Merged
Git-on-my-level merged 23 commits into
mainfrom
fix/stale-processing-reconciler
Jul 25, 2026
Merged

Git-on-my-level merged 23 commits into
mainfrom
fix/stale-processing-reconciler

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Jul 24, 2026 •

Copy link
Copy Markdown
Member

What

Fixes #10461. Revised per review.

The legacy synchronous POST /v1/conversations route admits a conversation to processing with no durable job. A hard process crash (OOM/SIGKILL) between admission and completion strands the row: the processing_admission_guard only 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-processing orphans, now hardened against the four review gaps.

How

A periodic + startup sweep, reconcile_stale_processing_conversations, finds conversations that are status == processing, have no finalization_job_id, are not deferred, 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-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 (alongside admit_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 a start_after cursor so a stable first page of excluded rows cannot hide a later eligible orphan; total examined rows are bounded by max_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

  • Index: the single-equality collection-group query rides Firestore's automatic single-field index — no composite index, not collection-scoped. Proven by firestore-query-coverage --check-ratchet (exit 0, no new debt) and an unchanged firestore.indexes.json. A unit-test tripwire pins the query to one equality with no order_by.
  • Setting: LISTEN_FINALIZATION_ORPHAN_STALE_SECONDS (default 900) is clamped to a 300s floor and a one-day ceiling (code-defaulted, consistent with the sibling replay-window setting).
  • Metrics: outcomes surface on 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+readmit

Re-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 stuck processing state (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 + pinned backend/.venv synced.
  • Focused unit tests (all changed surfaces):
    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.
  • Hermetic listen-pusher gauntlet (real Firestore emulator, strict loopback Cloud Tasks): 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

  • The sweep runs in every deployment mode (it needs no Cloud Tasks dispatch), so legacy-sync-route orphans in inline deployments are also recovered.
  • Behavior is bounded to the authoritative backend lifecycle owner; no client-contract change. GET /v1/conversations is unchanged.
  • Pre-existing, unrelated backend unit-suite failures (langchain import-isolation / proto-plus descriptor conflicts under full-collection in the local venv) are outside this diff and not addressed per the review. The authoritative hermetic gauntlet and the diff-scoped preflight are green.

Failure-Class: FC-split-mutation-authority

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Found one net-new security issue in the current diff after deduplicating module outputs.

Open in Web View Automation 

Sent by Cursor Security Agent: Security Reviewer


def final_attempt_failed(
job_id: str, dispatch_generation: int, lease_epoch: int, retry_count: int, *, firestore_client: Any = None
) -> bool:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Fix in Cursor Fix in Web

Reviewed by Cursor Security Reviewer for commit 7b6b00c. Configure here.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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".

@Git-on-my-level

Copy link
Copy Markdown
Member Author

Request changes — safety and eventual-recovery gaps

This must not merge in its current form.

  1. Live work can be terminalized. The sweep treats a job-less processing row as orphan from processing_admitted_at or created_at, then calls an unconditional processing → completed CAS. create_processing_conversation / server- and merge-originated flows do not universally stamp a server-owned admission marker; some accept caller historical created_at. A periodic run can therefore complete active processing. Recovery must require a durable, server-owned orphan/ownership fence that cannot overlap live work, with tests for fresh admission+old creation, old admission+fresh creation, and legacy no-admission behavior.

  2. Eligible orphans can starve forever. The collection-group query applies limit(100) before local filtering. A stable first page of fresh, deferred, or durable-job-owned rows can indefinitely hide later eligible orphans. Make eligibility/query progression durable and exhaustive (pagination/cursor or an authoritative queryable marker) and prove saturation with >100 excluded rows plus a later eligible orphan.

  3. Index and operational contract are incomplete. Register/deploy the required collection-group index rather than relying on a collection-scoped entry; classify and safely bound the recovery setting; emit alertable reconciliation outcomes/errors consistent with the existing durable reconciler.

  4. Strengthen the end-to-end regression. Cover deferred rows, timestamp authority/fallback, periodic and non-Cloud-Tasks mode, and all worker/fanout outcomes (not only successful ones).

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.

@Git-on-my-level

Copy link
Copy Markdown
Member Author

Revised per the request-changes. Commits 54ef496 (fix) + 1aa7cc8 (tests) push to this branch; not marked ready.

  1. Authority fence (no live-work terminalization). Eligibility is now bounded by the server-owned processing_admitted_at stamp only — never caller-controlled created_at. create_processing_conversation stamps it at every server/merge/import/developer admission; a legacy row predating the fence is migrated (stamped) and deferred to a later sweep rather than completed on first sight. Unit tests cover fresh-admit+old-create (no act), old-admit+fresh-create (the orphan), and legacy-no-admit (migrate). complete()'s CAS still fences any already-terminal/superseded row.
  2. No first-page starvation. The single-equality collection_group(status==processing) query pages with a start_after cursor so a stable first page of excluded rows (deferred/durable/fresh/legacy) cannot hide a later orphan; examined rows bounded by max_scan. The gauntlet seeds 120 excluded rows ahead of one eligible orphan and proves it is reached.
  3. Index / setting / metrics. Single-equality collection-group query rides Firestore's automatic single-field index — firestore-query-coverage --check-ratchet exits 0 with no new debt and firestore.indexes.json is unchanged (tripwire test pins the shape). LISTEN_FINALIZATION_ORPHAN_STALE_SECONDS is clamped to [300s, 1 day]. Outcomes surface on LISTEN_FINALIZATION_STALE_PROCESSING_RECONCILIATIONS_TOTAL{outcome=completed|migrated|skipped|error} (zero-init, dashboarded, privacy-safe).
  4. End-to-end regression. The gauntlet now covers timestamp authority/fallback (legacy two-phase), deferred exclusion, >100-row saturation + later orphan, periodic + non-Cloud-Tasks (inline) behavior, and no worker/fanout for any outcome.

Verification: 175 focused unit tests pass; hermetic listen-pusher gauntlet passes (~193s, real Firestore emulator); make preflight 20/20. Pre-existing langchain/proto import-isolation failures under full local collection are unrelated to this diff and left untouched per the review.

@Git-on-my-level

Copy link
Copy Markdown
Member Author

Request changes — stale-processing recovery remains unsafe

This revision improves coverage but cannot merge yet.

  1. Permanent starvation remains. Each periodic invocation restarts at the first collection-group page and stops after max_scan=2000. A stable excluded prefix larger than that means later eligible orphans are never reached. Persist/rotate a sweep cursor (including safe wraparound) or make eligibility server-queryable; bounded work must still guarantee eventual reachability. Replace the test that expects beyond-bound absence with a repeated-sweep regression that proves eventual recovery.

  2. Terminalization remains unsafe. Candidate discovery is non-transactional, but completion only checks status=processing. A finalizer can attach a durable job after the scan read and before completion, allowing the sweep to mark active durable work completed. Additionally, processing_admitted_at is an age timestamp—not active-work ownership/lease—and a legitimate synchronous processor can exceed the 300–900s threshold. Introduce a server-owned generation/lease/heartbeat or equivalent transactional ownership fence. Reconciliation must claim exactly the scanned orphan generation, and active processors/finalizers must not be terminalizable by the sweep.

  3. Finish the operational contract. Add the setting to authoritative backend/deploy/runtime_env.yaml for applicable backend roles with reliability classification; behaviorally exercise periodic scheduling (not only startup); count per-row exceptions as error, distinct from expected CAS skipped fencing.

  4. CI integration note. Current OpenAPI/metadata-preflight failures are base-integration drift (the live base is not an ancestor of this branch), not this patch. Do not absorb unrelated API/policy repairs, but rebase/revalidate the existing branch after the substantive fixes so merge-result checks are real.

No new issue/PR/ticket is authorized. Revise this existing PR only.

@Git-on-my-level
Git-on-my-level force-pushed the fix/stale-processing-reconciler branch from 1aa7cc8 to 30a9863 Compare July 24, 2026 09:01
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Revision 2 pushed (commits f6a990b + 30a9863, rebased onto main 7be007f). Not marked ready.

  1. Eventual discovery: persisted, rotated sweep cursor resumes a bounded window each sweep and wraps to the top on exhaustion — a stable excluded prefix larger than any per-invocation max_scan cannot permanently hide a later orphan. Repeat-sweep regression (2500 excluded rows + 1 orphan, max_scan=1000) proves the orphan is reached on the 3rd sweep.
  2. Ownership fence: transactional complete_orphan_conversation verifies exact scanned generation + no finalization_job_id + non-deferred/non-terminal immediately before terminalization; a lease heartbeat (renew_processing_lease in processing_admission_guard) keeps a live processor fresh so it is never terminalized. Race regressions cover finalizer-claimed, lease-renewed, deferred/terminal rows.
  3. Ops: LISTEN_FINALIZATION_ORPHAN_STALE_SECONDS declared in runtime_env.yaml (dev+prod backend-listen, category reliability) + chart values + deployment-secret-boundary policy; periodic scheduling behaviorally tested; unexpected per-row exceptions counted as error distinct from CAS skipped.
  4. Index: single-equality collection-group query rides the automatic single-field index — firestore-query-coverage --check-ratchet exits 0, no composite index.
  5. Rebase/drift: rebased onto main; OpenAPI compatibility passes (zero API surface changed). The committed app-client-openapi.json is stale on main itself (836778a memory-baseline endpoint) — unrelated base drift, not absorbed per the review.

Verification: focused unit tests pass; hermetic listen-pusher gauntlet passes (~187s, re-run post-rebase); make preflight 21/21; runtime_env dev+prod pass.

Failure-Class: FC-split-mutation-authority

@Git-on-my-level

Copy link
Copy Markdown
Member Author

Third request changes — recovery is still unsafe across production paths/pods

Independent review found remaining correctness blockers. Keep work in this existing PR only.

  1. Guard every live bare-processing producer. processing_admission_guard currently protects only the legacy conversation route. From-segments, merge, and deferred-enrichment paths can run live process_conversation without heartbeat/fencing, then become sweep-eligible after the age threshold. Apply a common server-owned processing lease/generation guard to every such producer, and ensure a falsely completed row cannot persist derived side effects afterward. Add behavioral tests through the actual routes/paths, not direct context-manager tests.

  2. Make persisted cursor advancement multi-pod safe. Multiple backend-listen pods run startup and periodic reconciliation. Cursor read/update currently has no generation/CAS/lease, so delayed scans can rewind progress and reintroduce starvation. Add transactional CAS or shared sweep leadership/lease with wraparound, and a real emulator contention test with competing sweep writers.

  3. Complete deployment surfaces. The recovery setting is missing from production Cloud Run backend and backend-sync runtime manifests, even though those services run the scheduler. Declare/classify it there too (or make scheduling impossible on roles where it is absent, with tests).

  4. Strengthen finalizer-vs-orphan race proof. Add an emulator contention test that concurrently executes durable-job attachment and orphan terminalization, proving exactly one transaction commits and no active work is falsely completed.

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.

@Git-on-my-level

Copy link
Copy Markdown
Member Author

Fourth request changes — two ownership-loss paths remain unsafe

The operating/configuration audit is now clean, but independent lifecycle review found two merge blockers:

  1. Durable finalizer memory writes occur before lifecycle ownership is proven. finalizer.py processes, then calls extract_memories, and only later performs claim_finalization_fanout. If lifecycle persistence lost to discard/terminal state, the finalizer still produces memory side effects. Pass/observe persistence ownership through the real finalizer path, fence before any canonical side effect, and add a regression that asserts extract_memories is never called when persistence/claim loses.

  2. Deferred enrichment has a stale window. It clears deferred before atomically reacquiring its processing generation/lease, while guard renewal waits up to the first heartbeat. An aged deferred row can be orphan-completed in that interval; the stale processor can then persist/side-effect after ownership loss. Make deferred-clear + ownership reacquisition an atomic guarded transition with immediate renewal/ownership confirmation, and make stale processors fail closed. Add an adversarial race regression.

  3. Make concurrency evidence executable. The new emulator race tests currently skip outside an explicitly provisioned emulator and are not invoked by any CI/package target; their finalizer side bypasses the production finalizer/request path. Add a deterministic emulator invocation wired into the relevant test/gauntlet path and race the real durable-finalization owner path against orphan completion.

Keep this one existing PR only. Do not repair baseline OpenAPI, CI bootstrap dependencies, or unrelated work.

@Git-on-my-level

Copy link
Copy Markdown
Member Author

Fifth request changes — fence all finalizer side effects and repair executable checks

Independent review found the durable finalizer fence still occurs after process_conversation has emitted calendar, usage/app, vector, action/goal, audio, counter, and webhook work. Deferring memory extraction alone is insufficient.

Required changes on this existing PR only:

  1. Fence the whole derived-side-effect bundle. Durable finalization must persist its conversation result, transactionally claim lifecycle/finalization ownership, then and only then emit every derived side effect (not just memory extraction). If persistence or claim loses, emit none. Add an adversarial real-path regression that forces a post-persistence claim loss and asserts zero calendar/app/vector/action/goal/audio/webhook dispatches.

  2. Repair gauntlet argument routing. CI’s documented --state-dir must be passed only to the listen-pusher runner, not appended to pytest after &&; reproduce the exact CI command.

  3. Update runtime-validator fixtures. The synthetic Cloud Run manifests must include the new setting; restore the 3 failing validator tests.

  4. Correct metric semantics. A failed legacy admission-stamp CAS must report skipped, not migrated; add the regression.

  5. Remove emulator race flakiness. Do not convert all Firestore exceptions to false. Synchronize/retry only expected contention, surface unexpected failures, and prove the executable gauntlet succeeds repeatedly.

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.

@Git-on-my-level

Copy link
Copy Markdown
Member Author

Final operational request change — complete scheduler runtime parity

The lifecycle/side-effect review is now clean. One operational configuration defect remains:

backend-integration runs the same uvicorn main:app scheduler but lacks LISTEN_FINALIZATION_ORPHAN_STALE_SECONDS in both dev and prod runtime manifests. It silently falls back to the code default, violating the source-controlled reliability-setting contract already applied to the other scheduler surfaces.

Add the classified setting to dev/prod backend-integration manifests (and any inherited/rendered contract fixture required by the repository), update validation coverage, and rerun the runtime manifest checks. Keep this existing PR only; do not repair unrelated OpenAPI or CI-bootstrap baseline failures.

@Git-on-my-level
Git-on-my-level force-pushed the fix/stale-processing-reconciler branch from 4a81c81 to d6e3a2d Compare July 24, 2026 12:21
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Resolved the two Codex P2 review threads — both were isOutdated against the current head (d6e3a2d), referencing early commit 7b6b00ccfa before the three revision rounds:

  • Admission age (r3643146303): the current get_stale_processing_orphan_candidates does not fall back to created_at. A bare-processing row missing processing_admitted_at is returned as legacy=True and migrated (stamped, deferred), never completed on first sight (test_legacy_orphan_is_migrated_not_completed).
  • First-page starvation (r3643146308): the sweep pages with a start_after cursor inside each invocation and a persisted/rotated cross-invocation sweep cursor with wraparound, so a stable excluded prefix cannot hide a later orphan. Saturation test seeds 120 excluded rows ahead of one eligible orphan and proves it is reached.

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 langchain_core/google modules, stale generated OpenAPI/Swift artifacts) also failing on main; none touch files in this diff.

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

fix(backend) reconcile stale bare-processing conversations — approve only (2867 lines, exceeds scope ceiling)

@Git-on-my-level
Git-on-my-level force-pushed the fix/stale-processing-reconciler branch from d6e3a2d to e6fdd6e Compare July 24, 2026 17:43
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Rebased onto latest main (9c295ff) — the branch was 18 commits behind. PR tests pass locally on the rebased head (e6fdd6ec); all 5 PR-scoped unit suites green via BACKEND_UNIT_TEST_FILE_LIST=… bash test.sh.

The three red checks remain pre-existing base failures (identical on latest main):

  • Backend unit suite — stale generated Swift/TS artifacts + missing langchain_core module; none of the 7 failing files are in this diff
  • Public Developer API contract — app-client-openapi.json stale from base-level pydantic/schema drift
  • Static Contracts — ModuleNotFoundError: No module named 'google' in conftest

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
@Git-on-my-level
Git-on-my-level force-pushed the fix/stale-processing-reconciler branch from e6fdd6e to 045aa6d Compare July 24, 2026 23:01
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.
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Rebased onto latest main to resolve stale-branch CI failures (langchain_core.messages import error from missing test stub). Also fixed a timing race in the inline stale-processing gauntlet scenario: the legacy-row migration assertion now waits for the admission stamp with the same bounded poll used for the aged orphan, matching the cloud_tasks scenario's tolerance for sweep-cursor pagination latency.

All checks green: backend unit suite, hermetic E2E gauntlet, OpenAPI contract, static contracts.

@Git-on-my-level

Copy link
Copy Markdown
Member Author

CI follow-up on exact head 96ece8100bf50ef7efe69f944fce8a7103aefb67:

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 processing_admitted_at migration stamp before retaining the same lifecycle assertions; production behavior and fencing are unchanged.

Verification:

  • npm run test:listen-pusher-stack:emulator -- --state-dir <isolated-dir> — passed; appended emulator concurrency suite: 4 passed.
  • Focused stale-processing/finalization/lifecycle contracts — 69 passed.
  • make preflight — 23/23 selected checks passed.
  • GitHub exact-head checks are green, including Listen Pusher Stack Gauntlet, Backend Hermetic Merge Gate, Backend unit suite, OpenAPI, and Static Contracts.

PR remains open, non-draft, approved, mergeable, and current with main at f2bdbf42175d10a7f37419ac7f991e664828b752. No merge or deployment was performed.

@Git-on-my-level
Git-on-my-level merged commit c78baea into main Jul 25, 2026
39 of 41 checks passed
@Git-on-my-level
Git-on-my-level deleted the fix/stale-processing-reconciler branch July 25, 2026 00:42
undivisible pushed a commit to undivisible/omi that referenced this pull request Sep 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(backend): reconcile stale bare-processing conversations after crash

2 participants