Skip to content

Home (backend): settle episode reads, hold floor rows, neutral titles - #24497

Merged
Git-on-my-level merged 22 commits into
mainfrom
lane/homesettle-backend
Nov 4, 2026
Merged

Git-on-my-level merged 22 commits into
mainfrom
lane/homesettle-backend

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

Requested by David

Home can publish capture fragments before its episode overlay arrives, then reuse a member's transcript-echo title while the episode finishes. This addresses the TestFlight 4314 sequence of fragment rows, delayed grouping into “Call, House Visits, and Breakfast”, and the standalone “Thank you.” row.

  • B1: Membership-aware /v1/conversations suppresses completed members only for an episodes-admitted, client-capable account with an exact client-held episode/member acknowledgement. The separate app PR retains each omitted member's snapshot locally and advances pagination by the original server page size. This removes redundant member payloads without orphaning members when an overlay changes.
  • B2: Completed uncurated content_below_floor rows stay off Home permanently, across capture lanes and regardless of duration or age (including the 458-second, 12-hour-old “Yeah.” case). Only provisional minimum-title/batch-short rows expire after two hours. Episode floor projection drops the 60-second window leg. Search/direct access and user curation retain the speech; pending, processing and in-progress rows remain visible.
  • B3: The episode list read idle-closes at most two stale live episodes and schedules compose in that call, outside the separate two-per-read recovery cap. Successful close reuses its committed state; only a lost CAS rereads one exact episode snapshot (no redirect traversal). Other live episodes keep their members until a later read. The base already schedules compose through _close for live/lookup reads; those paths get explicit regression coverage and retain one schedule per close.
  • B4: Conversation and episode-member read projections replace floor/short server-minimum titles and exact eight-word lazy placeholders with the existing neutral recording/time title. Missing-provenance first-sentence inference is confined to floor/short rows with speech already loaded. Dead-letter terminal titles and user edits remain authoritative. Legacy list/member rows with omitted transcripts are deliberately left alone: no transcript hydration/refetch is performed. Presentation only: no backfill or stored title writes.
  • B5: With no language preference and a supplied transcript, a non-English capture tag requires agreement from the character-weighted dominant transcript language; otherwise output is English. Conversations and episodes share the resolver. Omitted segments retain a valid capture tag. EPISODE_OUTPUT_LANGUAGE_PIN=off restores preference-then-capture fallback on both paths.

Reachability: an episode id or account capability marker alone cannot prove this client loaded a replacement. Suppression requires exact client-held episode/member acknowledgements, checked against an extant closed episode and its retained members. Existing clients, first reads, unfetched older pages, filtered views, missing episodes and lookup failures keep members visible. Date-filtered requests ignore the acknowledgement header entirely, so their exact matches and ordinary cache/version behavior survive even if a client sends it. Validation batches at most five exact episode documents per request, drawn from acknowledged members actually present on that page; members beyond the budget remain visible. Headers over 50 pairs are ignored. Responses identify omitted ids and the original page size for a future capable client to retain snapshots and paginate safely. The next app PR adds that opt-in; B1 intentionally keeps members visible on currently released builds.

Kill switches: HOME_HIDE_EPISODE_MEMBERS=off restores member list rows, conditional version checks and normal cacheability even if the client keeps sending its acknowledgement header; HOME_HIDE_BELOW_FLOOR_ROWS=off releases floor/minimum holds and floor-member projection hiding. HOME_NEUTRAL_MINIMUM_TITLES=off restores stored title presentation. All three default on. Existing EPISODES_ENABLED/admission and EPISODE_COMPOSER=off remain authoritative. EPISODE_OUTPUT_LANGUAGE_PIN=off also rolls back the conversation/episode transcript-language guard to preference-then-capture fallback.

Failure-Class: new

Product invariants: INV-MEM-4 and INV-TASK-2. Conversation processing continues to use canonical memory intake and the shared task capture policy; this change resolves its output language.

Backend only: B1–B5 ship with the next backend deployment, owned by the rollout lead. The mobile first-paint/placeholder changes and batch attachment at audio close are separate PRs. No app files, production access or deployment are included.

