Repository navigation
fix(backend): preserve episode speech liveness and closed recaps - #23506
Conversation
…sing Failure-Class: FC-high-water-cursor-skips-unready-row Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Preview deployment for your docs. Learn more about Mintlify Previews.
💡 Tip: Enable Automations to automatically generate PRs for you. |
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. |
## Summary Quiet replay clamps the oldest due page to 100, runs checks serially, and counts every non-exception return as `requeued`. A non-advancing prefix can hide later work; retirement looks like dispatch success, and 100/min cannot drain a queue receiving roughly 110 overdue obligations/min. Evaluate quiet pages with at most 16 independent leaf workers, preserving FSR/request context and joining all work before releasing the pass. Rotate a persisted CAS-fenced timestamp/document-ID cursor with a fixed cutoff per sweep (so recurring successors cannot prevent wrapping after a crash), reserve bounded successor wakes for overdue stale/error checks, retire missing conversations with an updated timestamp, and back off unchanged snapshots without overwriting newer work. Report `requeued`, `advanced`, `retired`, `stale`, `no_progress`, and `error` separately, plus oldest-overdue-age telemetry and effective database page logs without identities. `LISTEN_FINALIZATION_RECONCILE_LIMIT` overrides a backlog-aware default (100 normally, 500 once oldest overdue reaches five minutes), capped at 2000. `LISTEN_QUIET_REPLAY_CONCURRENCY` defaults to 16 and clamps to 1..16; set it to 1 for serial rollback. The existing interval knob is unchanged. Recording-lease, account, BYOK, and admission semantics stay authoritative. The live missing-conversation sample retired on the current release; no generation type mismatch was reproduced. This PR repairs the proven discovery/throughput/accounting defects and guards stale paths. Arm-amplification telemetry is a separate lead-owned follow-up. Failure-Class: FC-bounded-discovery-pinned-by-blocked-page Line-Count-Exception: backend/database/conversation_finalization_jobs.py | 2856 -> 2949 | Keep the incident replay cursor, CAS backoff and oldest-overdue query beside existing replay ownership; avoid an unrelated module migration during recovery. ## Product invariants affected none. Existing recovery admission, recording lease, account cutover, BYOK, and finalization generation fences remain authoritative. ## Validation Exact head `6b317890e99c8dbb247035f7d4c3aa7bc1ed81bc` passed the real Firestore emulator (101-row starvation, deleted cursor, wrap, missing-conversation retirement and crash/recurrence bounded sweep), all 14 selected files through canonical backend/test.sh under nice10 (964 passed, one deselected), all 33 repository preflight checks, metadata validation and the full pre-push hook. Both previously failing GitHub guard files are in that selected suite; no exemptions or baseline changes. GitHub CI is tracked separately and must complete on this head. ## Review scope The incident instruction explicitly limits this lane to quiet-check/replay files while the broader episode-lifecycle lane owns adjacent work. The per-pass leaf pool is bounded, propagates context, and joins all futures before the callback exits; it deliberately avoids children on the occupied shared DB pool. Shared executor registry health visibility and the lifecycle reference update are outstanding supporting-file review findings outside that boundary. A request to allow those two narrow edits is pending; no scope expansion or review resolution is implied by CI success. Read-only `git merge-tree` against the broader [PR23506](#23506) at `a92f93b2e11c257fc3488b515182e7cf04b0320b` confirms four content conflicts in the quiet evaluator, worker, replay service and query driver. The lead must reconcile that overlapping quiet-query/index design before combining the PRs. This PR itself requires no new index. No branch or worktree was merged during this check. ## Operator notes Lead and David own production changes; none were performed by this lane. The local incident handoff includes an unexecuted exact-page CAS mitigation proposal. Start a temporary drain at `LISTEN_FINALIZATION_RECONCILE_LIMIT=500` and `LISTEN_FINALIZATION_RECONCILE_INTERVAL_SECONDS=30`, with concurrency16. Expand to 1000/15 only while Firestore latency/errors and downstream processing pressure stay clean. The interval also affects other serial recovery sweeps and singleton lease cadence. At 110/min inflow, ideal coverage lower bounds for the 126,473-row snapshot are ~5h25m at 500/60, ~2h23m at 500/30, and ~33m at 1000/15, plus pass duration and other sweeps. At 100/60 the queue never drains; the no-arrival estimate alone is ~21h05m. Remove temporary overrides after oldest age/backlog recovery; adaptive selection returns to100 for a fresh queue. Rollback knobs are limit100/concurrency1, with the acknowledged throughput shortfall. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
Keep #23500 as the single quiet replay authority, including cursor, concurrency, progress repair, backoff and counters. Drop the redundant quiet due query and index while preserving episode segment identities, speech liveness and closed recap recovery. Failure-Class: FC-high-water-cursor-skips-unready-row Co-Authored-By: Claude Opus 5.5 <[email protected]>
Carry the reviewed main-integration prerequisite from bfd7dfe. Main's defensive retrieval and wrapped guards currently contradict their annotations and fail the mandatory whole-backend pyright gate. Preserve runtime behavior and all guards while aligning their declared types; episode behavior and quiet replay/arming remain unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Carry fallback module registration from 8037f2f so the real isolated retrieval suites can import dataclasses correctly. Preserve the existing test isolation and assertions. Carry the three payment CPU classifications from 39133dc; upstream CI run 40116299270 independently measured 1.37-1.73s for these subscription/Stripe cases. No global timing limit or test execution is disabled. These inherited main failures otherwise prevent exact-head CI from turning green. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Keep incoming main's canonical retrieval/wrapped typing, fallback registration and test duration classifications. Preserve the episode lifecycle work and #23500's single quiet replay authority; no custom arming or quiet query/index additions. Co-Authored-By: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 2af9fb2af1
ℹ️ 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".
| if episode and conversation_id in (episode.get('conversation_ids') or []): | ||
| # Refresh before the lazy idle-close check, including short speech batches. | ||
| _retain_activity(uid, episode, conversation_id, started_at, c) | ||
| return 'attached' |
There was a problem hiding this comment.
Preserve idle boundaries before refreshing resumed speech
If a conversation remains in progress through more than CLOSE_GAP_SECONDS of silence and no live read closes its episode during that interval, the next speech batch now refreshes last_activity_at and returns before checking the idle boundary. _record_moment_once likewise refreshes activity before its idle check, so subsequent notes continue the old occasion instead of closing it after the 30-minute gap. This makes episode grouping depend on whether the app polled during the silence. Distinguish ongoing speech from speech resuming after an already-expired gap before advancing the clock.
Useful? React with 👍 / 👎.
| consumption_owner = episode | ||
| if not episode or moment.conversation_id not in (episode.get('conversation_ids') or []): | ||
| consumption_owner = episodes_db.get_episode_for_conversation( | ||
| uid, moment.conversation_id, firestore_client=c.firestore_client | ||
| ) | ||
| consumed = set(((consumption_owner or {}).get('applied_segment_ids') or {}).get(moment.conversation_id) or []) |
There was a problem hiding this comment.
Carry consumed IDs when attaching to a newer live episode
If episode A consumed unplaced segments from c1, A closes idle, and another conversation opens episode B, resumed c1 speech can join B through _attach_once. That attachment copies neither applied_segment_ids nor the previous consumption receipts and rewrites the conversation link to B. This lookup then sees c1 already in B and reads an empty consumed-ID set, so the full transcript supplied by _on_finalized feeds A's previously consumed speech into B again. Carry the receipts when an existing conversation joins a newer episode, before overwriting its owner link; the episode is None carry-forward path does not cover this case.
Useful? React with 👍 / 👎.
… the live-poll recap (#23544) * fix(backend): bound episode receipts out of the episode doc and cache the live-poll recap Follow-up to #23506 (b72ddce): consumed unplaced-segment ids lived in the episode Firestore document, one id per consumed segment with no limit, so a very long unplaced conversation grew the document toward the 1 MiB limit; and GET /v1/episodes/live gained two Firestore reads per poll for the additive last-closed recap. Receipts are per-conversation state (a conversation spans episode boundaries and its finalization tail replays the whole stored transcript), so they now live in users/{uid}/episode_segment_receipts/{conversation_id}: the base document holds the most recent 2,000 ids, older ids roll into immutable s/{index} archive documents, and episode documents never carry them. The receipt write joins the episode compare-and-swap transaction, so a receipt exists exactly when the state that consumed the segment was stored. Live moments dedupe against the base document alone; the finalization tail reads every archive; a segment is never processed twice, including a 50k-segment whole-transcript tail (covered by a document-size test). Episodes written before the receipts collection kept ids in an applied_segment_ids field: the first post-change write adopts that list into the receipts and retires the in-document field, so a tail landing across the deploy still dedupes. The live poll serves the recap from a per-process cache for LAST_CLOSED_CACHE_SECONDS (30) while a live episode is on screen, and reads it fresh when no live episode is — the recovery-navigation answer the recap exists for. The response is unchanged, and a wire test now pins that response_model_exclude_unset never drops a field the generated clients require. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(backend): archive episode receipts by insertion order, not lexically plan_write sorted receipt ids alphabetically and archived the lowest-sorting shard, so past 2,000 receipts the base document kept the alphabetically highest UUIDs instead of the most recently consumed ids. Live moments dedupe against the base alone while the tracker re-presents its buffered segments and repairs place them later, so a just-consumed segment whose id sorted low was fed to the model twice. Receipt ids are now ordered oldest-first by insertion: stored order is preserved, new ids append, only the oldest overflow spills into the next immutable archive, and the base always keeps the most recent SHARD_SIZE window. Co-Authored-By: Claude Opus 5.5 <[email protected]> --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
Fixes the October 24 live-episode lifecycle failure: retained speech with
start=end=-1was excluded by the notes cursor, notes failures stopped episode activity, and closed recaps were hard to recover while member recordings finalized.-1audio offsets and the existing placed-segment cursor.last_closed_episodeto the live response when available (also alongside a newer live episode) andGET /v1/episodes/{episode_id}for account-scoped recovery navigation. Existingepisoderemains live-only.Failure-Class: FC-high-water-cursor-skips-unready-row
UI-Evidence: none
Client-file changes are generated OpenAPI wire models/methods required by the backend contract freshness gates; no handwritten client or UI code changes.
Product invariants affected
Line-Count-Exception: backend/routers/listen/transcripts.py | 1655 -> 1662 | Feed the retained unplaced fallback into the existing episode tracker at its persistence receipt.
Verification
The final head passed 547 tests across 34 focused episode/lifecycle and shared-prerequisite files through
BACKEND_UNIT_TEST_FILE_LIST=reconcile-main2-files.txt BACKEND_PYTEST_WORKERS=4 bash backend/test.shunderomi-heavy. The synthetic local Uvicorn/curl smoke passed using the real episode router/service and strict in-memory Firestore: unplaced-only notes, duplicate-ID suppression, idle-close recap discovery/direct lookup and account isolation. Outbound network and Google credentials were blocked.The full mandatory push gate passed, including whole-backend pyright, Firestore query guards, OpenAPI/client freshness and Swift compilation. Explicit metadata validation passed. Local receipts are retained in the episode-lifecycle-fix-1024 brief directory. Shared backend CI prerequisite fixes are inherited unchanged from current main; they add no separate changes to this PR's net diff.
Deployment and evidence limits
No production data was read or changed; no GCP tier was used. No PR merge, deployment, capacity change or config flip is included. The Firestore registry and generated manifest match main exactly; this PR adds no index and needs no new index prebuild. The lead owns subsequent rollout. The app must adopt the additive closed-recap field for recovery navigation. No historical closed-pointer backfill is performed.
The RCA's generation-1 check due at 05:57:45Z was still unchanged around 07:42Z. The original tests reproduced pre-transaction dispatch rejection and starvation behind a full shared replay page. Those quiet recovery mechanisms are now owned by the merged #23500; the episode PR retains and extends its missing-dispatch successor regression to verify exactly-once recovery after bindings return. The permitted evidence does not establish which occurred in production; task delivery, reconciler owner/revision, query failure and any pre-transaction exception remain the lead's open correlation question. This PR does not claim that the affected production conversation has finalized or that the all-users ramp hold can lift. Device/reconnect/STT acceptance and rollout verification remain outstanding.
🤖 Generated with Claude Code