Skip to content

perf(episodes): skip repeated sync attach reads and writes - #24582

Merged
Git-on-my-level merged 11 commits into
mainfrom
lane/fsepisodes
Nov 4, 2026
Merged

Git-on-my-level merged 11 commits into
mainfrom
lane/fsepisodes

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Nov 4, 2026 •

Copy link
Copy Markdown
Member

Requested by David

Repeated WAL intake and sync reprocessing rebuild the episode overlay even when the recorded span, speech, visibility and ownership are unchanged. This PR combines both rounds of the episode attach cost work while preserving membership, recorded timelines, caps, navigation and speech deduplication.

  • Keep the fenced canonical-partition fast path: require exact start/end/source, member list and owner revision proof, then validate the current conversation. Missing proof or changed evidence takes the full path. Share canonical/fixed-boundary candidate rows within one transaction attempt, discard the cache on retry, and pass existing fence rows into window checks.
  • Add a completed content memo to episode_links/{cid}. Bare sync_content_revision is unsafe: assignment.assign_in_transaction increments it unconditionally for admitted WAL merges, including identical transcript/span; batch projection and donor redirects also advance it. Keep the revision as a conservative fence and hash it together with the full transcript, proven recorded bounds, ancestry, source, recovery clocks/language, calendar/capture context, effective visibility inputs, completion state and batch pending/failed/deadline flags. Ignore relevance-decision timestamps. Missing/unsupported/undecodable evidence falls through. Donor and duplicate-group rows conservatively retain the full path.
  • Stamp the semantic key and owner ID in the existing attach transaction, validating the current row. Activate it only after successful recovery in a small completion transaction that revalidates the current row/link. This extra completion step prevents an attach-committed/recovery-failed update from permanently skipping speech. A direct attach hit reads only the link and current conversation, returns attached_unchanged, and performs zero episode reads, repartition reads, or writes. Current-row validation rejects stale inputs across discard/deletion, content growth and repointing.
  • Gate both intake and finalize before episode executor submission using the supplied row plus transactional validation of the link and current conversation. This adds one conversation read per successful scheduling hit, with no episode reads. A just-read visible snapshot cannot suppress the hook across a discard or deletion observed at the gate. A separate attach_finalized marker preserves the first finalize/compose signal after intake recovery; subsequent identical finalizations skip the whole hook, including compose scheduling. The durable finalizer bounds its memo lookup and falls through on failure. If that caller retains a stale visible row, authoritative member admission still rejects current discard/deletion; the full hook retires the hidden member and stops reconciliation. Donor and repointed-owner errors keep their existing retries, and this cleanup adds no read. Discard/duplicate CASes invalidate old memo proof atomically, so a restore cannot reuse a pre-discard stamp.
  • Add omi_sync_intake_content_shadow_total{speech,span}: plain-sync merges split by new_speech/repeat_only and unchanged/growth/changed/unknown recorded extent. Uses accepted survivors and existing bounds, emits only after commit once per plan, adds no database operations, and has no UID labels.
  • Skip episode scheduling after a no-op sync reprocess. Both enrichment callers always reach the shared scheduler: equal before/after inputs can already include a persisted append that still owes its first finalize, so equality skips only with completed current attach_finalized proof. Changed inputs force scheduling. Deep-copy the before snapshot before possible in-place mutation; normalize wire defaults and compare transcript, proven span, visibility and membership inputs. Changed content/extent/visibility and missing owners still schedule. Processing clocks alone do not schedule. Structured title, overview and action items remain in the scheduling digest unless Reduce redundant background episode composition #24579's config.episodes.episode_compose_settle_enabled capability is present and on. When that capability is absent or off, summary-only updates still schedule the current composer; either PR can land first. The existing repeat-work metric reports feature="episode_attach", outcomes scheduled/unchanged.
  • Reuse the placed owner through the recovered-ID CAS and recovery walk; omit intake's unused recorded owner lookup. Reuse receipts, owner and supplied visibility per walk, advancing only after successful CAS. A conflict invalidates the cached state. Notes transactions still validate current hidden/repointed state.
  • Omit value-identical link and reverse-membership writes independently; repair a stale reverse field even when its link is correct. Skip a duplicate-group CAS only when both its duplicate set and membership are already present.

The default-on umbrella EPISODE_ATTACH_OPTIMIZATIONS_ENABLED disables both rounds: all seven controls below, recorded-partition proof reuse/stamping, candidate/fence read reuse, and recovery receipt prefilter/caching. Off restores repartition and membership writes plus per-batch receipt reads. Canonical and fixed-boundary paths retain their shared fenced transaction; with reuse disabled this omits no operation and preserves serialization. Each Round 2 optimization also has its own default-on kill switch; false, off, 0 or no restores its prior path:
EPISODE_ATTACH_CONTENT_GATE_ENABLED, EPISODE_ATTACH_NOOP_SCHEDULE_ENABLED, EPISODE_ATTACH_OWNER_REUSE_ENABLED, EPISODE_ATTACH_MEMBERSHIP_DEDUPE_ENABLED, EPISODE_ATTACH_ROW_VISIBILITY_ENABLED, EPISODE_ATTACH_WALK_CONTEXT_ENABLED, EPISODE_ATTACH_DUPLICATES_DEDUPE_ENABLED.