The new failure class FC-provisional-home-content-published-as-final records the shared backend read contract and its behavioral guard artifacts.

Validation:

  • Full backend unit selection at c91a5ebd3812: 2,536 files, all six canonical CI shards through bin/omi-heavy, two workers per shard. Two local jobs reached their one-hour outer timeout under shared-host load; their exact 496 unfinished files were resumed with the same test.sh isolation, marker and CPU guards. The completed/resumed union is verified against the canonical selection: no omitted files.
  • After merging current main (91c848ee28fc), 68 affected test files passed with two workers: all 50 changed backend test files, all four newly selected files, and the Home regression files. Together these runs cover the merged branch’s 2,540 selected file paths. The upstream drain-fixture conflict was resolved using its complete current fixture and regenerated flag registry.
  • The subsequent phase-shadow main change (f95e9252d649) was integrated without changing Home verdicts: 24 affected files passed, including the new read-only shadow suites and all Home regressions. Cumulative verification covers all 2,545 file paths selected at f8e8df184f9c.
  • Five failing files were resolved and rerun with one worker: CI runner contract 15 passed, archive filter 4 passed, real native Opus recovery 68 passed, unsupported-language guard 48 passed, and migration safety guard 26 passed. The latter two passed unchanged, with their original timing limits. No added skips, credentials exceptions, test-budget increases or allowlist additions.
  • 40 Home regressions passed after the latest merge, including permanent-floor verdict observation without mutating source rows. An isolated source fixture of reviewed head 9789797e3c83 fails 14 review regression cases; the current implementation passes. New coverage includes kill-switch cache restoration/304, both neutral-title projections, language rollback/missing segments, five-document membership validation with excess members visible, successful-close document reuse, two idle closes per page, exact filtered reachability, and authoritative dead-letter/normal titles.
  • The subsequent merge of c28132c6454 resolves only the generated feature-flag registry conflict; Home implementation is unchanged from f8e8df184f9c.
  • Full backend type check: 0 errors. Both reported CI regressions pass; test_dead_letter_visible_row_title and its “Call the landlord.” expectation are unchanged. Episode list reads use the module/injected database handle and a strict fixture, with no credentials skip.

The CI runner honors an explicit low worker limit while preserving its auto default, tested on both changed-files and full selections. The archive fixture loads the real title policy before closing its import path. The cap-hold fixture waits for both independent starts and always releases its fake barrier; assertions and deadlines are unchanged.

Search's Short clips filter is handled by #24397. This PR changes read visibility and title presentation, without backfilling or storing discard/title changes.

@chatgpt-codex-connector

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 ⚠️ Failed 2026-11-03T11:42:45.487108Z
We couldn’t complete this review. Comment @codex review to try again.
9789797 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

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

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@Git-on-my-level Git-on-my-level self-assigned this Nov 3, 2026

@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 25 files

Confidence score: 3/5

  • process_conversation.py drops the cohort gate and ignores the language-pin kill switch, so the transcript-based language check can affect every user. Restore both checks before applying it.
  • service.py can make an episode’s output language flip based on the current batch’s segments. Validate the capture tag against a stable episode-level source instead.
  • settle_episode_for_read can let an idle-close failure break the entire GET /v1/episodes request. Keep a stale-episode recovery failure from failing the list read.
  • conversation_home_titles.py can leave legacy titles unchanged on non-indexed reads, and one undecodable transcript can prevent later rows from being neutralized. Handle each snapshot independently and cover the non-indexed path.
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/database/conversation_home_titles.py">

<violation number="1" location="backend/database/conversation_home_titles.py:26">
P2: Legacy titles are never neutralized on the non-indexed conversation-list path. `get_conversations_without_photos` includes `transcript_segments` unless indexed list reads are enabled, but this candidate filter excludes every such row; include rows with an existing transcript field or use their already-loaded transcript.</violation>

<violation number="2" location="backend/database/conversation_home_titles.py:33">
P2: The fallback client should be `get_firestore_client()`, not the legacy `conversations.db` proxy. The backend guide reserves `db` for existing code.</violation>

