Skip to content

fix(backend): retire quiet checks when conversation owners close - #23527

Merged
Git-on-my-level merged 13 commits into
mainfrom
lane/quiet-check-inflow
Oct 24, 2026
Merged

Git-on-my-level merged 13 commits into
mainfrom
lane/quiet-check-inflow

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

Summary

Quiet checks were armed at listen setup/reconnect/teardown, but sync-merge donor tombstones, smart merges, deletion and ordinary finalization writers did not retire them. They stayed waiting_quiet until replay rediscovered that their owner was gone or terminal. Reconnect reuse already has one deterministic job per conversation; it is not one new row per socket event.

  • Retire checks immediately after each relevant lifecycle commit through shared retirement code that rechecks the current job and conversation transactionally. A concurrent live reopen keeps its successor; delivered workers retain their generation fence. Refused donor/terminal arms also retire old debt. Post-commit cleanup failures emit shared fallback telemetry and leave replay debt; they cannot invalidate successful processing admission, terminal transitions or erasure.
  • Cover dead-letter/BYOK closure, meeting receipt binding, bulk-merge admission/rollback and recursive account erasure, including debt attached to older jobs. Account erasure uses one registered bounded UID-only query on the existing single-field index.
  • Restore an existing quiet obligation atomically when synchronous processing rolls back to an eligible live owner. A new generation fences old deliveries; the immediate due index resumes independent recovery without inventing new quiet rows.
  • Preserve the quiet-stop public API with an explicit re-export. Keep isolated fixture setup outside the existing endpoint-call CPU budget, with unchanged assertions and thresholds; model SDK field deletion for BYOK claim idempotency.
  • Own bounded replay leaves in the executor registry, including metrics and shutdown. Keep the DB coordinator separate, preserve context, join all owned futures, and limit outstanding submissions to the configured concurrency.
  • Clear terminal non-quiet/BYOK due indexes instead of renewing no-op debt. Document adaptive replay controls, observation, drain estimates and rollback.

Expected inflow change

For the observed mix (~495–498 dead-owner retirements per 500 replay rows), this should eliminate nearly all new dead-owner overdue obligations from the covered paths after rollout, roughly 99% of the sampled avoidable inflow if that mix persists. It does not remove the existing ~134k backlog or reduce legitimate first arms. This estimate is conditional, not a live acceptance measurement.

Current main has replay outcome counters but no arm counter. Add listen_quiet_check_arm_total with committed created, rearmed, reused, refused outcomes. The deterministic test expects and observes 1 created + 4 reused from five calls, one waiting row; terminal/donor arms are refused and leave zero waiting rows. The runbook separates these from replay retirement and actual per-window lifecycle rates. No production arm-rate measurement is claimed.

Product invariants

No path-mandated invariant citations were selected by scripts/pr-preflight --suggest. Preserve recording-lease, content, account, BYOK, revision and processing/fanout admission fences. Retiring a wake changes no conversation content, capture data or merge ownership. Live reopened owners retain quiet recovery. No language-gate, firmware, production configuration, production data or backfill change is included.

Validation

  • Scoped backend validation includes 46 selected files covering lifecycle/replay, Firestore contracts, nullable retrieval inputs, product-tool fail-soft behavior and Wrapped null handling. Canonical backend runner: cd backend && BACKEND_UNIT_TEST_FILE_LIST=<selected-file-list> nice -n 10 bash test.sh, through omi-heavy; lifecycle, sync/smart-merge, executor/replay and Firestore guard coverage.
  • Canonical hermetic backend E2E under the unchanged 120-second budget, with strict quiet-custody transactions and wire assertions that admitted finalization leaves no waiting quiet row. Read/write failure injection proves committed processing admission survives deferred cleanup and the same indexed debt can later retire.
  • Real isolated Firestore emulator: firebase emulators:exec --only firestore --project demo-quiet-retirement "backend/.venv/bin/python backend/scripts/quiet_finalization_replay_emulator_test.py". User/empty deletion, capture_end, completion/discard/failure, processed persistence/upsert, live reopen, orphan/deferred/noise/actual near-1MiB fallback, dead-letter/BYOK/meeting closure, recursive account erasure with multipage cursor, and SDK index deletion; existing cursor/starvation/crash cases retained.
  • Full pinned backend typecheck, scripts/pr-preflight --pr-body-file <body> and repository push gates; GitHub CI required before handoff.

