Repository navigation
fix(episodes): live notes name people, never raw diarization ids - #23404
Conversation
…diarization ids
A live episode's "So far" bullets read "Speaker 379 mentions..." because the
legacy live-moment renderer wrote the raw per-conversation diarization counter
into the prompt ("Speaker 379: ...") and the summarizer copied the label
verbatim into user-visible notes (#23381). The finished-notes v2 path already
renders cluster keys, so it never had the problem.
Add utils/speaker_display.SpeakerLabeler and route every LLM-facing or
user-facing transcript renderer through it: the owner renders as "You" or the
owner's name (live moments now resolve the account's display name), named
people keep their names, and every unnamed voice gets a dense per-transcript
"Speaker A/B/..." label in first-appearance order, keyed by
(speaker_id_scope, speaker_id) so merged multi-source transcripts stay
distinct. Raw diarization ids no longer reach any prompt or payload:
- live moments: incremental.speaker_label/_legacy_moment (+ moment rules now
forbid copying voice markers or placeholder headings like "New moment")
- TranscriptSegment.segments_as_string (titles, memories, summaries, chat)
- transcript_for_llm action-item speaker labels
- shared-chat bounded transcripts, smart-merge question excerpts, retrieval
chunks and MCP match snippets, review quotes
- conversation analytics and populate_speaker_names (MCP/integration/webhook
payloads)
Bump smart-merge QUESTION_VERSION: cached adjacent-merge answers were keyed to
the old raw-id excerpts.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Two guards so "Speaker 379" cannot come back:
- unit: run each LLM-facing formatter with the incident's raw ids (378/379,
across scopes) and assert the digits never survive a render; covers
segments_as_string, live and v2 moment renderers, cluster transcripts,
smart-merge lines, shared-chat bounded transcripts, MCP snippets, retrieval
chunks, action-item labels, populate_speaker_names and analytics.
- static: check_speaker_label_interpolation.py rejects any new interpolated
"Speaker {speaker_id}" (f-string, .format, %, concatenation) outside the
sanctioned SpeakerLabeler; registered in checks-manifest with a self-test.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
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: dd347bfb70
ℹ️ 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 segment.get('is_user'): | ||
| return 'Owner' | ||
| return owner_name |
There was a problem hiding this comment.
Keep owner and participant turns distinct when names match
When the owner and an identified participant share the same display name, returning the owner's name here gives both voices the same label. In the default legacy-serving path, _legacy_moment coalesces consecutive turns solely when their label strings match, so adjacent owner/participant speech is merged into one apparent turn and can be misattributed by the live-note model. Preserve a distinct owner marker such as You, or coalesce using voice identity rather than the rendered label.
Useful? React with 👍 / 👎.
| speaker_id = getattr(seg, 'speaker_id', None) | ||
| if speaker_id is not None: | ||
| return (f'speaker:{speaker_id}', f'Speaker {speaker_id}', None, False) | ||
| return (f'speaker:{speaker_id}', labeler.label(voice_key(seg)), None, False) |
There was a problem hiding this comment.
Include speaker scope in the analytics aggregation key
For merged or multi-source conversations where two voices reuse the same numeric speaker_id under different speaker_id_scope values, the labeler correctly assigns separate labels but this grouping key still collapses both voices. The later segment overwrites labels[key], while talk time and words remain combined, producing an incorrect speaker count and attributing the aggregate to only the later dense label. Build the aggregation key from voice_key(seg) as well.
Useful? React with 👍 / 👎.
| text = incremental.render_moment( | ||
| named, uid=uid, conversation_id=moment.conversation_id, owner_name=_owner_name(uid, c) | ||
| ) |
There was a problem hiding this comment.
Avoid retrying unresolved owner-name lookups per moment
For an account without a resolvable display/profile name, _owner_name(uid, c) performs the Firebase/Firestore lookup and returns None, after which render_moment treats that value as if no lookup was attempted and calls _resolve_owner_name(uid) to perform the same lookup again. Thus every pause or finalize update for unnamed users incurs two remote identity lookups before the model call; pass an explicit resolved-state sentinel or avoid the fallback lookup when the service already resolved the name.
Useful? React with 👍 / 👎.
| def label(self, key: Hashable) -> str: | ||
| label = self._labels.get(key) |
There was a problem hiding this comment.
Normalize raw voice keys before dictionary lookup
Several new callers pass fields from decoded Firestore segment dictionaries directly through voice_key; these dictionaries are consumed before response-model validation, so a malformed or legacy speaker_id/speaker_id_scope containing a list or dictionary makes the tuple unhashable and this lookup raises TypeError. For example, populate_speaker_names now crashes an entire developer conversation page before its existing per-record validation can skip the bad document, whereas the old f-string accepted such values. Validate or normalize the key before using it in _labels.
Useful? React with 👍 / 👎.
Git-on-my-level
left a comment
There was a problem hiding this comment.
FIX — Sol / P88, round 1, exact head dd347bfb7064569fc7408eb81e9eab88a7f919f2 (direct sprint-bus request).
[P1] Preserve the source-binding attribution contract when labels become scope-aware — backend/models/transcript_segment.py:380. The production renderer now distinguishes (speaker_id_scope, speaker_id), but transcript_sha256_for_binding still accepts v5 identity frames that omit speaker_id_scope. With two unnamed turns having speaker='SPEAKER_00', speaker_id=0, is_user=False, and identical stored words, changing only the second turn's scope from source-a to source-b changes the rendered attribution from Speaker A / Speaker A to Speaker A / Speaker B; both stored transcripts nevertheless remain canonical and produce the same non-null binding digest. A projection computed before that voice split can still pass _accepted_client_projection / bind_client_processing_updates after it, despite describing a different attribution. The existing hash-contract test changes its expected labels but does not cover a scope-only mutation.
Add this two-turn regression and make scope-changing attribution fail the projection binding (or introduce an explicitly versioned compatible binding that includes scope). Do not silently change the released v5 byte framing. Keep the dense display labels and the original transcript/speaker fields.
I reviewed the ten renderer migrations, MCP/webhook speaker_name shape, smart-merge iv2 cache invalidation and AST guard. No other P0/P1 finding. Existing automated P2 comments are outside this pool's blocking bar. This finding is supported by the exact-head renderer and hash/binding code; its standalone offline probe is queued behind omi-heavy, not reported as a passing runtime test. No merge/deploy performed. Fix re-review should cover only the delta.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 20fa13dd4b
ℹ️ 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".
| except Exception: | ||
| return None |
There was a problem hiding this comment.
Instrument the owner-name fail-open paths
When owner-name resolution raises, this handler silently returns None, and render_moment continues with You instead of the resolved identity. The new _owner_name handler in service.py likewise continues after logging, but neither path calls the shared fallback helper. Consequently, degraded identity resolution is absent from omi_fallback_total. Emit record_fallback with a degraded outcome for these exception paths; an ordinarily unnamed account need not count as a fallback. This is required by the new-fallback rule in backend/AGENTS.md.
AGENTS.md reference: backend/AGENTS.md:L315-L315
Useful? React with 👍 / 👎.
models.transcript_segment imports SpeakerLabeler at module scope, and test_action_item_date_validation stubs utils as a package with an empty __path__, so the isolated models.conversation load failed at collection with ModuleNotFoundError on this branch. Load the real stdlib-only module before the models load, mirroring utils.model_text, and snapshot it for restore. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Update stale rollout expectations and exercise both workload-only and rollback metric policies without changing runtime configuration. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Remove the unpublished duplicate repair before integrating the now-green main baseline. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 87c83fd50a
ℹ️ 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".
| people_map = {person.id: person.name for person in people} if people else {} | ||
| # Dense per-transcript labels: the raw speaker_id is a diarization counter that reaches | ||
| # the hundreds and must never reach an LLM prompt (#23381). | ||
| labeler = SpeakerLabeler() |
There was a problem hiding this comment.
Preserve the labeler across addressable transcript segments
When chat retrieval requests a transcript with addressable references, conversations_to_string in backend/utils/conversations/render.py calls segments_as_string([segment], ...) separately for every segment. Creating the labeler here resets it on each call, so all unnamed voices become Speaker A, even when their speaker IDs differ. This path is used by _render_addressable_conversations in backend/utils/retrieval/tools/conversation_tools.py, so the chat model loses speaker distinctions in retrieved conversations. Share a conversation-scoped labeler across these calls or render the referenced segments together.
Useful? React with 👍 / 👎.
| class SpeakerLabeler: | ||
| """Assigns dense "Speaker A/B/..." labels to unnamed voice keys, first appearance order.""" |
There was a problem hiding this comment.
Update the required speaker pipeline documentation
This change introduces a shared speaker-display policy and owner-name resolution for live episodes, but does not update backend/docs/listen_pusher_pipeline.mdx. backend/AGENTS.md explicitly requires that document to be updated in the same PR for speaker changes. Document the dense, scope-aware display labels and owner-name fallback there so the pipeline contract reflects the new behavior.
AGENTS.md reference: backend/AGENTS.md:L159-L159
Useful? React with 👍 / 👎.
…#23828) ## What changed and why Fix three P1 episode/projection failures identified in #23404 and #23418. Client projection binding now rejects mixed scopes among unnamed voices while preserving hash encoding v5. WAL attachment and sync finalization merge recovered member speech into running notes with transactional content receipts; close rechecks recovered member transcripts for unapplied speech. Attachment retries version conflicts three times with jitter and fresh reads, and saturated episode hooks retain bounded deferred admission until capacity returns. Recovered text uses bounded batches so prompt truncation cannot acknowledge unseen words. Complete live prompt input and recovery share content-revision receipts, so WAL appended to the same canonical conversation skips proven live speech and preserves novel gaps. Donor repointing transfers receipt namespaces with the membership CAS inside the retry owner; absorb finalization reads the survivor's current transcript. Canonical ingest binding uses the same scope guard as persisted binding. Existing EPISODES and LIFECYCLE flags and defaults are preserved. Failure-Class: FC-once-only-trigger-dropped-at-capacity The admission regression is a once-only trigger lost at capacity. Companion tests cover missing scope in v5 binding and recovered speech incorrectly treated as already consumed. ## Product invariants affected INV-TASK-2: episode updates retain provisional items and never write action items, Candidates, or memories. Customer identity and serving-plane authorities are preserved (INV-DATA-1). ## How it was verified - Local backend shard through `BACKEND_UNIT_TEST_FILE_LIST=/Volumes/Ephemeral/scratch/p88fix/regressions.txt BACKEND_PYTEST_WORKERS=1 bin/omi-heavy run -- nice -n 19 bash backend/test.sh` (workspace `bin/omi-heavy`): all 16 targeted files passed again after the round-two corrections, including 78 episode-service cases, ingest trust/idempotency and the background-task inventory ratchet. - Fail-before/pass-after: corrected regressions run against base production sources `5f2caea10a6` fail on mixed-scope binding, lost recovered notes/close rebuild, two CAS conflicts, and saturated final hooks. The candidate passes those regressions. - `bin/omi-heavy run -- nice -n 19 make preflight`: all 35 repository checks passed (389 seconds), including Firestore guards, runtime source closure, async blocking, import purity, metadata, and file-size gates. - `bin/omi-heavy run -- nice -n 19 bash backend/scripts/typecheck.sh`: canonical full backend type check, zero errors. - `bin/omi-heavy run -- nice -n 19 bash backend/testing/sync_cloud_tasks_stack/run.sh --only sync --state-dir /Volumes/Ephemeral/scratch/p88fix/sync-stack`: hermetic Sync Cloud Tasks gauntlet passed with real local Firestore/Redis and separate admission/worker processes; sanitized evidence retained. - Read-only Luna rounds 1 and 2 returned FIX-FIRST; their findings were corrected with fail-before/pass-after regressions. Under acknowledged lead ruling `2fedac`, no third review runs: acceptance is corrected-head CI plus the regression mapping for the lead's delta review. Terminal CI and that mapping will be attached before handoff. These are source, hermetic unit, and local harness claims. Product deployment and production acceptance belong to the lead's release train. ## Tests - `test_transcript_hash.py`: dict/model scope-only attribution correction, legacy unscoped mix, bound owner/person compatibility, v5 unchanged. - `test_client_processing_finalize.py`: router and transactional binding reject the stale digest while finalization fields survive. - `test_episodes_service.py`: recovered speech at attach, idempotent replay, existing member gap behind an applied offset, close after a provider failure, three fresh CAS attempts retaining concurrent members, full long-transcript prompt coverage in served/legacy modes, preserved speaker-evidence IDs, and ordinary-finalize/unplaced-slice failure receipts. - `test_episodes_finalize_paths.py` and `test_executors.py`: saturated final/intake hooks run without another append, context survives, errors surface, cancelled and shutdown work stays bounded. - Review regressions fail at `0b0e740ae3c` and pass after correction: canonical ingest scope guard, same-row live/WAL consumption, donor receipt transfer, and fresh donor CAS attempts. The merged-survivor finalization test also proves only novel survivor speech reaches the model. - `test_background_task_ratchet.py`: both retry APIs remain subject to caller inventory; returned cast-wrapped futures transfer ownership while done callbacks alone remain detached. The new regression fails before correction; all six scanner cases pass afterward. - Round-two regressions fail at `90f2eff0f13` and pass after correction: absorbed callback survives two fresh CAS conflicts, legacy-only donor receipts prevent replay, and transferring 50,000 content receipts bounds every archive to 2,000 IDs while retaining order and all proof. ## Risks and rollout Recovery can add notes-model calls for retained WAL snapshots whose prior live consumption cannot be proved. Older placed cursor-only state cannot distinguish an old line from a new gap behind that cursor, so its first recovery conservatively merges the retained snapshot once. Legacy unplaced-ID receipts remain proof; new live content receipts prevent replay. Updates merge into the existing compact state. The deferred queue is process-local like the ordinary executor queue, capped at 64 pending submissions with synchronous producer backpressure when full; shutdown cancels it. Its documented background-task inventory entry retains the existing best-effort episode-overlay lifetime over durable source conversations. No new queue infrastructure or migration is required. Lead-owned backend/listen/pusher release train required after merge. No production access or mutation was used in this lane.
What
A live episode's "So far" summary read "Speaker 379 mentions…", "Speaker 378 notes…" — raw per-conversation diarization counters shown as if they were people (same footgun as the "343 people" live row fixed app-side in #23379). Live moment headings could also degenerate to a placeholder ("New moment"). This fixes every backend transcript formatter at the source: a raw diarization id can no longer reach an LLM prompt or user-visible text.
Root cause
The finished-conversation notes path (notes v2) renders cluster-key transcripts (
[<segment-id> c0] text) with no copyableSpeaker N:labels, which is why finished notes said "a speaker said…". The live episode path, however, renders moment text throughincremental._legacy_moment→speaker_label(backend/utils/episodes/incremental.py), which formatted each unnamed voice asSpeaker {speaker_id}— a per-conversation diarization counter that reaches the hundreds in a long conversation. The summarizer copied the dialogue label verbatim into bullets, people and moment headings.NOTES_PACKET_V2_MODEdefaults toshadow, so the legacy renderer served this episode.The same
Speaker {id}pattern existed in nine more formatters:TranscriptSegment.segments_as_string, action-item speaker labels, shared-chat bounded transcripts, smart-merge question excerpts, retrieval chunks, MCP transcript snippets, review quotes, conversation analytics, andpopulate_speaker_names(MCP/integration/webhook payloads)."New moment" is not a code default (the string exists nowhere in the repo): the app shows
moment.headingor falls back to the episode title, and the model returned the placeholder itself for low-signal audio. The moment rules now forbid placeholder headings explicitly.Fix
One shared labeler,
backend/utils/speaker_display.py:get_user_nameprecedence (fail-open to "You");(speaker_id_scope, speaker_id)so merged multi-source transcripts keep voices distinct.All ten formatters route through it. The moment prompt rules additionally tell the model that dialogue labels are voice markers, never names, and that titles must name the topic, not a placeholder. Smart-merge
QUESTION_VERSIONbumps toiv2because cached adjacent-merge answers were keyed to the old raw-id excerpts.Guards
backend/tests/unit/test_speaker_display_no_raw_ids.py— runs every LLM-facing formatter with the incident's raw ids (378/379, across scopes) and asserts the digits never survive a render..github/scripts/check_speaker_label_interpolation.py— zero-tolerance AST check (f-string /.format/%/ concatenation) rejecting any new interpolatedSpeaker {id}outside the sanctioned labeler; registered in.github/checks-manifest.yaml(local + ci lanes) with a--self-test, no new workflow.Tests
Focused backend suites via
BACKEND_UNIT_TEST_FILE_LIST bash test.sh: 51 test files across three batches, all green — including the formatter suites (episodes incremental/service, notes packet v2, transcript segment, smart-merge state, shared chat, MCP search/rest, transcript chunks/canonicalization/hash, owner attribution, working observations, user-name resolution, analytics, render factory, folder enrichment, relevance Jev, review). Updated 16 existing tests whose expectations pinned the old raw-id labels; the transcript-hash digest contract itself is unchanged (it binds raw ids by design and is not display text).Failure-Class: FC-generated-presentation-contract-bypass
Product invariants affected
none — no tracked invariant covers transcript label formatting; the speaker-naming authority for app UI (dense ordinals, #23379) is unchanged, and this PR brings backend prompt labels to the same no-raw-ids contract.
Deploy note
Backend deploy only (Cloud Run/GKE backend release). No listen/pusher change, no app build required: episode bullets, moment headings and
speaker_namefields are backend-generated.🤖 Generated with Claude Code