Same release train as #24544 (dfd489aa75e2, still open when checked): its batch rows attach at audio close and remain compatible with the conservative memo fallback for incomplete transcription. When combining, retain its public attach_recorded(..., pending_transcription=...) helper and pending_at forwarding alongside this PR's attach_row argument. Neither PR should deploy separately from the agreed train.

No production reads/writes, merge or deployment by this agent. No new query shape, index or public API.

Publication status

This PR was merged externally at cc1d62ca56310ba5ed70479635c1aaee56da5677 on 2026-11-04 at 12:47:58 UTC, while the agent's subsequent normal pre-push gate was running. Its merged source head is 93d8c89d182c89e823b917d7abf0cf1e0afa4565. The agent did not merge or deploy it. The P1/P2 and full umbrella rollback fixes are included in that head.

A later safety follow-up is local at 02372e29c75fac97a01e1e9a560dda68986f2623. Its normal pre-push checks all passed, but GitHub rejected the deleted branch reference. That commit is not included in this PR; separate publication awaits David's direction.

Product invariants affected

none

Validation

  • Full backend type check on the stable combined source: 0 errors (PYRIGHT_PYTHON="$PWD/backend/.venv/bin/python" bash backend/scripts/typecheck.sh through omi-heavy).
  • Review regression coverage: The durable stale-row regression was red for both discard/deletion before cleanup, then all 20 review cases passed; negative cases keep donor/repoint conflicts out of discard cleanup. stale visible snapshots followed by concurrent discard, soft deletion or missing document cannot suppress intake/finalize; the submitted finalize hook retires discarded/deleted members. Hits read the link and current conversation without episode reads or writes.
  • Composer compatibility: title, overview and action-item changes schedule with the old composer or Reduce redundant background episode composition #24579 off; they skip with Reduce redundant background episode composition #24579 on. Tests cover attach-first/composer-first and runtime off/re-enable. An additional smoke check loads Reduce redundant background episode composition #24579's actual config source (head 55eb517cfe38) and passes both orders with default-on, off and re-enabled settings.
  • Rollback: tests prove the umbrella overrides all seven individual switches, re-enters repartition/writes despite completed proof, restores separate fixed-boundary/window candidate queries, and restores per-batch receipt reads.
  • 795 passed across 19 targeted unit files, through /Users/dazheng/workspace/omi/bin/omi-heavy using the canonical backend/test.sh file-isolated runner: attach review/cost, first-finalize obligations, closed skip, live integrity, episode service, finalizer hook/paths, late recorded audio, receipts, composer, sync reprocess, intake shadow, flag budget and incremental live notes, plus conversation-tool sanitization (9) and legacy sync-v2 coordinator coverage (175) and merge-validation coverage (50). The latter two suites exposed and now cover import-isolation regressions: recorded-time arithmetic imports its canonical configuration constant directly, and sync fixtures retain the real pure attach-key/telemetry modules before package stubbing. Held-processing scheduler doubles also accept the new keyword arguments and return scheduling intent.
  • Real isolated loopback Firestore emulator v1.22.0 on final source 93d8c89d182c: 24 passed in 60.71s, including both stale durable-finalizer discard/deletion races and current-row/memo/restore, candidate reuse/retry and visibility fences. The owned emulator was stopped afterward. The earlier v1.21.0 run on 0d389a5696a3 had 21 passed / 1 SDK transaction-lock timeout; retry budgets and contention fixtures were not changed. The final rerun used the emulator version currently installed on the host.
  • make preflight: 40 checks passed on the stable combined source; PR metadata validation also passed. The normal pre-push gate passed without bypasses, including its 40 manifest checks, full backend type check, selected backend unit tests and pinned formatting. Published head: 93d8c89d182c89e823b917d7abf0cf1e0afa4565. The final normal push passed 40 manifest checks, full backend type check (0 errors), selected unit suites and pinned formatting without bypasses. Exact-head CI finished green: 65 terminal checks, none failed or pending, on 93d8c89d182c89e823b917d7abf0cf1e0afa4565.
  • No production reads/writes, GCP tier, merge or deployment by this agent.

Line-Count-Exception: backend/utils/sync/pipeline.py | 4062 -> 4073 | Keep the frozen legacy reprocess callback in parity with enrichment while passing its semantic snapshot and first-finalize scheduling obligation to the shared gate.

Expected saving and deployment verification

Upper-bound planning estimate, avoiding overlap: 39–59M fewer reads/day and 4–6M fewer writes/day, roughly $27–41/day net. Round 2 adds approximately 9–14M fewer reads/day beyond Round 1 (roughly $3–7/day net after allowing for marker writes). Compared with the earlier write forecast, conservatively reserve up to 1M additional writes/day for first-finalize markers; the net Round 2 write delta is therefore 0–0.7M more writes/day until measured. The eligible completed/repeat-only finalization share is not measured. Owed first-finalize work always runs; equality inside a processing pass is not a saving. Treat this as a planning ceiling until caller counters measure the eligible share. These ranges include memo validation/completion overhead and reserve another 1M reads/day for mandatory current-row scheduling validation. Actual added overhead follows scheduling attempts that reach current-row validation, including rejected stale snapshots; that rate remains unmeasured, so revise this reserve against caller counters after deployment. Round 1's original $15–25/day estimate counted reads only; its unchanged-repartition fast path also removes most repeated attach writes. No additional paid-compose saving is claimed: that requires measured composer outcomes after deployment. These are forecasts from the Nov 4 75M reads / 9.15M writes caller snapshot, using $0.06/100k reads, $0.18/100k writes and the handoff's 0.9 net multiplier. They are not measured production savings, and the levers must not be summed independently.