<violation number="3" location="backend/database/conversation_home_titles.py:64">
P3: The broad handler also swallows `ListReadBudgetExhausted`, so budget exhaustion is recorded as a generic 'other' fallback instead of a deadline or documents exhaustion. Re-raise or special-case that type so telemetry and truncation stay correct.</violation>

<violation number="4" location="backend/database/conversation_home_titles.py:68">
P2: One undecodable transcript aborts the whole batch, leaving every later placeholder title unneutralized on the page. Wrap the decode and projection for each snapshot in its own try so one bad row only skips itself.</violation>
</file>

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

<violation number="1" location="backend/tests/unit/test_episode_home_read.py:163">
P3: The relaxed `field_paths` check accepts either field set for every batch, and the batch sizes can't tell the two reads apart. A member read that switches to transcript fields would still pass. Record the field paths per batch and assert the order, e.g. the first three calls use `MEMBER_FIELDS` and the last three use the transcript paths.</violation>
</file>

<file name="backend/utils/llm/output_language.py">

<violation number="1" location="backend/utils/llm/output_language.py:50">
P3: `segments` defaults to `None`, so any caller that omits it downgrades a non-English capture tag to `'en'` even when the transcript is in that language. Consider making `segments` a required argument so each caller states its transcript source explicitly.</violation>
</file>

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

<violation number="1" location="backend/database/conversations.py:2010">
P3: This candidate filter should use the same whitespace rule as `neutralize_minimum_title`. A whitespace-only `user_title` is not a user override, so the placeholder title is skipped here and keeps showing in list reads. Test with `str(row.get('user_title') or '').strip()`.</violation>
</file>

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

<violation number="1" location="backend/utils/conversations/process_conversation.py:404">
P2: This line drops the `NOTES_PACKET_V2_MODE` cohort gate and does not check `episode_output_language_pinned()`, so the new transcript-based language check applies to every user and the `EPISODE_OUTPUT_LANGUAGE_PIN` kill switch cannot roll it back. `trigger_conversation_apps` still uses the gated path, so structured output and app output can now pick different languages. Gate this line the same way as before, and keep the legacy fallback for when the pin or cohort is off.</violation>
</file>

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

<violation number="1" location="backend/utils/conversations/home_titles.py:37">
P2: This neutral title is rendered in UTC, so a user outside UTC sees the wrong clock time on Home, for example 10:14 PM for a 3:14 PM local recording. Resolve the user's time zone for `uid` and pass it as `tz_name`, as the processing paths do, or confirm that UTC is intended here.</violation>
</file>

<file name="backend/routers/conversations.py">

<violation number="1" location="backend/routers/conversations.py:1013">
P2: Heal runs after the Home projection, so acknowledged completed members that are locked are never passed to `heal_conversations` on the list read. Move the heal call above `project_list` so recovery sees every fetched row.</violation>

<violation number="2" location="backend/routers/conversations.py:1018">
P2: `start_date`/`end_date` narrow the result set but do not set `filtered`, so a date-window read can still suppress members. Add both to the `filtered` predicate so the design's 'filtered lists keep rows' rule holds.</violation>
</file>

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

<violation number="1" location="backend/utils/episodes/service.py:422">
P2: A failure while idle-closing one stale episode raises out of `settle_episode_for_read` and fails the whole `GET /v1/episodes` read. The list read used to be pure; the composed side effects now can break it. Wrap the close in a try/except that logs and falls back to the row as read, matching `schedule_missed_composes`.</violation>

<violation number="2" location="backend/utils/episodes/service.py:947">
P2: Validating a capture tag against each moment's own segments makes the episode's output language depend on the current batch. A short-turn batch can flip a French or Vietnamese episode to English and back. Validate once per conversation, not per moment, or keep the memoized conversation language stable across moments.</violation>
</file>

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

<violation number="1" location="backend/utils/episodes/home_membership.py:39">
P3: This projection runs `list_row=True`, which increments the `shown`/`hidden_below_floor` home-member counters in `record_home_members`. The suppression pass is an internal check, so each Home request with held episodes double-counts members. Keep the list-row visibility filter but skip the metric call for this internal projection.</violation>
</file>

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