Scope and rollback

Focused on owner retirement and the deferred replay-pool/runbook P1s. #23506 owns episode lifecycle reconciliation; this adds no episode policy or new index. Throughput rollback remains limit 100 / concurrency 1. Revert this PR to roll back the source change; existing replay remains the recovery backstop. No merge/deploy is performed by this lane.

Failure-Class: new

Line-Count-Exception: backend/database/conversations.py | 4458 -> 4473 | Wire shared retirement after existing lifecycle commits; broader persistence extraction would expand this focused incident fix.
Line-Count-Exception: backend/database/conversation_finalization_jobs.py | 2949 -> 2976 | Retire quiet ownership after admission and terminal fallback, and clear terminal replay indexes without changing admission semantics.

🤖 Generated with Claude Code

Git-on-my-level and others added 6 commits October 24, 2026 22:35
Retire merged, deleted and non-live conversation checks with a shared owner fence; register bounded replay workers and document recovery controls. Clear terminal replay indexes instead of renewing no-op debt.

Failure-Class: new

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Exercise actual near-ceiling, orphan, deferred and noise-close commits in the isolated Firestore emulator. Re-review the smart-merge query coverage digest for its post-commit document-only retirement.

Failure-Class: new

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Close remaining indirect terminal paths and recursive account deletion through the same latest-owner fence. Register the bounded UID-only erasure scan and exercise terminal, merge rollback and multipage erasure behavior.

Failure-Class: new

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Make the moved quiet-stop API an explicit export. Align nullable/coercible retrieval inputs with their existing runtime behavior, retain product-query validation without a redundant check, and preserve nullable Wrapped segment handling through the positive-duration filter. These five unchanged-main diagnostics blocked the mandatory full backend type gate.

Failure-Class: new

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Keep the existing coercion behavior while separating the normalized string from the object input for the required type gate.

Failure-Class: new

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Register the lightweight model-text and result-bound modules inside existing import-isolation scopes so dataclass annotation resolution works while network and heavy parent packages remain stubbed.

Failure-Class: new

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 24, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-24T19:20:48.661479Z 58624f1 New commits
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@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: 40783dea01

ℹ️ 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".

Comment on lines +2758 to +2759
if claimed_status != ConversationStatus.in_progress:
stop_quiet_check_for_conversation(uid, conversation_id, firestore_client=db)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Isolate quiet-check cleanup failures from committed admission

If the new retirement read or transaction fails after the status CAS commits, this function raises even though the conversation is already processing. The synchronous finalize path in backend/routers/conversations.py calls admit_processing before entering processing_admission_guard, so this failure skips both the processor and its rollback. Subsequent requests see an already-processing conversation, and the orphan sweep eventually completes it without running summarization. This also affects conversations without quiet checks because retirement always performs an initial Firestore read. Keep cleanup failures from invalidating a successful admission, relying on the existing quiet-check replay backstop or another retry mechanism for retirement.

Useful? React with 👍 / 👎.

Git-on-my-level and others added 3 commits October 25, 2026 00:38
Apply the strict hermetic transaction facade to quiet arm and post-admission retirement reducers. Assert finalization wire requests leave the prior quiet obligation retired and unindexed without weakening reconnect identity or terminal-response checks.

Failure-Class: new

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Keep post-commit retirement failures from invalidating processing admission, terminal transitions or erasure. Log deferred cleanup and retain the indexed replay backstop. Inject read and write failures to prove admission success and subsequent quiet-debt repair.