After the shared train deploys, compare matching fully post-deployment 24h windows at comparable sync volume, with every emitting service present:

source ~/.local/bin/gcp-agent-env.sh ro-prod
FSR_CALLER_WINDOW=24h python3 avo/firestore-reads/measure.py --hours 24

From ~/workspace/omi (workspace tooling outside this public monorepo), compare caller rows for database.episode_receipts:get_consumed_ids, database.episode_timeline:recorded_candidates, database.episodes:read_memberships, database.episode_recorded_components:commit, database.episode_timeline:attach, database.episodes:get_episode, database.episodes:_link_target and database.episodes:_update. Include new database.episode_attach_memo:check / :finish reads when comparing the family total. The current measurement script prints read rows; use the same Managed Prometheus source for sum by (service_name, caller, collection, op) (increase(omi_firestore_billed_writes_by_caller_total[24h])). Compare database.episode_recorded_components:attach, database.episode_timeline:_attach_recorded_window, database.episode_timeline:attach_recorded, database.episodes:update_episode and database.episode_attach_memo:complete; transaction refactoring can move caller attribution, so compare their sum. Inspect synthetic unchanged, grown, new-member, discarded, donor and deleted capture membership/timelines before train approval. On deploy day, inspect sum by (speech, span) (increase(omi_sync_intake_content_shadow_total[24h])) to measure the unproven repeat-only/unchanged versus new-speech/growth shares. Monitor attach conflict/error outcomes and the repeat-work scheduled/unchanged ratio; missing services or lower sync volume are not savings.

Failure-Class: none

🤖 Generated with Claude Code

@cubic-dev-ai cubic-dev-ai 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.

3 issues found across 11 files

Confidence score: 3/5

  • In episode_recorded_components.py, the early return skips fixed-boundary fence checks, so captures overlapping live, user, or calendar episodes can remain assigned to their automatic owner instead of returning None. Apply those checks on the early-return path.
  • In 2026-11-04-episode-attach-reads.md, the caller labels don’t match the probe naming: they omit the database. prefix, and episode_recorded_components:commit is nested. Align the labels so the caller probe can identify them correctly.
  • In episode_recorded_components.py, importing from utils/ reverses the layering described in backend/AGENTS.md. Move the span and discard checks to a database-level helper, or confirm the exception is accepted.
Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="backend/docs/listen_pusher_pipeline/changes/2026-11-04-episode-attach-reads.md">

<violation number="1" location="backend/docs/listen_pusher_pipeline/changes/2026-11-04-episode-attach-reads.md:19">
P3: The caller labels here omit the `database.` prefix that the caller probe uses (see `database.rollout_cohorts:_read_memberships` in the bundled-reader runbook). `episode_recorded_components:commit` is also a nested function inside `attach`. Use the exact labels the probe emits so the post-deploy comparison finds these rows.</violation>
</file>

<file name="backend/database/episode_recorded_components.py">

<violation number="1" location="backend/database/episode_recorded_components.py:18">
P3: This `database/` module now imports from `utils/`, which reverses the layering in `backend/AGENTS.md`. Move the span and discard checks into a database-level helper, or confirm the reverse import is an accepted exception.</violation>

<violation number="2" location="backend/database/episode_recorded_components.py:200">
P2: The early return skips the fixed-boundary fence checks that the full path applies. A capture that now overlaps a live, user, or calendar episode would stay in its automatic owner instead of returning None. Re-run the fixed-row checks before returning the cached owner, or confirm that fixed episodes cannot appear after the proof is written.</violation>
</file>

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

and not is_relevance_discarded(member)
and not any(member.get(k) for k in ('deleted', 'sync_merged_into'))
):
full = episodes.unseal(uid, owner)

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: The early return skips the fixed-boundary fence checks that the full path applies. A capture that now overlaps a live, user, or calendar episode would stay in its automatic owner instead of returning None. Re-run the fixed-row checks before returning the cached owner, or confirm that fixed episodes cannot appear after the proof is written.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/database/episode_recorded_components.py, line 200:

<comment>The early return skips the fixed-boundary fence checks that the full path applies. A capture that now overlaps a live, user, or calendar episode would stay in its automatic owner instead of returning None. Re-run the fixed-row checks before returning the cached owner, or confirm that fixed episodes cannot appear after the proof is written.</comment>

<file context>
@@ -140,21 +142,65 @@ def _state(template, window, previous, facts):
+                    and not is_relevance_discarded(member)
+                    and not any(member.get(k) for k in ('deleted', 'sync_merged_into'))
+                ):
+                    full = episodes.unseal(uid, owner)
+                    if full is not None:
+                        return {**full, '_recorded_windows': [full]}
</file context>

when the legacy receipt base is absent. No rollout flag or public API changes.

