Repository navigation
perf(episodes): retain paid compose work and compose late notes on open - #25065
Conversation
Replace the 35-file source digest that keyed notes/L1 reuse with an explicit prompt version, guarded by a pinned prompt-source digest in the test. A deploy that touches unrelated code no longer voids every stored hash. Skip the L1 memory-extraction call for noise rows and owner speech under 30 words. Unknown owner attribution is never read as owner absence; a curated row always extracts; nothing is written on a skip. Fable LLM-efficiency #5 and #7.
Fable LLM-efficiency item 1. Behind EPISODE_COMPOSE_KEEP_PAID (default on): one repair retry over the bad output alone, a title-and-lede compose for short episodes, superseded results stored and marked pending, and a two-paid-failure cap. Adds a bounded trigger label to the composer run and paid-call metrics.
… gist A single-member episode no longer pays the composer model: its title, lede, chapters and follow-ups are built from that conversation's own notes in code. The mapping is explicit so the episode page and the conversation detail agree: title/emoji from the notes, lede from the new gist (or the overview when the notes have no sections), one chapter per section with its bullets as points and times from the cited segments, follow-ups from open action items, people from participants. The shortcut writes the same composed stamps as the model path, so a later member or transcript change recomposes normally. Kill switch EPISODE_SINGLE_MEMBER_COMPOSE (default on). The notes call gains one field, gist (at most 12 words), clipped server-side and persisted on Structured. It rides the episode-member wire with home_step so
…xcerpt tool The closed-episode composer reads each member's notes by default and can fetch a bounded raw transcript excerpt on demand. Off by default behind EPISODE_COMPOSER_NOTES_FIRST; the cohort is EPISODE_COMPOSER_NOTES_FIRST_PERCENT. Bounds: 4,000 chars and 15 minutes per call, 4 calls and 12,000 chars per compose, 5 model turns. Adds input-token and tool-call metrics by mode, a read-only side-by-side operator script, and the flag registry / deployment classification rows.
Codex Review Summary: ✅ CompletedThis 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. |
|
Preview deployment for your docs. Learn more about Mintlify Previews.
💡 Tip: Enable Automations to automatically generate PRs for you. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 545e2a833c
ℹ️ 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 is_deferred(episode): | ||
| return True |
There was a problem hiding this comment.
Preserve the first-open trigger until members finish
If a deferred historical episode is opened while any member is still processing, the read-triggered compose returns waiting without clearing compose_deferred_at. When that member finishes, schedule_for_conversation() calls this helper and returns without scheduling because the episode is still deferred. Subsequent detail polls cannot recover it either: scheduling is throttled for 600 seconds, whereas openEpisode() polls for only 40 seconds. Consequently, even a member that finishes seconds after the page opens leaves the page uncomposed, and ordinary Home reads suppress recovery throughout the seven-day grace window. Persist that the first open occurred, or otherwise let member finalization resume the requested compose.
Useful? React with 👍 / 👎.
| def _curated(conversation: Any) -> bool: | ||
| return any(bool(_field(conversation, name)) for name in _CURATED_FIELDS) |
There was a problem hiding this comment.
Carry user-keep authority into L1 admission
For a conversation protected only by sync_relevance_user_kept or folder_user_set, this exemption never takes effect on the production extraction path: extract_memories() receives a Conversation, but neither flag is declared on that model, and deserialize_conversation() constructs it with Conversation(**data), dropping those fields. The reprocess path also writes sync_relevance_user_kept only into the persistence payload, not the object passed to extraction. As a result, a meaningful recording with fewer than 30 owner words still skips memory extraction after the user explicitly keeps it or organizes it into a folder, contrary to the exemption implemented here. Preserve the authority on the extraction input or pass it explicitly to admission.
Useful? React with 👍 / 👎.
| 'compose_deferred_at': None, | ||
| } | ||
|
|
||
| written = _write(uid, episode_id, c, finish) |
There was a problem hiding this comment.
Fence single-member writes against newer composed results
When two replicas compose a single-member episode around a transcript upgrade, an older invocation can overwrite the newer invocation's completed notes. This shortcut uses neither the paid path's evidence re-read nor its finish guard: _write() reads the latest episode version and then successfully applies the old member snapshot, so its CAS does not reject the stale result. It also replaces the evidence stamps and clears pending regeneration, leaving needs_compose() false after the overwrite; ordinary reads therefore cannot recover the newer notes. Guard against a newer compose and recheck member evidence before accepting this shortcut's result, including its retry path.
Useful? React with 👍 / 👎.
| if words < L1_MIN_OWNER_WORDS: | ||
| return SHORT_OWNER_SPEECH |
There was a problem hiding this comment.
Avoid whitespace-based admission for unsegmented languages
For supported languages such as Thai, this unconditional word floor suppresses substantive recordings rather than just short speech. transcript_word_count() in relevance_rules.py handles CJK specially but otherwise uses text.split(), so Thai phrases containing many words count as a single word; an 815-character Thai transcript with eight space-separated phrases returns only eight and is rejected here as short_owner_speech. Both owner-attributed and unknown-owner inputs use that counter. The existing notes floor explicitly avoids applying its word threshold to non-English captures in notes_short_clip_policy.english_word_floor(). Use a language-appropriate count or bypass this admission threshold when word boundaries cannot be measured reliably.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 78a6c220f0
ℹ️ 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".
| final episode = episodes?.openedEpisode(opened.id) ?? | ||
| episodes?.homeEpisodes |
There was a problem hiding this comment.
Let refreshed Home state replace stale opened snapshots
When a normal closed episode is opened before its compose finishes, openEpisode() caches the uncomposed detail and stops polling because composeDeferred is false. This unconditional preference then masks every subsequent Home refresh: _readHome() updates _homeEpisodes but never updates or invalidates _openedEpisodes. Consequently, even when the existing Home polling retrieves the completed notes, the open page remains on its stale processing view or draft notes until it is reopened. Reconcile opened snapshots with newer Home results, or avoid preferring an unsettled cached detail indefinitely.
Useful? React with 👍 / 👎.
| gist = _line(structured.get('gist'), COMPOSER_MAX_PARAGRAPH_CHARS) | ||
| # The overview is the section render whenever sections exist, so it is only a lede | ||
| # when there is nothing else to read; otherwise the gist is the one-line lede. | ||
| lede = gist or ('' if sections else _line(structured.get('overview'), COMPOSER_MAX_PARAGRAPH_CHARS)) |
There was a problem hiding this comment.
Preserve edited overviews in single-member episode notes
If a user edits the first-party summary before a deferred single-member episode is composed, database/conversations.py:update_conversation_summary() replaces structured.overview and deletes structured.sections, but leaves the generated gist intact. This expression then selects that stale gist instead of the corrected overview, and the shortcut produces no moments because the sections were deleted. The resulting episode therefore shows only the old generated claim and completely omits the user's correction. Preserve the authoritative overview as the body when sections are absent rather than allowing the gist to replace it.
Useful? React with 👍 / 👎.
## What/why L8a: preserve successful notes/L1 work across unrelated deploys and skip L1 for deterministic noise or fewer than 30 owner words. Unknown attribution uses the whole transcript as an upper bound; curated/imported content retains extraction. Stack order: L8a (this PR) → L8b #25065 → L9 #25075. Base main; L8a has no dependency. Normal merges only. Supersedes #25046. ## Flags, ramp and rollback `EPISODE_COMPOSER_REUSE` is default ON (unset=on). Off restores source-key writes and L1 extraction. Both directions accept compatible successful stable and pre-deploy keys; unchanged eligible work does not regenerate on deploy/rollback/toggles. Model routing changes and installed pydantic/langchain-core version changes invalidate keys. Installed versions are snapshotted once at import; historical aliases require their recorded locks (pydantic 2.11.10, langchain-core 1.3.3). A future dependency bump intentionally costs one successful notes recomputation and one admitted L1 recomputation per unchanged effective input on next processing, then reuse resumes. The population is bounded to work actually reprocessed; no proactive backfill. Existing provider retries and concurrent processing can add calls before success is persisted. No spend estimate is claimed. L8b and L9 have independent switches. Normal gates, then watch notes/L1 miss/skip ratios, checkpoint errors, memory yield and processing failures. Refactor-lead owns expansion/rollback. No measured margin claim. Rollback: `EPISODE_COMPOSER_REUSE=off`, or revert this PR; compatibility reads remain enabled during flag rollback so rollback does not re-buy stored work. ## Product invariants INV-MEM-4: preserves canonical promotion authority. No new memory writer; admission only avoids extraction, with successful checkpoint validation unchanged. INV-TASK-2: preserves capture suggestion authority, no task creation changes. ## Dispositions - Cost P1 / tests-merge P1-4: compatible pre-deploy source aliases and cross-mode reads prevent toggle-driven reciprocal invalidation. Exact effective inputs, content revision and successful output validation remain required. - Luna FIX-FIRST at c704ac9: installed dependency versions now participate in stable keys and gate every historical alias. Tests change either dependency independently, reject all historical aliases at a mismatch in both flag modes, preserve locked-version aliases, and verify one notes recomputation followed by reuse across flag flips. Metadata is never queried per call. - Correctness P2-7: independent model-routing digest invalidates both stable keys and historical aliases. - Tests-merge P0-1: based on current main; separate owned flag-budget entry and live name count. Each stack member merges current main normally before publication. - Split correction: the L1-dependent Hermetic E2E and Parakeet stack fixtures belong here. Their speech now clears the 30-word floor, preserving the real memory and exactly-once assertions. Correction 8cf55aa was carried at earlier head c704ac9 with normal main merges. Full Hermetic E2E, Listen Pusher Stack Gauntlet and the isolated lifecycle runner pass locally; assertions and admission thresholds remain intact. David approved one corrective full-hook push after the initial split publication exposed these fixture omissions. - L8b findings stay in #25065; notes-first findings stay in L9. No source PR is closed or merged. ## Tests For the dependency correction: all 13 focused backend files pass (47 dedupe tests, including 23 new dependency cases) through file-isolated backend/test.sh (3600s per-file budget); make preflight passes all 44 checks. At earlier head c704ac9, full Hermetic Backend E2E passed (202 passed, 3 existing skips, 2 existing xfails), and all three formerly failing CI checks passed; the new head will run CI again. The fixture correction also passes the full Listen Pusher Stack Gauntlet and 13 emulator contention tests, plus the separately isolated lifecycle runner (31 passed, 3 existing xfails). Regression tests cover pre-deploy checkpoints through on/off/on/off, changed model route, exact changed inputs, invalid output, admission and flag budget. Line-Count-Exception: backend/utils/conversations/process_conversation.py | 3394 -> 3398 | Four-line admission at the existing canonical memory-extraction boundary; extraction authority stays in its existing owner. UI-Evidence: none -- backend only Failure-Class: none Non-test diff versus main merge base: +359 / -23 (382 changed). Own stack delta: +359 / -23 (382 changed), excluding tests and render evidence.
# Conflicts: # backend/tests/unit/test_flag_budget.py
# Conflicts: # backend/config/flag_budget.json
## Behavior — enrollment closes before the owner fetch Only identical episode list/detail/lookup calls that enroll **before the owner starts `_fetch_members`** may share that owner's read. The owner closes `accepting` under the same map lock used for enrollment, then immediately fetches inline. Any caller arriving after enrollment closes bypasses directly to its own fresh read, even while the owner is still fetching or preparing its earlier snapshot. There is no grace sleep or batching delay. This corrects a concrete freshness defect in the earlier implementation: its unfinished Future could already contain a snapshot captured before a deletion/edit that completed before the next request began. The new request incorrectly inherited that snapshot. The old green tests did not establish freshness because their enrollment barrier was inside `get_all`, too late to be a valid sharing boundary. That earlier implementation is superseded. The bounded flight record carries a private Future plus `accepting`. Closed records remain in the map until owner completion for capacity accounting. Late bypasses neither replace nor remove them; cleanup checks record identity. The map still admits at most 128 flights with at most 1,000 unique member IDs each, keyed by Firestore plane, uid and sorted unique IDs. Capacity/oversized/reentrant calls use the independent read without truncation. Owners fetch inline with no child executor job; nested reads bypass flights. Exceptions/cancellation release early waiters and permit retry. Cancelling a waiter cannot cancel the owner. Every participant receives an independent deep copy. Completed flights/results are not retained; no writes, visibility/entitlement rules, plan filters or client shapes change. The existing `episode_members_singleflight` read lever remains default 100. Explicit 0 in the existing `FIRESTORE_READ_LEVERS` object restores independent reads at the new flight layer; the separate pre-existing cache behavior remains unchanged. No serving config is changed. The separate `episode_members_cache` remains default 0; its 60-second TTL is neither activated nor repurposed by this PR. Source default0 is not a live off-state claim: firestore-lead ec5e02 reports that cache100 on the serving backend, so this feature only sees cache misses there. Actual eligible overlap must be measured. Existing fixed-cardinality `firestore_cache_requests_total` namespace `fsr_episode_members_flight`, results `owner|coalesced|bypass|error`, remains unchanged and contains no uid/member identifiers. No production threads, tasks, executors, grace periods or TTLs are added. Original base: `BasedHardware/omi@aa3df45`. Prior-art review found merged #24929 (dark TTL memo), #25061 (shadow observation), and the audio rebuild Future pattern; no duplicate open episode-member coalescing PR was found. This corrective commit changes only `home_read.py` and its focused single-flight test file. Failure-Class: FC-read-in-flight-across-delete-resurrects-row The same stale-adoption mechanism applies here: a later request must not inherit an underlying read issued before its completed deletion. The guard is now the pre-fetch enrollment boundary, tested through the real member helper; no registry definition is changed. ## Restricted validation Serial, isolated file processes through workspace `bin/omi-heavy`, using this worktree's own Python 3.11 `backend/.venv`, with host load checked below 60 before heavy admission: - `.venv/bin/python -m pytest tests/unit/test_episode_members_singleflight.py -q`: **22 passed**. - Episode member cache/home/router siblings: **25 / 33 / 11 passed** respectively; **91 focused tests total**. - The new real `_read_members` regression first failed all **3** deletion/edit/soft-deletion cases against the old implementation. With the fix, it captures an independent fake-SDK snapshot, pauses owner preparation, completes the mutation, then proves the late caller makes its own second RPC and sees missing/current state before releasing the owner. It also proves that bypass keeps the original closed record. - Early-sharing tests now pause the owner metric callback before enrollment closes and assert no SDK call has started when waiters enroll. Isolation, independent deep copies, shared errors then retry, capacity/ID bypass, reentrancy, owner/waiter cancellation, rollback and metric failures remain covered. A closed-capacity case checks that neither same-key nor new-key bypass replaces/removes the owner. - From backend, `.venv/bin/pyright --pythonpath .venv/bin/python utils/episodes/home_read.py`: **0 errors, 45 warnings**. Pinned formatting passes. The corrective commit is `a88ccda60f11c0937d55fdd4c8def55955184b04`. The normal push hook passed all 36 selected preflight checks (including the seven-file Firestore guard: 847 passed), standard backend type checking with 0 errors, and the changed single-flight file: 22 passed. The unchanged 40-file cap restricted the broad selector to that changed test file. Final command/log results are in the appended implementation receipt. No full backend suite, skip hatch, force push or workflow edit. Existing route tests exercise local ASGI/fake dependencies; no live Firestore, installed backend, deployment, image build or production canary is claimed. Independent review and new-head GitHub CI are parent-owned, with no duplicate waiter/heartbeat started. ## Dated economic basis — ceiling only This is rank 2 / source 4 in the 2026-11-11 margin proposal, the largest additional eligible backend-invisible proposal after #25080's sync allowance repair lane. Conversation pagination needs client adoption; memory-history work needs its privacy failure gate. No overlapping credit is claimed. Recorded sampled caller pool: **20.278400M reads/day** for `utils.episodes.home_read:_read_members`, trailing 24h nominally ending **2026-11-10T22:33Z** (snapshot generated **22:35:59Z**). Recorded GMP query family: `topk(120, sum by (service_name, caller, collection, kind)(increase(omi_firestore_billed_reads_by_caller_total[24h])))`; select/sum this caller's rows. Source: workspace `data/run-2026-11-11-goals/margin-round4/firestore-measure-snapshot.json`, `deep-read-gmp.json` query strings and `deep-code-kimi-result.md`, source analysis pinned at `85de1985f0fb4fddd05e0de4b36c1ac68108d81e`; published KB `projects/admin-omi-tv-dashboard/evidence/2026-11-11-margin-unmeasured-programs.md`. Settled price basis is **2026-11-02..08**, Cloud Firestore Read Ops net **$4,054.076894 / 8,167.507724 read-M = $0.496366459757/read-M**, from recorded `firestore-read-cost-daily.json` billing-export aggregates. This gives only a **$0–$10.065518/day gross caller ceiling**. Corresponding closed Nov09 caller volume **17.134M / $8.505** is a different window and is not substituted into this estimate. These historical records were read locally; this task used no GCP tier and made no new cloud/vendor measurement. The eligible overlap is only the narrow **pre-fetch enrollment interval**, not broad concurrent misses or the duration of an in-flight RPC/preparation. Its share is even narrower and **UNMEASURED**, as is realized paid/free impact; **no expected saving and $0 booked**. Prometheus sampling, top-k omissions, retry/reset/scrape coverage, caller-vs-route attribution and mismatched native/billing windows limit the ceiling; the caller pool is not all avoidable. This does not include episode-window query reads, enable or alter the separate existing cache, imply a per-plan attribution join, or forecast savings. ## Dated readback PROPOSAL, not a serving ACK - **Baseline Nov11:** margin-lead / firestore-lead capture all-series member caller reads, `owner/coalesced/bypass/error` outcomes, episode-route 5xx and p95, and reads per successful episode completion (plus route-success denominators). Use matched windows and preserve coverage/overflow evidence. - **Target first full serving day Nov14:** only if ordinary lead2 review/release gates allow serving before Nov14 begins (by Nov13 23:59Z); otherwise use the next actual full serving day. No merge, deployment or activation is authorized by this PR or this date. - **Conditional D+2 Nov16:** margin-lead / firestore-lead reconcile the first full serving day's settled read-SKU export only after export completeness is established; shift the readback with the real serving day if later. Compare matched baseline per successful episode completion and route health, and distinguish fleet-wide SKU movement from this caller's measured reduction. Paid/free remains unmeasured until valid attribution exists. Keep $0 booked until correctness, serving identity/traffic and settled measurement prove a net impact. Implementation stops after the corrective normal push and metadata verification. Independent new-code review, new-head CI and ordinary lead2 release gates are parent-owned; no merge, deploy, activation or runtime acceptance is claimed. <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/BasedHardware/omi/pull/25086?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="View guided diff" src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a> <a href="https://www.cubic.dev/action/auto-fix/pr/BasedHardware/omi/25086?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F25086&source=description" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"><img alt="Turn on auto-fix" src="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"></picture></a> <!-- End of auto-generated description by cubic. --> Measurement ownership ACK (2026-11-11T01:47:56Z, coordkit bus `29da15`): firestore-lead owns the sync/episode readbacks, first full serving day Nov 14 / settled Nov 16 only if ordinary lead2 approval and serving allow it; otherwise D is the next full UTC serving day and readback D+2 after export completeness. This ACK does not authorize activation or deployment. Final source reviews on the earlier head `fb3bb9b83f5c9e3d5bc12302369e8e316a732074`: lead2-approved Sol privacy substitute PRE:CLEAN, then independent Luna privacy/erasure SHIP. Independent DeepSeek FINAL:CLEAN covers the earlier corrected source and its real-helper mutation regressions. These reviews cover the unchanged episode topic patch, not a claim of runtime acceptance or savings. Current PR head: `d4fab30d6726818c511346443f8cb052652aebb5`. Main was integrated after #25093 merged as `643c991a5544b6c0387f3dddd6f9b36cb9b51b54` and #25080 merged as `ad8fd1278eabb4eb1c0e4ee0aff31a150cb4ead1`, under lead2's local branch-refresh allowance. The normal push preserved the reviewed helper/test blobs and the normalized three-file topic patch. Focused tests: 22 passed through `omi-heavy`; normal hooks passed. Fresh exact-head CI is terminal green: **36 SUCCESS, 23 SKIPPED, zero pending/failed/cancelled** (backend run 42967827128); the formerly failing backfill file now has 101 passed / 1 skipped, with no guard or assertion change. Lead2 issued MERGE-OK at this head (bus d91753). Latest main #25065 also touches the helper outside the flight layer; that drift is disclosed for merge-desk's fresh-main and combined-tree checks. No merge, deploy, activation or settled saving is claimed here. Cost-change acceptance also requires accepted-result/output parity under the published quality guard (`omi-knowledge` commit `e450f118493bdc990c224ca018435a550c132ede`, `projects/omi-100m-plan/evidence/2026-11-11-quality-standing-guard.md`). Missing/stale/incomplete quality evidence is HOLD; transport success alone does not establish useful output. This proposal contributes $0 additional admitted savings to the ruling15 meter-basis path.
#25065 landed the attach-time re-arm itself (late_member.joined, both attach funnels, the evidence compare and the four tests), so this branch drops its duplicate implementation and keeps the residual: - The re-arm was gated on episode_late_compose_enabled(), which reads EPISODE_COMPOSER_THRIFT, a cost control. Turning THRIFT off for cost reasons silently restored the class-7 gap. The signal now has its own default-on EPISODE_COMPOSE_LATE_ATTACH_ENABLED. - Kill-switch test tracks the new env name; a new unit test pins the switch as independent of EPISODE_COMPOSER_THRIFT. - Registry row, generated registry doc and the change note for the flag. No new collection, index, queue, migration or composer contract change; an unchanged fingerprint still buys no second paid compose.
#25053) _Requested by **David**_ (relay-cl1 ruling f6502a; Fable audit 2026-11-10, class 7) ## Reconciliation with #25065 (read this first) Merged #25065 already landed the attach-time re-arm itself: `utils/episodes/late_member.py` (`joined`, called from `sync_attach.attach` and `batch_close.attach_closed_batch_capture`), the evidence compare, and the four tests. This PR originally proposed that same implementation and is now **reduced to the one delta that #25065 left open** — the kill switch — on top of current `main`. Nothing else of the original #25053 diff still needs to land. ## What changed and why Class 7 of the 2026-11-10 Fable audit: episode notes are written before the members finish and are not marked stale. The uncovered trigger was the attach path: a member could join an already-composed **closed** episode without any compose being scheduled. #25065 fixed the trigger but gated it on `episode_late_compose_enabled()`, which reads **`EPISODE_COMPOSER_THRIFT`** — a cost control (`backend/config/episodes.py:202`). Turning THRIFT off for cost reasons therefore silently restored the class-7 gap and notes that never saw the late member. This PR gives the signal its own switch: - `EPISODE_COMPOSE_LATE_ATTACH_ENABLED` (default on; `false`/`0`/`off`/`no` disables new stamps), `backend/config/episodes.py`. - `late_member.joined` now gates on it instead of THRIFT (`backend/utils/episodes/late_member.py:17`). - Kill-switch test now tracks the new env name; `backend/tests/unit/test_episode_late_member.py` pins the switch as independent of `EPISODE_COMPOSER_THRIFT` and covers live/uncomposed no-ops. - Registry row, generated registry doc, and a change note for the flag. The composer contract is untouched: `schedule_for_conversation` still compares the member's speech/name evidence, stamps `compose_pending_since` only when it changed, and the paid-once lease still dedupes. An unchanged fingerprint buys no second paid compose. No new collection, index, queue or data migration. ## Product invariants affected none ## Tuning - Late-member compose trigger, existing: one `schedule_for_conversation` call per member that joins a closed episode with `composed_at`. Unchanged by this PR; only the gate moved to its own flag. Before #25065 there were 0 such calls. ## New states and exits - `compose_pending_since` on a closed episode: existing state, existing writer (#25065). This PR only changes which switch gates the writer. Rollback: `EPISODE_COMPOSE_LATE_ATTACH_ENABLED=false` stops new stamps from this path; already-stamped episodes still drain through the existing composer. ## How it was verified - Registry: `scripts/render_feature_flag_registry.py --check` and `validate_registry` pass; the new row is default-on `ops_kill` with no `review_by`. - Targeted unit tests below (backend unit suite runs in CI; no local test environment was available in this workspace). - Read-only `ro-prod` metadata check of David's own account (no content, no uids printed) established the original gap: four late sync members on a composed closed episode with no pending signal. ## Tests - `backend/tests/unit/test_episode_late_member.py` (new): re-arm survives `EPISODE_COMPOSER_THRIFT=off`; the new kill switch stops it; live/uncomposed episodes are left alone. - `backend/tests/unit/test_episodes_service.py`: `test_intake_attach_to_a_composed_closed_episode_rearms_its_compose`, `test_intake_attach_to_a_composed_closed_episode_respects_the_kill_switch` (now the new flag). - `backend/tests/unit/test_episode_attach_review.py`: `test_recorded_attach_to_a_composed_closed_episode_rearms_its_compose`, `test_recorded_attach_to_a_live_episode_does_not_rearm_a_compose`. ## UI evidence UI-Evidence: none -- backend change only ## Failure class (fixes) Failure-Class: none Rollback: set `EPISODE_COMPOSE_LATE_ATTACH_ENABLED=false`, or revert the PR.
What/why
L8b keeps paid composer results, maps eligible single-member notes without another call, labels compose triggers, and composes late deferred episodes on first open. It preserves paid notes while a newly joined member is processing and retains the guarantee that late members eventually appear in episode notes.
L8a #25073 is merged into main as 7ec9a04. Under lead2 1c606e, this branch merges origin/main without rebasing and preserves main’s L8a dependency-version fencing alongside L8b. L9 #25075 remains separate. No PR is merged or closed by this work.
Flags and defaults
EPISODE_COMPOSER_THRIFT: default ON, unset=on. Controls keep-paid/repair, single-member mapping and late deferral/read trigger. Off restores paid single-member composition, discard/retry and finalize scheduling; detail reads schedule no compose. Durable deferrals still drain through ordinary recovery.EPISODE_COMPOSER_REUSE: independently default ON; its deploy/rollback compatibility preserves successful notes/L1 work. Thrift rollback never changes reuse keys or L1 admission.EPISODE_COMPOSER_NOTES_FIRSTis absent from this PR's final tree and stays default OFF in its separate PR until David's side-by-side verdict.Numeric late age/grace settings remain tuning. Late age means episode recorded-start age (48h), not individual member upload age. Read recovery exits after seven days. Notes gain an additive bounded gist in their existing call; older successful notes remain eligible without buying gists in a regeneration wave.
Ramp
L8b may serve after normal gates. Refactor-lead watches failures/conflicts, paid logical calls/repairs, input/output tokens, waiting-member retention, deferred/open/grace completion and notes freshness. Roll back on a regression. L9 stays OFF until David compares content and cumulative billed input/output, retries and failures on the same episodes; no paid side-by-side or deployment is run here. No variable-margin attainment claim.
Product invariants
INV-MEM-4: canonical memory promotion stays the authority; the L8a dependency only avoids extraction. INV-TASK-2: episode follow-ups show existing open actions and create no tasks. INV-UI-1 / INV-UI-3: existing mobile primitives and styling retained. Visibility fences discard a paid result if an original member is hidden/removed, including during a waiting-member race. Ownership tokens fence stale paid writes and lease release.
Dispositions
compose_deferredsignal; one initial read plus at most eight 5s polls, each read <=4s and total deadline 45s. Concurrent opens coalesce; page exit/account change/disposal fence results and stop further reads. Home retains its filtered membership; opened cache is invalidated with Home/delete visibility.trigger; refresh the measured production inventory after these families serve. The inventory is not fabricated from unserved code. L9 enablement requires the authoritative ledger, not these counters alone.Tests
At earlier head d7a1112, merge-main validation passed: backend/test.sh passed 1,398 tests across 43 files, covering every episode/composer suite, test_flag_budget.py and the seven L8a unit suites (dedupe, dependency upgrades and aliases, prompt versions, L1 admission, usage context, short-clip rollout and owner-memory admission). Tests use file isolation and BACKEND_UNIT_FILE_BUDGET_SECONDS=3600. backend/scripts/typecheck.sh reports zero errors. make preflight passes all 75 selected checks on the clean merge commit.
Regenerated with owning scripts: scripts/render_feature_flag_registry.py, backend/scripts/generate_firestore_indexes.py --write, backend/scripts/openapi_runner.sh with export_openapi.py --surface app-client --write, generate_dart_models.py --all and generate_swift_openapi_types.py. All outputs reproduce the merged tree.
At earlier head 78a6c22, the full hook and the original backend/Flutter/render verification passed. At earlier head bb6907c, the copyWith regression, 108 Flutter episode tests, 138 spine tests, backend typing, preflight and the full hook passed; CI was terminal green. Those are historical receipts, not validation claims for this merge.
UI-Evidence
Real Flutter widget renders from app/test/widgets/episode_composed_render_test.dart, fictional fixtures, light/dark composed pages and lede-only detail result. Client layout is unchanged by the split; refresh behavior is exercised by provider/widget regressions.
UI-Evidence: .agent-artifacts/ui-evidence/composer-thrift/ (tracked PNGs and evidence.json).
Failure-Class: none
Rollback
EPISODE_COMPOSER_THRIFT=offindependently restores finalize composition; existing deferrals drain through ordinary read recovery.EPISODE_COMPOSER_REUSE=offrestores source-key writes/L1 admission while compatibility reads avoid buying stored work. L9's separate switch restores full-transcript input. No data migration.Salvage: restored composed-episode re-deferral with an explicit client signal; completed the stamp-fault and client lifetime gaps. Dropped only redundant late-compose and L9-percentage switches, replaced by the independent stack controls. No incomplete salvage feature remains.
Supersedes #25039 #25046 #25048 #25057 #25062 (L9 source #25039 moves to the separate L9 PR; #25046 moves to #25073).
Line-Count-Exception: backend/utils/episodes/composer.py | 1105 -> 1734 | Preserve the existing canonical lifecycle, CAS, visibility and lease authority; scoped additions delegate admission/attach signaling to small helpers.
Line-Count-Exception: backend/utils/episodes/service.py | 2222 -> 2223 | Preserve the existing canonical lifecycle, CAS, visibility and lease authority; scoped additions delegate admission/attach signaling to small helpers.
Luna FIX-FIRST disposition (earlier head 78a6c22): fixed the stale single-member write and the same empty-result clearing race with an atomic episode/member revision fence; newer member or episode snapshots return superseded without retrying the stale payload. Both the normal write and window-only fallback retain the guard. Regression tests exercise real episode persistence with StrictFirestore. At that earlier head, other pre-read writes (paid compose gap, provisional deferral title, scheduling stamps) were explicitly listed in backend/docs/listen_pusher_pipeline/changes/2026-11-10-composer-snapshot-fence.md; the paid gap is closed by the disposition below. Validation at that earlier head: all 36 episode suites passed through backend/test.sh; the final focused rerun passes 33 single-member tests and 126 composer tests; make preflight passes all 77 selected checks; the full hook and CI results are reported separately.
Luna #25075 review disposition (earlier head fa02849, L8b-owned schema): added an optional composeDeferred override to Episode.copyWith. Omitted overrides preserve the current value; an explicit false clears a deferred episode. app/test/unit/episode_schema_test.dart covers both behaviors. Validation at earlier head bb6907c: app/test.sh passes all 108 selected episode tests plus its 138 spine tests; backend scripts/typecheck.sh passes with zero errors; make preflight passes all 77 selected checks. The stale single-member/empty-result transactional fence and regression coverage are included at that earlier head and preserved in the merge. L8a and L9 branches are untouched.
Merge-main disposition (lead2 1c606e): merged origin/main at 9ca056a, including L8a merge 7ec9a04, without rebasing. The sole conflict was adjacent appended tests in backend/tests/unit/test_conversation_llm_input_dedupe.py: retained main’s dependency-version tests verbatim and L8b’s additive-gist checkpoint test. Main’s installed-dependency compatibility guard remains in place; the L8b notes-2/gist aliases remain inside that guard. No new scope or L9 branch changes. David authorized one full-hook fast-forward push for this merge; the PR remains unmerged.
Luna FIX-FIRST disposition (earlier head d7a1112): paid multi-member completion and its window-only fallback now pass canonical member revisions captured at the final visibility reads to the existing episode/member transaction fence. Any subsequent member revision change or deletion refuses publication; the episode CAS guard also rejects original-member removal. Hidden originals refuse unconditionally, including a hide during the final visibility pass after the evidence fingerprint check. Refused paid notes are discarded, never published or stamped current, and the lease is released under its ownership token. Existing superseded scheduling provides bounded recomposition: background settling buys one call before the quiet timer; settling rollback remains capped at three attempts. No L8a or L9 branch changes, new flags, or paid retry loop. The snapshot-fence change doc now describes the closed paid-write gap.
At earlier head ef71cfa, validation: backend/test.sh passed every episode/composer suite plus flag-budget and the seven L8a suites: 1,413 tests across 44 files (43 files passed initially; the flag-budget file passed after the merge-count reconciliation). The 15 new strict-transaction regressions cover hard/soft deletion, discard, merge-away, revision changes, unchanged publication, both paid-write variants, hiding during the final visibility pass, and bounded recompose scheduling with settling on/off. backend/scripts/typecheck.sh passed with zero errors. make preflight passed all 75 selected checks on the clean commit. No live account data or production calls were used.
Main reconciliation at earlier head ef71cfa: merged origin/main at 4e9c704 without rebasing. The sole conflicted file was backend/tests/unit/test_flag_budget.py; retained main's projection-debt entry and L8b's thrift entry, with the shared owner checks. Reconciled the declared count to the actual merged inventory (269). Regenerated feature-flag-registry.md and firestore.indexes.json with their owning scripts. No OpenAPI/wire sources changed in this fix or main reconciliation. The PR remains unmerged.
Luna FIX-FIRST disposition (earlier head ef71cfa): removed the visibility loop's revision overwrite. The post-call _members fingerprint snapshot supplies the only expected revisions. The visibility pass now compares against that unchanged map; a revision difference, a missing snapshot entry, or a missing/hidden/discarded member refuses publication before the notes write. Both normal and window-only publishing transactions continue to validate the same snapshot map. The unsafe paid result is discarded, its lease is released under the existing token guard, and superseded uses the existing bounded recompose scheduling. No new retry path, scheduler, flag, or unrelated production change.
Current validation: backend/test.sh passed 1,416 tests across 44 files (all episode/composer suites, flag budget, and the seven L8a suites). The three added cases failed against the earlier implementation and pass with this fix: visible notes changing between the fingerprint snapshot and visibility reread never publish, and recompose remains bounded with settling on/off. Existing unchanged-member and fallback transaction tests still pass. backend/scripts/typecheck.sh passed with zero errors. make preflight passed all 75 selected checks on the clean commit. Full hook and CI results are reported separately. The snapshot-fence change doc describes the immutable snapshot revision rule.
GitHub reported CONFLICTING/DIRTY before this work, so origin/main at 6d45be4 was merged without rebasing. The sole conflict was the flag-budget count: main declares 268 entries, while this branch includes the thrift entry and correctly declares 269; retained 269, verified against the actual entries and test_flag_budget.py. The merge has no other tree changes. No generated sources or registry inputs changed. L8a/L9 branches are untouched; this PR remains unmerged.