<violation number="1" location="backend/utils/episodes/home_read.py:128">
P2: This call has no `budget`, so each Home page can fetch and decode the full transcript for every legacy-title member, with no cap. The conversation list path passes a `ListReadBudget` for the same work. Pass a budget here, or bound the candidate count, to keep the read cost predictable.</violation>
</file>

<file name=".github/failure-classes/FC-provisional-home-content-published-as-final.json">

<violation number="1" location=".github/failure-classes/FC-provisional-home-content-published-as-final.json:3">
P2: This new failure-class definition is being added by a PR with `fix:` commits, but the PR body has no `Failure-Class` declaration, so failure-class validation fails. Add exactly `Failure-Class: new` to the PR body.</violation>
</file>

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

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

and not row.get('user_title')
and (row.get('structured') or {}).get('title')
and not (row.get('structured') or {}).get('title_provenance')
and 'transcript_segments' not in row

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: Legacy titles are never neutralized on the non-indexed conversation-list path. get_conversations_without_photos includes transcript_segments unless indexed list reads are enabled, but this candidate filter excludes every such row; include rows with an existing transcript field or use their already-loaded transcript.

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/conversation_home_titles.py, line 26:

<comment>Legacy titles are never neutralized on the non-indexed conversation-list path. `get_conversations_without_photos` includes `transcript_segments` unless indexed list reads are enabled, but this candidate filter excludes every such row; include rows with an existing transcript field or use their already-loaded transcript.</comment>

<file context>
@@ -0,0 +1,68 @@
+        and not row.get('user_title')
+        and (row.get('structured') or {}).get('title')
+        and not (row.get('structured') or {}).get('title_provenance')
+        and 'transcript_segments' not in row
+    }
+    if not candidates:
</file context>

Comment thread backend/utils/episodes/ARCHITECTURE.md Resolved
or normalize_language(language_code)
or 'en'
)
user_language = resolve_output_language(uid, language_code, getattr(conversation, 'transcript_segments', None))

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 line drops the NOTES_PACKET_V2_MODE cohort gate and does not check episode_output_language_pinned(), so the new transcript-based language check applies to every user and the EPISODE_OUTPUT_LANGUAGE_PIN kill switch cannot roll it back. trigger_conversation_apps still uses the gated path, so structured output and app output can now pick different languages. Gate this line the same way as before, and keep the legacy fallback for when the pin or cohort is off.

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/process_conversation.py, line 404:

<comment>This line drops the `NOTES_PACKET_V2_MODE` cohort gate and does not check `episode_output_language_pinned()`, so the new transcript-based language check applies to every user and the `EPISODE_OUTPUT_LANGUAGE_PIN` kill switch cannot roll it back. `trigger_conversation_apps` still uses the gated path, so structured output and app output can now pick different languages. Gate this line the same way as before, and keep the legacy fallback for when the pin or cohort is off.</comment>