Failure-Class: new

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Model actual due-field deletion for repeated BYOK claims, keep account-erasure outbox cleanup as an explicit collaborator in the tombstone unit seam, and construct isolated payment routers in fixture setup so the existing call CPU guard measures endpoint behavior. Preserve all assertions, thresholds and required suites.

Failure-Class: new

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@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: d88674c08d

ℹ️ 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".

Comment on lines 2757 to +2758
if claimed:
if claimed_status != ConversationStatus.in_progress:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Restore the quiet obligation when processing admission rolls back

When synchronous finalization fails, processing_admission_guard calls rollback_processing_admission, which returns the conversation to in_progress through this same status helper. The new admission cleanup has already marked its quiet check quiet_done and removed reconcile_after_at, but the rollback does not rearm it. Previously scheduled deliveries cannot restore that retired obligation, so a transient processing failure now loses quiet-check recovery and must wait for the slower fallback scan or another client interaction. Rearm the check on a successful processing-to-in-progress rollback, or defer retirement until processing has a durable successor.

Useful? React with 👍 / 👎.

Comment on lines +78 to +82
except Exception:
# Cleanup must not invalidate an already-committed owner transition.
# Keep the durable index for the independent quiet replay backstop.
logger.exception('event=quiet_check_retirement outcome=deferred operation=stop_quiet_check_for_conversation')
return False

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Record deferred cleanup through the shared fallback telemetry

When Firestore cleanup fails, this new fail-open branch continues the committed operation and delegates retirement to replay, but emits only an exception log. The equivalent job/account handlers do the same, leaving these degraded outcomes absent from the shared fallback metrics. backend/AGENTS.md explicitly requires new fallbacks to call utils.observability.fallback.record_fallback; instrument these deferred-retirement paths with that helper while preserving their non-throwing behavior.

AGENTS.md reference: backend/AGENTS.md:L316-L316

Useful? React with 👍 / 👎.

Git-on-my-level and others added 2 commits October 25, 2026 01:29
Use the boundary-helper fixes now landed in main through #23512 so this focused quiet-lifecycle PR no longer carries competing versions of those files. Preserve published history with a normal follow-up commit.

Failure-Class: new

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Restore an existing quiet obligation atomically with the successful processing-to-live CAS, with a new generation and immediate due index. Publish deferred cleanup through shared fallback telemetry without invalidating committed owner results. Guard restoration, stale deliveries, dependency failures and telemetry failures in unit and real Firestore tests.

Failure-Class: new

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@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: 58624f1841

ℹ️ 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".


def _record_deferred_retirement(operation: str) -> None:
try:
from utils.observability.fallback import record_fallback

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Move the fallback telemetry import to module scope

The new deferred-retirement handler imports record_fallback inside the function, contrary to the explicit backend rule, “All imports at module top level — never inside functions.” Move this import to module scope while retaining the exception guard around telemetry emission so telemetry failures still cannot invalidate committed lifecycle operations.

AGENTS.md reference: backend/AGENTS.md:L163-L163

Useful? React with 👍 / 👎.

Git-on-my-level and others added 2 commits October 25, 2026 02:26
Keep telemetry failures isolated while complying with the backend import contract. Patch the resolved callable in the failure-injection guard.

Failure-Class: new

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Apply the same backend import rule to the shared fallback counter assertion.

Failure-Class: new

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Git-on-my-level
Git-on-my-level merged commit ef676fe into main Oct 24, 2026
64 of 66 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/quiet-check-inflow branch October 24, 2026 20:03
Git-on-my-level added a commit that referenced this pull request Oct 24, 2026
#23527 landed a parallel guard fix for this file on main (per-test
payment_router fixture calling the old _load_payment_router in fixture
setup). Keep its public shape -- tests take a payment_router fixture and
alias it locally -- but back it with this lane's module-scoped fixture:
one import per file instead of one per test, shared-mock call-state reset
between tests, unconditional stub replacement (no real-module attribute
mutation in batched sessions), and utils.stripe/utils.subscription parent
pinning. Drops main's now-dead per-test fixture. Allowlist entries for
this file stay removed.
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.

1 participant