After deployment, compare `avo/firestore-reads/measure.py` caller rows for
`episode_timeline:recorded_candidates`, `episodes:read_memberships`,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3: The caller labels here omit the database. prefix that the caller probe uses (see database.rollout_cohorts:_read_memberships in the bundled-reader runbook). episode_recorded_components:commit is also a nested function inside attach. Use the exact labels the probe emits so the post-deploy comparison finds these rows.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/docs/listen_pusher_pipeline/changes/2026-11-04-episode-attach-reads.md, line 19:

<comment>The caller labels here omit the `database.` prefix that the caller probe uses (see `database.rollout_cohorts:_read_memberships` in the bundled-reader runbook). `episode_recorded_components:commit` is also a nested function inside `attach`. Use the exact labels the probe emits so the post-deploy comparison finds these rows.</comment>

<file context>
@@ -0,0 +1,22 @@
+when the legacy receipt base is absent. No rollout flag or public API changes.
+
+After deployment, compare `avo/firestore-reads/measure.py` caller rows for
+`episode_timeline:recorded_candidates`, `episodes:read_memberships`,
+`episode_recorded_components:commit`, and `episode_receipts:get_consumed_ids`
+at comparable sync volume. The handoff estimates $15–25/day net, equivalent to
</file context>
Suggested change
`episode_timeline:recorded_candidates`, `episodes:read_memberships`,
`database.episode_timeline:recorded_candidates`, `database.episodes:read_memberships`,

from config.recorded_time_tolerances import CLOSE_GAP_SECONDS, MAX_EPISODE_SECONDS
from database._client import run_transactional
from database import episodes
from utils.conversations.recorded_time import conversation_span

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3: This database/ module now imports from utils/, which reverses the layering in backend/AGENTS.md. Move the span and discard checks into a database-level helper, or confirm the reverse import is an accepted exception.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/database/episode_recorded_components.py, line 18:

<comment>This `database/` module now imports from `utils/`, which reverses the layering in `backend/AGENTS.md`. Move the span and discard checks into a database-level helper, or confirm the reverse import is an accepted exception.</comment>

<file context>
@@ -15,6 +15,8 @@
 from config.recorded_time_tolerances import CLOSE_GAP_SECONDS, MAX_EPISODE_SECONDS
 from database._client import run_transactional
 from database import episodes
+from utils.conversations.recorded_time import conversation_span
+from utils.conversations.fragment_visibility import is_relevance_discarded
 
</file context>

@Git-on-my-level Git-on-my-level changed the title perf(episodes): cut redundant Firestore attach reads perf(episodes): skip repeated sync attach reads and writes Nov 4, 2026
@Git-on-my-level
Git-on-my-level marked this pull request as draft November 4, 2026 11:37
@Git-on-my-level

Copy link
Copy Markdown
Member Author

episodes batch 1: ships together as one train, CI red

@Git-on-my-level
Git-on-my-level marked this pull request as ready for review November 4, 2026 12:05
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 4, 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-11-04T12:10:39.584348Z 93d8c89 Draft marked ready
ℹ️ 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.

@cubic-dev-ai cubic-dev-ai 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.

16 issues found across 34 files

Confidence score: 3/5

  • In finalize.py, on_realtime_segments calls skip_unchanged_schedule directly, so its blocking Firestore transaction can stall the event loop. Run it in the pool worker.
  • In sync_attach.py, recovery can detect that a conversation became hidden but return the earlier placement result instead. Propagate skipped_discarded and call end_discarded before returning.
  • In episode_attach_memo.py, a stamp-transaction failure can make the caller report error even after recovery succeeded. Keep memo-stamp failures from changing the reported attach outcome.
  • In finalizer.py, the new skip bypasses EPISODE_ATTACH_NOOP_SCHEDULE_ENABLED, so the documented rollback switch won't restore full scheduling. Gate the skip on noop_schedule_enabled().
Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="backend/utils/sync/intake_content_shadow.py">

<violation number="1" location="backend/utils/sync/intake_content_shadow.py:12">
P3: This counter never pre-creates its label series, unlike `absorption_metrics._prime()`. Until a combination first occurs, it is absent from `/metrics`, so the repeat-only/unchanged share query returns no data instead of 0. Prime all `SPEECH` x `SPANS` children at import, following the `_prime()` pattern.</violation>
</file>

<file name="backend/docs/listen_pusher_pipeline/changes/2026-11-04-episode-attach-reads.md">

<violation number="1" location="backend/docs/listen_pusher_pipeline/changes/2026-11-04-episode-attach-reads.md:18">
P3: The post-deploy comparison points at `avo/firestore-reads/measure.py`, which is not in this repository. Either add the script path that exists or name the external location, so the verification step can be run.</violation>

<violation number="2" location="backend/docs/listen_pusher_pipeline/changes/2026-11-04-episode-attach-reads.md:98">
P3: The kill-switch table documents env var defaults and effects, which the changes README reserves for `listen_pusher_pipeline.mdx`. Move the table into that contract section and link to it from this note; the mdx currently has no `EPISODE_ATTACH_*` entries.</violation>

<violation number="3" location="backend/docs/listen_pusher_pipeline/changes/2026-11-04-episode-attach-reads.md:122">
P3: The Round 2 dollar range doesn't match the read range stated here. At the note's $0.06/100k and 0.9 multiplier, 9–14M reads is about $4.9–7.6/day, not $3–7. Recompute the range or state the price basis used.</violation>
</file>

<file name="backend/tests/unit/test_sync_reprocess_coalesce.py">