<file context>
@@ -401,13 +401,7 @@ def occasion_reason():
-            or normalize_language(language_code)
-            or 'en'
-        )
+        user_language = resolve_output_language(uid, language_code, getattr(conversation, 'transcript_segments', None))
         summary_app_selected = selected_summary_app(uid, summary_app_selected, redis_db.get_user_preferred_app)
         minimum = quiet_minimum(
</file context>

try:
if budget is not None:
budget.check()
client = firestore_client if firestore_client is not None else conversations.db

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2: The fallback client should be get_firestore_client(), not the legacy conversations.db proxy. The backend guide reserves db for existing code.

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/conversation_home_titles.py, line 33:

<comment>The fallback client should be `get_firestore_client()`, not the legacy `conversations.db` proxy. The backend guide reserves `db` for existing code.</comment>

<file context>
@@ -0,0 +1,68 @@
+    try:
+        if budget is not None:
+            budget.check()
+        client = firestore_client if firestore_client is not None else conversations.db
+        refs = [
+            client.collection('users').document(uid).collection('conversations').document(cid) for cid in candidates
</file context>

record_fallback(
component='firestore_read', from_mode='none', to_mode='none', reason='other', outcome='degraded', log=logger
)
logger.warning('event=home_legacy_title outcome=unavailable exception_type=%s', type(error).__name__)

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: One undecodable transcript aborts the whole batch, leaving every later placeholder title unneutralized on the page. Wrap the decode and projection for each snapshot in its own try so one bad row only skips itself.

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/conversation_home_titles.py, line 68:

<comment>One undecodable transcript aborts the whole batch, leaving every later placeholder title unneutralized on the page. Wrap the decode and projection for each snapshot in its own try so one bad row only skips itself.</comment>

<file context>
@@ -0,0 +1,68 @@
+        record_fallback(
+            component='firestore_read', from_mode='none', to_mode='none', reason='other', outcome='degraded', log=logger
+        )
+        logger.warning('event=home_legacy_title outcome=unavailable exception_type=%s', type(error).__name__)
</file context>

Comment thread backend/database/conversations.py Outdated
)

if list_fields_only:
neutralize_legacy_list_titles(uid, rows, budget=budget)

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 candidate filter should use the same whitespace rule as neutralize_minimum_title. A whitespace-only user_title is not a user override, so the placeholder title is skipped here and keeps showing in list reads. Test with str(row.get('user_title') or '').strip().

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/conversations.py, line 2010:

<comment>This candidate filter should use the same whitespace rule as `neutralize_minimum_title`. A whitespace-only `user_title` is not a user override, so the placeholder title is skipped here and keeps showing in list reads. Test with `str(row.get('user_title') or '').strip()`.</comment>

<file context>
@@ -2014,6 +2006,10 @@ def get_conversations_without_photos(
     )
 
+    if list_fields_only:
+        neutralize_legacy_list_titles(uid, rows, budget=budget)
+    return rows
+
</file context>

)
projected = neutralize_minimum_title({**row, 'transcript_segments': segments})
row['structured'] = projected['structured']
except Exception as error:

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 broad handler also swallows ListReadBudgetExhausted, so budget exhaustion is recorded as a generic 'other' fallback instead of a deadline or documents exhaustion. Re-raise or special-case that type so telemetry and truncation stay correct.

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/conversation_home_titles.py, line 64:

<comment>The broad handler also swallows `ListReadBudgetExhausted`, so budget exhaustion is recorded as a generic 'other' fallback instead of a deadline or documents exhaustion. Re-raise or special-case that type so telemetry and truncation stay correct.</comment>

<file context>
@@ -0,0 +1,68 @@
+            )
+            projected = neutralize_minimum_title({**row, 'transcript_segments': segments})
+            row['structured'] = projected['structured']
+    except Exception as error:
+        record_fallback(
+            component='firestore_read', from_mode='none', to_mode='none', reason='other', outcome='degraded', log=logger
</file context>

if not episode or episode.get('recorded_merged_into') or episode.get('status') == 'live':
continue
projected = home_read.project_episode(
uid, episode, members={row['id']: row for row in rows if row.get('episode_id') == eid}, list_row=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.

P3: This projection runs list_row=True, which increments the shown/hidden_below_floor home-member counters in record_home_members. The suppression pass is an internal check, so each Home request with held episodes double-counts members. Keep the list-row visibility filter but skip the metric call for this internal projection.

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/home_membership.py, line 39:

<comment>This projection runs `list_row=True`, which increments the `shown`/`hidden_below_floor` home-member counters in `record_home_members`. The suppression pass is an internal check, so each Home request with held episodes double-counts members. Keep the list-row visibility filter but skip the metric call for this internal projection.</comment>

<file context>
@@ -0,0 +1,74 @@
+            if not episode or episode.get('recorded_merged_into') or episode.get('status') == 'live':
+                continue
+            projected = home_read.project_episode(
+                uid, episode, members={row['id']: row for row in rows if row.get('episode_id') == eid}, list_row=True
+            )
+            if projected:
</file context>

Comment thread backend/utils/episodes/home_read.py Resolved
Comment thread backend/utils/llm/output_language.py Resolved
@Git-on-my-level
Git-on-my-level merged commit 723183e into main Nov 4, 2026
75 of 80 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/homesettle-backend branch November 4, 2026 01:52
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