Repository navigation
Home (backend): attach batch captures to episodes at audio close - #24544
Conversation
There was a problem hiding this comment.
3 issues found across 9 files
Confidence score: 4/5
.github/failure-classes/FC-finalize-hook-allowlist-omits-ingestion-path.jsonchangescanonical_prevention, which the registry rules reserve for a separate lifecycle PR. Keep the artifact addition here and move that change to its own PR.backend/utils/episodes/ARCHITECTURE.mddescribes batch-close attachment as an unmarked episode-store write, conflicting with the Client channel rule. Clarify how the client-seen marker applies.backend/docs/listen_pusher_pipeline.mdxleaves out the existing episode and recorded-time gates, plus the sharedrecord_fallbacktelemetry on failure. Document those behaviors.
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/episodes/ARCHITECTURE.md">
<violation number="1" location="backend/utils/episodes/ARCHITECTURE.md:486">
P2: This sentence makes batch-close attachment an unmarked episode-store write, which contradicts the Client channel rule above that nothing is written to the episode store without the client-seen marker. Either document this as an explicit exception with its rationale, or gate `attach_closed_batch_capture` on `client_gate.client_seen(uid)` to match the rest of the episode write paths.</violation>
</file>
<file name=".github/failure-classes/FC-finalize-hook-allowlist-omits-ingestion-path.json">
<violation number="1" location=".github/failure-classes/FC-finalize-hook-allowlist-omits-ingestion-path.json:5">
P2: This edits the existing class's `canonical_prevention`, which the failure-class rules reserve for a separate registry-only lifecycle PR. Keep only the `canonical_prevention_artifact` addition here and move the new prevention text to a registry-only PR. Otherwise `scripts/failure-class validate` rejects the instance-fix declaration.</violation>
</file>
<file name="backend/docs/listen_pusher_pipeline.mdx">
<violation number="1" location="backend/docs/listen_pusher_pipeline.mdx:299">
P3: This paragraph omits two behaviors the code implements: attachment is gated by the existing episode and recorded-time switches, and a failure emits the shared `record_fallback` degraded-fallback telemetry. Name both so operators know which switch disables attachment and which signal shows a failed attach.</violation>
</file>
Reply with feedback, questions, or to request a fix.
View guided diff | Turn on auto-fix | Re-trigger cubic
There was a problem hiding this comment.
8 issues found across 24 files
Confidence score: 3/5
- In
batch_close.py, admission can change after the caller readsrow, soattach_recordedmay link a capture that is no longer eligible. Recheck admission within the membership transaction. - In
episode_batch_pending.py, pending transcriptions get a two-hour deadline instead of the documented 30-minute target, so Home can show “Transcribing…” too long. Cap the entry deadline at 30 minutes. - In
home_read.py, malformed audio bounds such as NaN or infinity can makedatetime.fromtimestampraise and return a Home 500. Validate the bounds or catch conversion errors.
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/tests/unit/test_episode_home_read.py">
<violation number="1" location="backend/tests/unit/test_episode_home_read.py:428">
P2: This HTTP test checks only title and status for the pending, dead-letter, and deadline cases. It never checks the committed audio finish time that the PR says these placeholders must show. Assert `finished_at` for the non-projected outcomes so the audio-bounds override is covered.</violation>
</file>
<file name=".github/failure-classes/FC-finalize-hook-allowlist-omits-ingestion-path.json">
<violation number="1" location=".github/failure-classes/FC-finalize-hook-allowlist-omits-ingestion-path.json:9">
P3: `test_episode_batch_audio_close.py` does not exercise the sync-finalization hook or the Home folding contract described by this failure class; it only tests batch-close attachment. Remove it from `canonical_prevention_artifact` or add a regression test that drives the omitted sync path.</violation>
</file>
<file name="backend/database/episode_batch_pending.py">
<violation number="1" location="backend/database/episode_batch_pending.py:18">
P2: This assigns every pending transcription the full two-hour timeliness SLA, so Home can show “Transcribing…” for two hours instead of the documented normal 30-minute target. Cap the entry deadline at 30 minutes while retaining the two-hour SLA as the upper bound.</violation>
</file>
<file name="backend/utils/episodes/batch_close.py">
<violation number="1" location="backend/utils/episodes/batch_close.py:50">
P1: This admission check is not fenced with the membership transaction. If deletion, privacy, STT, or batch-lane ownership changes after the caller reads `row`, `attach_recorded` can still link the ineligible capture and stamp pending metadata; revalidate admission inside that transaction or enforce a snapshot precondition.</violation>
</file>
<file name="backend/tests/unit/test_episode_batch_pending_alert.py">
<violation number="1" location="backend/tests/unit/test_episode_batch_pending_alert.py:13">
P3: This test does not check the alert's firing chain. Add assertions that `rule['condition'] == 'E'`, that the reduce step consumes `D`, and that `D`'s expression is `$A > 0`. Otherwise a miswired threshold passes while the alert never fires.</violation>
</file>
<file name="backend/tests/unit/test_episode_batch_audio_close.py">
<violation number="1" location="backend/tests/unit/test_episode_batch_audio_close.py:385">
P3: This test's name says the deadline is gained atomically without reset, but it only asserts the deadline is truthy. Assert the exact deadline relative to the pending start (the 2h value the sibling tests check) and that the existing membership's values are unchanged.</violation>
</file>
<file name="backend/docs/listen_pusher_pipeline/changes/2026-11-04-home-batch-close-deadline.md">
<violation number="1" location="backend/docs/listen_pusher_pipeline/changes/2026-11-04-home-batch-close-deadline.md:9">
P3: This change note points to `charts/monitoring/pending/episode-batch-pending.json`, but the catalog is at `backend/charts/monitoring/pending/episode-batch-pending.json`. Correct the path so operators can locate the staged alert.</violation>
</file>
<file name="backend/utils/episodes/home_read.py">
<violation number="1" location="backend/utils/episodes/home_read.py:313">
P2: `project_episode` can turn malformed stored audio bounds into a Home 500: the numeric check admits NaN, infinity, and out-of-range timestamps, which `datetime.fromtimestamp` raises on. Catch conversion errors or validate the timestamp before replacing the displayed clocks.</violation>
</file>
Reply with feedback, questions, or to request a fix.
View guided diff | Turn on auto-fix | Re-trigger cubic
| started = datetime.fromtimestamp(row['server_batch_audio_start'], timezone.utc) | ||
| finished = datetime.fromtimestamp(row['server_batch_audio_end'], timezone.utc) | ||
| c = collaborators or service.Collaborators(firestore_client=conversations.db) | ||
| service.attach_recorded(uid, conversation_id, row, started, finished, c, pending_transcription=True) |
There was a problem hiding this comment.
P1: This admission check is not fenced with the membership transaction. If deletion, privacy, STT, or batch-lane ownership changes after the caller reads row, attach_recorded can still link the ineligible capture and stamp pending metadata; revalidate admission inside that transaction or enforce a snapshot precondition.
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/batch_close.py, line 50:
<comment>This admission check is not fenced with the membership transaction. If deletion, privacy, STT, or batch-lane ownership changes after the caller reads `row`, `attach_recorded` can still link the ineligible capture and stamp pending metadata; revalidate admission inside that transaction or enforce a snapshot precondition.</comment>
<file context>
@@ -0,0 +1,62 @@
+ started = datetime.fromtimestamp(row['server_batch_audio_start'], timezone.utc)
+ finished = datetime.fromtimestamp(row['server_batch_audio_end'], timezone.utc)
+ c = collaborators or service.Collaborators(firestore_client=conversations.db)
+ service.attach_recorded(uid, conversation_id, row, started, finished, c, pending_transcription=True)
+ return 'attached'
+ except Exception as error:
</file context>
| 'deadline': ("Couldn't transcribe", 'failed'), | ||
| 'projected': ('Recovered transcript', 'completed'), | ||
| } | ||
| assert (wire['title'], wire['status']) == expected[outcome] |
There was a problem hiding this comment.
P2: This HTTP test checks only title and status for the pending, dead-letter, and deadline cases. It never checks the committed audio finish time that the PR says these placeholders must show. Assert finished_at for the non-projected outcomes so the audio-bounds override 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_episode_home_read.py, line 428:
<comment>This HTTP test checks only title and status for the pending, dead-letter, and deadline cases. It never checks the committed audio finish time that the PR says these placeholders must show. Assert `finished_at` for the non-projected outcomes so the audio-bounds override is covered.</comment>
<file context>
@@ -365,3 +365,64 @@ def test_members_read_in_recorded_order_not_arrival_order(monkeypatch):
+ 'deadline': ("Couldn't transcribe", 'failed'),
+ 'projected': ('Recovered transcript', 'completed'),
+ }
+ assert (wire['title'], wire['status']) == expected[outcome]
</file context>
| assert (wire['title'], wire['status']) == expected[outcome] | |
| assert (wire['title'], wire['status']) == expected[outcome] | |
| if outcome != 'projected': | |
| assert wire['finished_at'].startswith((START + timedelta(minutes=2)).strftime('%Y-%m-%dT%H:%M:%S')) |
| return {} | ||
| return { | ||
| 'episode_transcription_pending_at': pending_at, | ||
| 'episode_transcription_deadline_at': pending_at + timedelta(seconds=SLA_SECONDS), |
There was a problem hiding this comment.
P2: This assigns every pending transcription the full two-hour timeliness SLA, so Home can show “Transcribing…” for two hours instead of the documented normal 30-minute target. Cap the entry deadline at 30 minutes while retaining the two-hour SLA as the upper bound.
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_batch_pending.py, line 18:
<comment>This assigns every pending transcription the full two-hour timeliness SLA, so Home can show “Transcribing…” for two hours instead of the documented normal 30-minute target. Cap the entry deadline at 30 minutes while retaining the two-hour SLA as the upper bound.</comment>
<file context>
@@ -0,0 +1,19 @@
+ return {}
+ return {
+ 'episode_transcription_pending_at': pending_at,
+ 'episode_transcription_deadline_at': pending_at + timedelta(seconds=SLA_SECONDS),
+ }
</file context>
| 'episode_transcription_deadline_at': pending_at + timedelta(seconds=SLA_SECONDS), | |
| 'episode_transcription_deadline_at': pending_at + timedelta(seconds=min(SLA_SECONDS, 30 * 60)), |
| if isinstance(value, (int, float)) and not isinstance(value, bool): | ||
| if key == 'start': | ||
| started = datetime.fromtimestamp(value, timezone.utc) | ||
| else: | ||
| finished = datetime.fromtimestamp(value, timezone.utc) |
There was a problem hiding this comment.
P2: project_episode can turn malformed stored audio bounds into a Home 500: the numeric check admits NaN, infinity, and out-of-range timestamps, which datetime.fromtimestamp raises on. Catch conversion errors or validate the timestamp before replacing the displayed clocks.
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_read.py, line 313:
<comment>`project_episode` can turn malformed stored audio bounds into a Home 500: the numeric check admits NaN, infinity, and out-of-range timestamps, which `datetime.fromtimestamp` raises on. Catch conversion errors or validate the timestamp before replacing the displayed clocks.</comment>
<file context>
@@ -288,14 +293,38 @@ def project_episode(
+ ('start', row.get('server_batch_audio_start')),
+ ('end', row.get('server_batch_audio_end')),
+ ):
+ if isinstance(value, (int, float)) and not isinstance(value, bool):
+ if key == 'start':
+ started = datetime.fromtimestamp(value, timezone.utc)
</file context>
| if isinstance(value, (int, float)) and not isinstance(value, bool): | |
| if key == 'start': | |
| started = datetime.fromtimestamp(value, timezone.utc) | |
| else: | |
| finished = datetime.fromtimestamp(value, timezone.utc) | |
| if isinstance(value, (int, float)) and not isinstance(value, bool): | |
| try: | |
| converted = datetime.fromtimestamp(value, timezone.utc) | |
| except (OverflowError, OSError, ValueError): | |
| continue | |
| if key == 'start': | |
| started = converted | |
| else: | |
| finished = converted |
| "backend/tests/unit/test_episodes_service.py", | ||
| "app/test/widgets/l5_home_visibility_test.dart" | ||
| "app/test/widgets/l5_home_visibility_test.dart", | ||
| "backend/tests/unit/test_episode_batch_audio_close.py" |
There was a problem hiding this comment.
P3: test_episode_batch_audio_close.py does not exercise the sync-finalization hook or the Home folding contract described by this failure class; it only tests batch-close attachment. Remove it from canonical_prevention_artifact or add a regression test that drives the omitted sync path.
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 .github/failure-classes/FC-finalize-hook-allowlist-omits-ingestion-path.json, line 9:
<comment>`test_episode_batch_audio_close.py` does not exercise the sync-finalization hook or the Home folding contract described by this failure class; it only tests batch-close attachment. Remove it from `canonical_prevention_artifact` or add a regression test that drives the omitted sync path.</comment>
<file context>
@@ -5,7 +5,8 @@
"backend/tests/unit/test_episodes_service.py",
- "app/test/widgets/l5_home_visibility_test.dart"
+ "app/test/widgets/l5_home_visibility_test.dart",
+ "backend/tests/unit/test_episode_batch_audio_close.py"
],
"evidence_prs": [],
</file context>
| assert rule['uid'] == 'omi-episode-batch-pending-overdue' | ||
| assert rule['labels']['severity'] == 'info' | ||
| assert rule['labels']['tier'] == 'agent' | ||
| assert rule['data'][0]['model']['expr'] == 'sum(increase(omi_episode_batch_pending_overdue_reads_total[15m]))' |
There was a problem hiding this comment.
P3: This test does not check the alert's firing chain. Add assertions that rule['condition'] == 'E', that the reduce step consumes D, and that D's expression is $A > 0. Otherwise a miswired threshold passes while the alert never fires.
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_episode_batch_pending_alert.py, line 13:
<comment>This test does not check the alert's firing chain. Add assertions that `rule['condition'] == 'E'`, that the reduce step consumes `D`, and that `D`'s expression is `$A > 0`. Otherwise a miswired threshold passes while the alert never fires.</comment>
<file context>
@@ -0,0 +1,15 @@
+ assert rule['uid'] == 'omi-episode-batch-pending-overdue'
+ assert rule['labels']['severity'] == 'info'
+ assert rule['labels']['tier'] == 'agent'
+ assert rule['data'][0]['model']['expr'] == 'sum(increase(omi_episode_batch_pending_overdue_reads_total[15m]))'
+ assert rule['noDataState'] == 'OK'
+ assert 'not unique members' in rule['annotations']['scope']
</file context>
| ) | ||
| store.rows[('users', 'owner', 'episodes', result['id'])]['close_reason'] = reason | ||
| assert attachment.attach_closed_batch_capture('owner', 'capture', store.rows[path], collaborators=c) == 'attached' | ||
| assert store.rows[path]['episode_transcription_deadline_at'] |
There was a problem hiding this comment.
P3: This test's name says the deadline is gained atomically without reset, but it only asserts the deadline is truthy. Assert the exact deadline relative to the pending start (the 2h value the sibling tests check) and that the existing membership's values are unchanged.
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_episode_batch_audio_close.py, line 385:
<comment>This test's name says the deadline is gained atomically without reset, but it only asserts the deadline is truthy. Assert the exact deadline relative to the pending start (the 2h value the sibling tests check) and that the existing membership's values are unchanged.</comment>
<file context>
@@ -0,0 +1,385 @@
+ )
+ store.rows[('users', 'owner', 'episodes', result['id'])]['close_reason'] = reason
+ assert attachment.attach_closed_batch_capture('owner', 'capture', store.rows[path], collaborators=c) == 'attached'
+ assert store.rows[path]['episode_transcription_deadline_at']
</file context>
| outcome after a finalization dead letter, failed status/upload or deadline. | ||
| Successful late projection restores ordinary metadata; retained audio and retry | ||
| work are preserved. The read-observed overdue counter has no labels. Its info | ||
| alert is staged in `charts/monitoring/pending/episode-batch-pending.json`, |
There was a problem hiding this comment.
P3: This change note points to charts/monitoring/pending/episode-batch-pending.json, but the catalog is at backend/charts/monitoring/pending/episode-batch-pending.json. Correct the path so operators can locate the staged alert.
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-home-batch-close-deadline.md, line 9:
<comment>This change note points to `charts/monitoring/pending/episode-batch-pending.json`, but the catalog is at `backend/charts/monitoring/pending/episode-batch-pending.json`. Correct the path so operators can locate the staged alert.</comment>
<file context>
@@ -0,0 +1,20 @@
+outcome after a finalization dead letter, failed status/upload or deadline.
+Successful late projection restores ordinary metadata; retained audio and retry
+work are preserved. The read-observed overdue counter has no labels. Its info
+alert is staged in `charts/monitoring/pending/episode-batch-pending.json`,
+alongside batch timeliness monitoring, without provisioning.
+
</file context>
| alert is staged in `charts/monitoring/pending/episode-batch-pending.json`, | |
| alert is staged in `backend/charts/monitoring/pending/episode-batch-pending.json`, |
|
episodes batch 1: ships together as one train, CI red |
…ose attachment and batch-1 fast paths Combine the pending deadline write with the shared fenced transaction and canonical partition proof. Validate pending close replays against committed archive bounds and leave transcript-recovery memos to the sync path. Keep composer settling, Home read cuts, deduplicated membership and recovery reuse. Update the new sync callback and regression tests to the public attach helper; exercise replay idempotency with optimization rollback in strict and emulator transactions. Regenerate the merged feature flag catalog.
Include the independent record-seal repair fix from PR 24603. No conflicts or changes to the previously validated episode attachment resolution.
…rding Keep the stale hidden-member finalization proof compatible with the composer settle callback introduced on current main. Production behavior is unchanged.
Archive epochs can carry submicrosecond float precision while close admission normalizes them into Python datetimes. Compare the same normalized values on replay, keeping the canonical partition proof and all visibility guards. Cover integer and fractional epochs with attach optimizations both on and off in unit and real Firestore tests.
Release each test's Firestore channel at fixture teardown rather than retain it through later concurrency cases. Tests and transaction retry limits stay unchanged.
…close Retain the speaker carry and recording-scope routes from PR 24509 alongside the audio-close membership barrier. Regenerate the union flag catalog.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 817784dced
ℹ️ 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".
| try: | ||
| started = datetime.fromtimestamp(row['server_batch_audio_start'], timezone.utc) | ||
| finished = datetime.fromtimestamp(row['server_batch_audio_end'], timezone.utc) | ||
| c = collaborators or service.Collaborators(firestore_client=conversations.db) |
There was a problem hiding this comment.
Resolve the default Firestore client through its accessor
When no collaborators are supplied, this new attachment path passes conversations.db, the legacy compatibility proxy, into the timeline transactions. backend/AGENTS.md explicitly prohibits introducing new uses of that proxy and requires resolving the client with database._client.get_firestore_client() at call time. Use that accessor for the default collaborator while retaining the existing collaborator injection, so this new path follows the supported client-resolution boundary rather than extending the legacy dependency.
AGENTS.md reference: backend/AGENTS.md:L180-L180
Useful? React with 👍 / 👎.
| failed = ( | ||
| row.get('finalization_status') == 'dead_letter' or status == 'failed' or row.get('record_upload_failed') | ||
| ) | ||
| title = "Couldn't transcribe" if failed or overdue else 'Transcribing…' |
There was a problem hiding this comment.
Preserve user-authored titles on pending batch members
If a user renames a batch capture before its transcript arrives, this assignment replaces their saved title with Transcribing…; if transcription fails, it remains Couldn't transcribe indefinitely. database.conversations.update_conversation_title persists the override in user_title, and prepare_conversation_for_read reapplies it to structured.title, but this projection unconditionally overwrites that resolved title. Preserve a nonblank user title while still projecting the processing or failure status, so episode members respect the same durable rename as ordinary conversation reads.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
3 existing issues remain and 4 new issues found across 27 files
Confidence score: 3/5
episode_recorded_components.pycan attach a capture after its admission state changes because the membership transaction trusts a stale precheck. Revalidate the current conversation’s close-admission guards in the transaction.episode_timeline.pydropspending_patchon the cap-return path, so an eligible batch member can be attached without a transcription deadline. Apply the pending update before returning.home_read.pycan hide a user’s nonblank renamed title while projection is pending, or leave it hidden after projection fails. Preserve the resolved title in those statuses.test_episode_batch_audio_close.pydoes not verify the behavior its assertions claim to cover: one checks only that the deadline exists, and others inspect an untouched row. Assert against persisted state and verify the deadline andepisode_idremain unchanged after replay.
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/tests/unit/test_episode_batch_audio_close.py">
<violation number="1" location="backend/tests/unit/test_episode_batch_audio_close.py:192">
P3: These final assertions check the original `row`, which the controller never touches, so they always pass. Assert on the persisted state (the store or the object passed to `attach_recorded`) instead, or drop them.</violation>
</file>
<file name="backend/database/episode_timeline.py">
<violation number="1" location="backend/database/episode_timeline.py:110">
P2: The cap-return path drops `pending_patch`, so an eligible batch member can attach without `episode_transcription_deadline_at`. Add the pending update before this early return; otherwise Home cannot show the bounded transcription state or terminal failure after finalization fails.</violation>
</file>
<file name="backend/utils/episodes/home_read.py">
<violation number="1" location="backend/utils/episodes/home_read.py:306">
P2: Preserve a nonblank resolved title when projecting the pending or failure status; otherwise episode members hide the user's rename until projection succeeds, or indefinitely after failure.</violation>
</file>
<file name="backend/utils/episodes/batch_close.py">
<violation number="1" location="backend/utils/episodes/batch_close.py:49">
P3: Resolve the default Firestore client with `database._client.get_firestore_client()` instead of `conversations.db`; this path should not introduce another dependency on the legacy compatibility proxy.</violation>
</file>
Requires human review: Auto-approval blocked because this review re-detected 3 unresolved issues already reported by Cubic.
View guided diff | Turn on auto-fix | Re-trigger cubic
| members = episodes.read_memberships( | ||
| transaction, client, uid, [conversation_id], admit_conversation_id=conversation_id | ||
| ) | ||
| pending_patch = episode_batch_pending.read_patch(transaction, client, uid, conversation_id, pending_at) |
There was a problem hiding this comment.
P2: The cap-return path drops pending_patch, so an eligible batch member can attach without episode_transcription_deadline_at. Add the pending update before this early return; otherwise Home cannot show the bounded transcription state or terminal failure after finalization fails.
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_timeline.py, line 110:
<comment>The cap-return path drops `pending_patch`, so an eligible batch member can attach without `episode_transcription_deadline_at`. Add the pending update before this early return; otherwise Home cannot show the bounded transcription state or terminal failure after finalization fails.</comment>
<file context>
@@ -106,6 +107,7 @@ def attach(transaction):
members = episodes.read_memberships(
transaction, client, uid, [conversation_id], admit_conversation_id=conversation_id
)
+ pending_patch = episode_batch_pending.read_patch(transaction, client, uid, conversation_id, pending_at)
rows = (candidates or recorded_candidates)(
uid, started, finished, firestore_client=client, transaction=transaction
</file context>
| failed = ( | ||
| row.get('finalization_status') == 'dead_letter' or status == 'failed' or row.get('record_upload_failed') | ||
| ) | ||
| title = "Couldn't transcribe" if failed or overdue else 'Transcribing…' |
There was a problem hiding this comment.
P2: Preserve a nonblank resolved title when projecting the pending or failure status; otherwise episode members hide the user's rename until projection succeeds, or indefinitely after failure.
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_read.py, line 306:
<comment>Preserve a nonblank resolved title when projecting the pending or failure status; otherwise episode members hide the user's rename until projection succeeds, or indefinitely after failure.</comment>
<file context>
@@ -288,14 +293,38 @@ def project_episode(
+ failed = (
+ row.get('finalization_status') == 'dead_letter' or status == 'failed' or row.get('record_upload_failed')
+ )
+ title = "Couldn't transcribe" if failed or overdue else 'Transcribing…'
+ status = 'failed' if failed or overdue else 'processing'
+ # Audio bounds remain truthful even when finalization never filled its clocks.
</file context>
| title = "Couldn't transcribe" if failed or overdue else 'Transcribing…' | |
| title = title if title.strip() else ("Couldn't transcribe" if failed or overdue else 'Transcribing…') |
| controller.schedule_finalization.assert_awaited_once_with('capture') | ||
| fallback.assert_called_once() | ||
| assert fallback.call_args.kwargs['outcome'] == 'degraded' | ||
| assert row['episode_id'] is None and row['transcript_segments'] == [] |
There was a problem hiding this comment.
P3: These final assertions check the original row, which the controller never touches, so they always pass. Assert on the persisted state (the store or the object passed to attach_recorded) instead, or drop them.
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_episode_batch_audio_close.py, line 192:
<comment>These final assertions check the original `row`, which the controller never touches, so they always pass. Assert on the persisted state (the store or the object passed to `attach_recorded`) instead, or drop them.</comment>
<file context>
@@ -0,0 +1,392 @@
+ controller.schedule_finalization.assert_awaited_once_with('capture')
+ fallback.assert_called_once()
+ assert fallback.call_args.kwargs['outcome'] == 'degraded'
+ assert row['episode_id'] is None and row['transcript_segments'] == []
+
+
</file context>
| try: | ||
| started = datetime.fromtimestamp(row['server_batch_audio_start'], timezone.utc) | ||
| finished = datetime.fromtimestamp(row['server_batch_audio_end'], timezone.utc) | ||
| c = collaborators or service.Collaborators(firestore_client=conversations.db) |
There was a problem hiding this comment.
P3: Resolve the default Firestore client with database._client.get_firestore_client() instead of conversations.db; this path should not introduce another dependency on the legacy compatibility proxy.
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/batch_close.py, line 49:
<comment>Resolve the default Firestore client with `database._client.get_firestore_client()` instead of `conversations.db`; this path should not introduce another dependency on the legacy compatibility proxy.</comment>
<file context>
@@ -0,0 +1,62 @@
+ try:
+ started = datetime.fromtimestamp(row['server_batch_audio_start'], timezone.utc)
+ finished = datetime.fromtimestamp(row['server_batch_audio_end'], timezone.utc)
+ c = collaborators or service.Collaborators(firestore_client=conversations.db)
+ service.attach_recorded(uid, conversation_id, row, started, finished, c, pending_transcription=True)
+ return 'attached'
</file context>
The CI merge tree included #24544 after the preceding local gate. Its Home projection changes a status expression to an aliased processing/failed value. The stale inventory fails exactly that module before refresh. Preserve the source guard and update the one reviewed snapshot value. Validation: canonical six-file backend unit gate passes with 926 passes and 68 strict xfails; the stale-snapshot reproduction has one failure.
## What changed and why Harden the lifecycle guards so an inventory refresh cannot hide a new unstamped entry or an unmodeled state. Clearing a job and rebuilding it from an alias now invalidates old deadline evidence; mutated aliases and opaque patches cannot restore it. A separate census compares persisted entries with the declarations for every deadline-bearing machine. Positional setdefault values and literal aliases enter the state-vocabulary check. Valid stamped rebuilds, declared entries and debt-clearing exits remain accepted. The existing span-only patch has a checked four-field return contract with portable AST fingerprints; source changes, overlapping keys and shadowed names fail the proof. This remains bounded source analysis, not whole-program execution or runtime liveness acceptance. Preserve the existing changed-file test coverage and select scheduler regressions. Recognize actual PhaseMetrics instances using Gauge suffixes declared by the real factory. Use the fresh-cohort BYOK gauge queried by its page. The source audit at main563e6c240944 also removes the two stale record_pending metric/page xfails supplied by #24595; #24587's admission lease still leaves an overall pending-dwell deadline gap. The table has 54 rows and 66 remaining clause-specific gaps, plus 2 pure synthetic ordering counterexamples (68 strict xfails). Expected failures allow AssertionError only. The report tracks each remaining dependency; simulator-backed transition/shadow/property rows remain B2 after merged WP-A and rollout-owner go. ## Product invariants affected none ## How it was verified From the product checkout, use the durable file list in the workspace evidence record: ```bash unset GOOGLE_APPLICATION_CREDENTIALS CLOUDSDK_CONFIG CLOUDSDK_CORE_PROJECT CLOUDSDK_AUTH_ACCESS_TOKEN_FILE GOOGLE_CLOUD_PROJECT export BACKEND_PYTEST_WORKERS=1 BACKEND_UNIT_TEST_FILE_LIST="$TASK_WORKSPACE_ROOT/data/run-2026-11-04-lifecycle-invariants/evidence/backend-unit-files.txt" "$TASK_WORKSPACE_ROOT/bin/omi-heavy" run -- nice -n 19 bash backend/test.sh ``` `TASK_WORKSPACE_ROOT` is the verified omi-workspace checkout. Dated evidence: `data/run-2026-11-04-lifecycle-invariants/README.md`. The six-file gate was rerun after integrating main through `c8304ee6e8cd`; its two new finalization writers and bounded queued entry are registered. A later main integration adds #24544's reviewed Home status projection to the inventory. Before that one-value snapshot refresh, the local writer suite reproduced exactly one failure for `home_read.py`; afterward the unchanged six-file gate passes again. With five cloud credential/project variables unset and one worker, backend/test.sh passed 926 tests with 68 strict xfails across the two lifecycle files and four existing selector/ratchet controls. The 23 targeted regression/control cases passed. The unmasked invariant run produced exactly 68 AssertionErrors and 201 passes; the exact case set matches 66 KNOWN_GAPS + 2 ordering cases, with no unexpected or CPU guard failures. Timing and slot limits were unchanged. Before the fixes, 12 review reproductions failed (3 setdefault cases, clear+alias, 8 deadline-bearing states). An additional mutated source-alias case also failed. Canonical patch-proof fingerprints match under Python 3.11.15 and 3.14.6. These are source/unit checks without network or GCP. Exact-head fullCI and rollout-owner acceptance are required before merge. ## Tests Payload writer/value/key/alias/duplicate inventory; state vocabulary; all-class entry census; deadline mutation lifetime; verified patch boundary; positive entry/rebuild/exit controls; selector coverage preservation; source-defined metrics; clause-specific strict xfails; pure synthetic ordering controls. ## UI evidence UI-Evidence: none -- test infrastructure only ## Failure class (fixes) Failure-Class: none ## New guards Lifecycle source changes cannot silently add the covered payload forms, persisted entries or literal state values without revisiting the declared contract. Source-derived metrics stay tied to their committed alert expressions. ## Tracking Owner: lcinv. ANX card:lcinv-lifecycle-invariants under capture/transcription. No product/.github/firmware/account-data changes and no deploy needed.
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_ENABLEDdefaults 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 publicattach_recordedhelper. The final speaker-tip merge was clean; the core episode resolution is unchanged.Validation at
817784dced26: 858 passed across 21 focused backend files throughbackend/test.shwith 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 throughomi-heavyat 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
cf601889c67band exact candidateb8633977345c. 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-warningssuppressed 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 preflightpassed 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.