<violation number="1" location="backend/tests/unit/test_sync_reprocess_coalesce.py:1306">
P2: The `off` case cannot detect a broken kill switch: the proof mock returns False for `off`, so scheduling happens even if `EPISODE_ATTACH_NOOP_SCHEDULE_ENABLED` is ignored. Return True for `off` too, so only the env gate forces the schedule.</violation>
</file>

<file name="backend/database/episode_attach_memo.py">

<violation number="1" location="backend/database/episode_attach_memo.py:100">
P2: `complete` lets a Firestore failure from its stamp transaction propagate after recovery already succeeded. The caller then reports the attach as `error` even though the work completed. `matches` fails open with a fallback record, so wrap this call the same way.</violation>
</file>

<file name="backend/tests/unit/test_sync_intake_content_shadow.py">

<violation number="1" location="backend/tests/unit/test_sync_intake_content_shadow.py:14">
P3: The parametrized cases skip the `changed` and `unknown` span branches of `capture`, and the `new_speech`/`unchanged` pairing. Add those cases so every label branch of the fixed-cardinality counter is covered.</violation>
</file>

<file name="backend/utils/conversations/finalizer.py">

<violation number="1" location="backend/utils/conversations/finalizer.py:152">
P2: This skip ignores `EPISODE_ATTACH_NOOP_SCHEDULE_ENABLED`. Gate the new block on `noop_schedule_enabled()` as `schedule_after_finalization` does, so the rollback switch restores full scheduling as documented.</violation>
</file>

<file name="backend/utils/enrichment/callback.py">

<violation number="1" location="backend/utils/enrichment/callback.py:288">
P3: This labels disabled users as `unchanged` and can label swallowed submit failures as `scheduled`, so the metric does not distinguish actual scheduling from no-op or failure. Return and record distinct outcomes at both sync callers.</violation>

<violation number="2" location="backend/utils/enrichment/callback.py:290">
P3: The success log changes from `outcome=processed` to `outcome=success` without explanation. Any log-based alert or query keyed on `event=sync_reprocess_callback outcome=processed` will stop matching. Restore the original outcome value, or call the rename out in the PR description.</violation>
</file>

<file name="backend/utils/episodes/capture_groups.py">

<violation number="1" location="backend/utils/episodes/capture_groups.py:36">
P2: The duplicates skip returns before `update_episode`, so reverse membership for the duplicate ids is never repaired and the transactional membership checks never run. The skip only inspects the owner snapshot's arrays, which can be stale, so gate it on validated current link state or run the normal update when the reverse links are not confirmed.</violation>
</file>

<file name="backend/utils/episodes/finalize.py">

<violation number="1" location="backend/utils/episodes/finalize.py:85">
P1: This memo check runs a blocking Firestore transaction on the event loop. `on_realtime_segments` is async and calls `schedule_synced_intake_attach` directly. Move the `skip_unchanged_schedule` call into the pool worker, or wrap it in `run_blocking(db_executor, ...)` before the call.</violation>
</file>

<file name="backend/tests/unit/test_episode_live_integrity.py">

<violation number="1" location="backend/tests/unit/test_episode_live_integrity.py:1176">
P2: `assert calls` is outside the if/else, so it also runs for the `deleted`/`discarded` cases. Those raise `conversation_hidden` in `read_memberships` before `recorded_candidates` runs, so `calls` is empty and the assertion fails. Move it into the `else` branch.</violation>
</file>

<file name="backend/utils/sync/pipeline.py">

<violation number="1" location="backend/utils/sync/pipeline.py:1195">
P2: The snapshot work (`process_snapshot` deep copies, `should_schedule`) runs for every sync reprocess, even for users outside the episodes cohort or with the optimization switched off. Gate these calls on `episodes_enabled_for(uid)` and `noop_schedule_enabled()` so non-cohort users do not pay for two full-row deep copies and model dumps per reprocess.</violation>

<violation number="2" location="backend/utils/sync/pipeline.py:1287">
P2: Users outside the episodes cohort get `outcome='unchanged'` because `schedule_after_finalization` returns False when episodes are disabled. That inflates the 'exact reuse' rate that the PR's post-deploy verification relies on. Record a distinct outcome such as 'disabled' when `episodes_enabled_for(uid)` is false, or skip the record for those users.</violation>
</file>

<file name="backend/utils/episodes/sync_attach.py">

<violation number="1" location="backend/utils/episodes/sync_attach.py:122">
P2: A recovery can return `skipped_discarded` after its write detects that the conversation became hidden, but this returns the earlier placement result instead. Propagate that result and call `end_discarded` before returning so finalization records the discard cleanup.</violation>
</file>

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

return
snapshot = dict(row) if isinstance(row, Mapping) else {}
try:
if skip_unchanged_schedule(uid, conversation_id, snapshot):

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: This memo check runs a blocking Firestore transaction on the event loop. on_realtime_segments is async and calls schedule_synced_intake_attach directly. Move the skip_unchanged_schedule call into the pool worker, or wrap it in run_blocking(db_executor, ...) before the call.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/utils/episodes/finalize.py, line 85:

<comment>This memo check runs a blocking Firestore transaction on the event loop. `on_realtime_segments` is async and calls `schedule_synced_intake_attach` directly. Move the `skip_unchanged_schedule` call into the pool worker, or wrap it in `run_blocking(db_executor, ...)` before the call.</comment>

<file context>
@@ -55,12 +58,32 @@ def attach_synced_at_intake(uid: str, conversation_id: str, row: Mapping[str, An
         return
     snapshot = dict(row) if isinstance(row, Mapping) else {}
     try:
+        if skip_unchanged_schedule(uid, conversation_id, snapshot):
+            return
         submit_with_context(
</file context>

monkeypatch.setattr(finalize, 'episodes_enabled_for', lambda _: True)
monkeypatch.setattr(finalize, 'lifecycle_executor', lambda *a, **kw: object())
# An equal processing pass may skip only with completed current finalize proof.
proof = Mock(return_value=change in {'none', 'timestamps'})

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: The off case cannot detect a broken kill switch: the proof mock returns False for off, so scheduling happens even if EPISODE_ATTACH_NOOP_SCHEDULE_ENABLED is ignored. Return True for off too, so only the env gate forces the schedule.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/tests/unit/test_sync_reprocess_coalesce.py, line 1306:

<comment>The `off` case cannot detect a broken kill switch: the proof mock returns False for `off`, so scheduling happens even if `EPISODE_ATTACH_NOOP_SCHEDULE_ENABLED` is ignored. Return True for `off` too, so only the env gate forces the schedule.</comment>

<file context>
@@ -1262,3 +1262,69 @@ def callback(*_):
+    monkeypatch.setattr(finalize, 'episodes_enabled_for', lambda _: True)
+    monkeypatch.setattr(finalize, 'lifecycle_executor', lambda *a, **kw: object())
+    # An equal processing pass may skip only with completed current finalize proof.
+    proof = Mock(return_value=change in {'none', 'timestamps'})
+    monkeypatch.setattr(finalize, 'skip_unchanged_schedule', proof)
+    schedule = Mock()
</file context>
Suggested change
proof = Mock(return_value=change in {'none', 'timestamps'})
proof = Mock(return_value=change in {'none', 'timestamps', 'off'})

):
transaction.update(ref, {marker: key})

run_transactional(client, finish, transient=True)

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: complete lets a Firestore failure from its stamp transaction propagate after recovery already succeeded. The caller then reports the attach as error even though the work completed. matches fails open with a fallback record, so wrap this call the same way.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/database/episode_attach_memo.py, line 100:

<comment>`complete` lets a Firestore failure from its stamp transaction propagate after recovery already succeeded. The caller then reports the attach as `error` even though the work completed. `matches` fails open with a fallback record, so wrap this call the same way.</comment>

<file context>
@@ -0,0 +1,100 @@
+        ):
+            transaction.update(ref, {marker: key})
+
+    run_transactional(client, finish, transient=True)
</file context>

if not row:
return
try:
if trigger == ProcessingTrigger.SYNC_UPDATE and episodes_enabled_for(uid):

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: This skip ignores EPISODE_ATTACH_NOOP_SCHEDULE_ENABLED. Gate the new block on noop_schedule_enabled() as schedule_after_finalization does, so the rollback switch restores full scheduling as documented.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/utils/conversations/finalizer.py, line 152:

<comment>This skip ignores `EPISODE_ATTACH_NOOP_SCHEDULE_ENABLED`. Gate the new block on `noop_schedule_enabled()` as `schedule_after_finalization` does, so the rollback switch restores full scheduling as documented.</comment>

<file context>
@@ -148,6 +149,24 @@ async def _episode_after_finalization(
     if not row:
         return
     try:
+        if trigger == ProcessingTrigger.SYNC_UPDATE and episodes_enabled_for(uid):
+            try:
+                unchanged = await asyncio.wait_for(
</file context>

if (
duplicates_dedupe_enabled()
and set(ids) <= set(owner.get('duplicate_conversation_ids') or [])
and set(ids) <= set(owner.get('conversation_ids') or [])

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: The duplicates skip returns before update_episode, so reverse membership for the duplicate ids is never repaired and the transactional membership checks never run. The skip only inspects the owner snapshot's arrays, which can be stale, so gate it on validated current link state or run the normal update when the reverse links are not confirmed.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/utils/episodes/capture_groups.py, line 36:

<comment>The duplicates skip returns before `update_episode`, so reverse membership for the duplicate ids is never repaired and the transactional membership checks never run. The skip only inspects the owner snapshot's arrays, which can be stale, so gate it on validated current link state or run the normal update when the reverse links are not confirmed.</comment>

<file context>
@@ -24,11 +25,17 @@ def canonical_row(uid, conversation_id, row, *, firestore_client=None):
+    if (
+        duplicates_dedupe_enabled()
+        and set(ids) <= set(owner.get('duplicate_conversation_ids') or [])
+        and set(ids) <= set(owner.get('conversation_ids') or [])
+    ):
+        return owner
</file context>


Upper-bound planning estimate, avoiding additive overlap: **39–59M reads and 4–6M writes
saved/day** (about **$27–41/day net** at the handoff's prices). Round 2 adds an
estimated **9–14M fewer reads/day** beyond Round 1 (about **$3–7/day net**).

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3: The Round 2 dollar range doesn't match the read range stated here. At the note's $0.06/100k and 0.9 multiplier, 9–14M reads is about $4.9–7.6/day, not $3–7. Recompute the range or state the price basis used.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/docs/listen_pusher_pipeline/changes/2026-11-04-episode-attach-reads.md, line 122:

<comment>The Round 2 dollar range doesn't match the read range stated here. At the note's $0.06/100k and 0.9 multiplier, 9–14M reads is about $4.9–7.6/day, not $3–7. Recompute the range or state the price basis used.</comment>

<file context>
@@ -0,0 +1,141 @@
+
+Upper-bound planning estimate, avoiding additive overlap: **39–59M reads and 4–6M writes
+saved/day** (about **$27–41/day net** at the handoff's prices). Round 2 adds an
+estimated **9–14M fewer reads/day** beyond Round 1 (about **$3–7/day net**).
+This reserves another 1M reads/day for the mandatory current-row scheduling
+validation; actual overhead equals successful scheduling memo hits/day and is
</file context>

All new controls default **on**; `false`, `off`, `0` or `no` restores that
optimization's prior path. They are read at the call boundary:

| Kill switch | Effect when off |

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3: The kill-switch table documents env var defaults and effects, which the changes README reserves for listen_pusher_pipeline.mdx. Move the table into that contract section and link to it from this note; the mdx currently has no EPISODE_ATTACH_* entries.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/docs/listen_pusher_pipeline/changes/2026-11-04-episode-attach-reads.md, line 98:

<comment>The kill-switch table documents env var defaults and effects, which the changes README reserves for `listen_pusher_pipeline.mdx`. Move the table into that contract section and link to it from this note; the mdx currently has no `EPISODE_ATTACH_*` entries.</comment>

<file context>
@@ -0,0 +1,141 @@
+All new controls default **on**; `false`, `off`, `0` or `no` restores that
+optimization's prior path. They are read at the call boundary:
+
+| Kill switch | Effect when off |
+| --- | --- |
+| `EPISODE_ATTACH_OPTIMIZATIONS_ENABLED` | Disable all seven controls below, recorded-partition proof reuse, candidate/fence read reuse, and receipt prefilter/caching; run every recovery batch with fresh receipts |
</file context>



@pytest.mark.parametrize(
'speech,span', [('repeat_only', 'unchanged'), ('repeat_only', 'growth'), ('new_speech', 'growth')]

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3: The parametrized cases skip the changed and unknown span branches of capture, and the new_speech/unchanged pairing. Add those cases so every label branch of the fixed-cardinality counter is covered.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/tests/unit/test_sync_intake_content_shadow.py, line 14:

<comment>The parametrized cases skip the `changed` and `unknown` span branches of `capture`, and the `new_speech`/`unchanged` pairing. Add those cases so every label branch of the fixed-cardinality counter is covered.</comment>

<file context>
@@ -0,0 +1,48 @@
+
+
[email protected](
+    'speech,span', [('repeat_only', 'unchanged'), ('repeat_only', 'growth'), ('new_speech', 'growth')]
+)
+def test_plain_merge_is_shadowed_once_after_commit(speech, span):
</file context>

record_feature(uid, processed_conversation, 'episode_attach', 'scheduled' if schedule_episode else 'unchanged')

logger.info('event=sync_reprocess_callback outcome=processed')
logger.info('event=sync_reprocess_callback outcome=success')

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3: The success log changes from outcome=processed to outcome=success without explanation. Any log-based alert or query keyed on event=sync_reprocess_callback outcome=processed will stop matching. Restore the original outcome value, or call the rename out in the PR description.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/utils/enrichment/callback.py, line 290:

<comment>The success log changes from `outcome=processed` to `outcome=success` without explanation. Any log-based alert or query keyed on `event=sync_reprocess_callback outcome=processed` will stop matching. Restore the original outcome value, or call the rename out in the PR description.</comment>

<file context>
@@ -273,7 +278,14 @@ def enrich_conversation(uid: str, conversation_id: str, language: str):
+    record_feature(uid, processed_conversation, 'episode_attach', 'scheduled' if schedule_episode else 'unchanged')
 
-    logger.info('event=sync_reprocess_callback outcome=processed')
+    logger.info('event=sync_reprocess_callback outcome=success')
     return sync_done(processed_conversation)
</file context>
Suggested change
logger.info('event=sync_reprocess_callback outcome=success')
logger.info('event=sync_reprocess_callback outcome=processed')

row=process_snapshot(conversation_data, processed_conversation),
inputs_changed=should_schedule(episode_before, processed_conversation),
)
record_feature(uid, processed_conversation, 'episode_attach', 'scheduled' if schedule_episode else 'unchanged')

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3: This labels disabled users as unchanged and can label swallowed submit failures as scheduled, so the metric does not distinguish actual scheduling from no-op or failure. Return and record distinct outcomes at both sync callers.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/utils/enrichment/callback.py, line 288:

<comment>This labels disabled users as `unchanged` and can label swallowed submit failures as `scheduled`, so the metric does not distinguish actual scheduling from no-op or failure. Return and record distinct outcomes at both sync callers.</comment>

<file context>
@@ -273,7 +278,14 @@ def enrich_conversation(uid: str, conversation_id: str, language: str):
+        row=process_snapshot(conversation_data, processed_conversation),
+        inputs_changed=should_schedule(episode_before, processed_conversation),
+    )
+    record_feature(uid, processed_conversation, 'episode_attach', 'scheduled' if schedule_episode else 'unchanged')
 
-    logger.info('event=sync_reprocess_callback outcome=processed')
</file context>

@Git-on-my-level
Git-on-my-level merged commit cc1d62c into main Nov 4, 2026
65 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/fsepisodes branch November 4, 2026 12:48
Git-on-my-level added a commit that referenced this pull request Nov 4, 2026
#24579 added a keyword-only row= to composer.after_finalized; the #24582
review test's lambda double rejected it (TypeError -> outcome=error).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Git-on-my-level added a commit that referenced this pull request Nov 4, 2026
* fix(episodes): coalesce background summary composition

* fix(episodes): preserve read promotion on worker exit

* fix(episodes): harden trigger telemetry and rollout coverage

* fix(episodes): recover pending composition across write failures and restart

* fix(episodes): compose immediately when settle queue is full

* test(episodes): accept composer row kwarg in durable-hook double

#24579 added a keyword-only row= to composer.after_finalized; the #24582
review test's lambda double rejected it (TypeError -> outcome=error).

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Git-on-my-level added a commit that referenced this pull request Nov 4, 2026
)

<!-- claude-projects-attribution: {"github_login":"Git-on-my-level"} -->
_Requested by **David**_

Batch captures previously stayed outside episodes until transcription
finished. Audio close now attaches retained captures by committed audio
bounds before queueing finalization, through the shared fenced
recorded-time membership transaction. Arrival and processing clocks
never select the episode or change its live pointer.

The membership transaction stamps a fixed pending-transcription entry
time and two-hour deadline. Replays preserve the deadline. Home shows
“Transcribing…” while awaiting the durable batch projection; a dead
letter, failed upload/status or elapsed deadline shows “Couldn't
transcribe” with the committed audio finish time. A later successful
projection restores ordinary member metadata. Audio and retry work
remain retained.

`EPISODE_BATCH_CLOSE_ATTACH_ENABLED` defaults on. Setting it to
false/off/0/no restores attach-after-transcription. Episode/cohort,
privacy, custom-STT, retention, lock, deletion and donor guards remain
authoritative. Attachment adds no model calls and does not require a
client-seen marker. Failure emits shared degraded-fallback telemetry and
leaves finalization as the repair path. The overdue metric is an
unlabeled read-observation counter; the info alert remains in the
pending catalog, with no monitoring provisioning in this PR.

Refreshed with merge commits through main `563e6c240944` (#24577,
#24579, #24582/#24604 and subsequent main changes, including #24509).
The resolution keeps batch 1's shared transaction/fence, attempt-local
candidate reuse, current canonical partition proof, visibility
validation, deduplicated memberships and recovery memo. Pending close
writes its deadline inside that transaction without claiming/resetting
completed transcript recovery. Close replay validates current committed
archive bounds, normalized through the same datetime conversion used at
admission, and is a true no-op with attach optimizations on or off.
Changed bounds still update the episode without renewing the deadline.
Composer settling, foreground promotion, Home read cuts and
recording-speaker carry remain intact.

The five original conflicts were in `episode_recorded_components.py`,
`episode_timeline.py`, `service.py`, the Firestore query-driver registry
and the generated feature-flag catalog. The sync callback and affected
tests now use the public `attach_recorded` helper. The final speaker-tip
merge was clean; the core episode resolution is unchanged.

Validation at `817784dced26`: **858 passed across 21 focused backend
files** through `backend/test.sh` with an explicit file list and four
workers; **4 real Firestore emulator replay cases passed**, covering
integer/fractional archive epochs and attach optimizations on/off. All
tests/build gates run through `omi-heavy` at low priority, with no
production credentials.

Emulator limitation: the full 28-case episode suite alternated SDK
transaction-lock timeouts between two old concurrency cases. Its last
full run was **27 passed / 1 failed**, not all green. Both concurrency
cases then passed together in a targeted run on exact main
`cf601889c67b` and exact candidate `b8633977345c`. All 28 cases have
passing candidate executions across full plus targeted runs; this does
not establish a cause for the intermittent timeout. Core
episode/emulator source is byte-identical after the final main merge,
and the four new replay cases were rerun on the final head. Firestore
clients now close at fixture teardown; test concurrency and transaction
retry budgets are unchanged.

Final hermetic e2e at `817784dced26`: **205 passed, 3 skipped, 2 xfailed
in 101.14s**, within the unchanged **120s** limit. Native-library
threads were capped at one; `--disable-warnings` suppressed only the
console warning summary, without filtering warnings or changing warning
assertions. Two earlier final-head attempts reached the wall limit (one
at 100% test progress while rendering warnings). The lead authorized a
documented 300s diagnostic if necessary, but it was **not used**.
Committed and remote-CI budgets remain 120s. `make preflight` passed
**43/43** before the final clean main merge; the normal push hook runs
the final required gates again.

Failure-Class: FC-finalize-hook-allowlist-omits-ingestion-path

Product invariants: INV-MEM-4 and INV-TASK-2. Canonical episode
ownership and task/enrichment authority remain unchanged.

No PR merge, deploy, production account access or GCP calls. GCP tier:
none. No rebase, force-push, workflow additions or firmware edits. The
lead owns merge and the backend/listen release train.

UI-Evidence: none -- backend response projection; related mobile fixture
evidence belongs to #24541.
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