Skip to content

fix(backend): dedupe unidentified live+sync overlap and reuse known speaker IDs (#23364) - #23381

Merged
Git-on-my-level merged 7 commits into
BasedHardware:mainfrom
ocakciomursel-pixel:fix/sync-live-overlap-speaker-dedupe-23364
Oct 27, 2026
Merged

Git-on-my-level merged 7 commits into
BasedHardware:mainfrom
ocakciomursel-pixel:fix/sync-live-overlap-speaker-dedupe-23364

Conversation

@ocakciomursel-pixel

@ocakciomursel-pixel ocakciomursel-pixel commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Fix live/offline transcript overlap without collapsing different unidentified voices or renumbering a committed scoped voice on replay.

  • Reuse known identities only for new legacy sync scopes; persisted scope bindings and batch acoustic/manual authority win.
  • Join anonymous live windows only for the same persisted scoped voice. Fuzzy matches require compatible duration and a unique live occurrence, preserving genuine repeated speech.

Validation: combined integration of #23435/#23461/#23463 plus this branch passed 143 focused backend tests, backend typecheck (0 errors), and 56 unchanged Flutter speaker/playback mapping and widget tests. PCM/Firestore integration tests use synthetic audio and real assignment/receipts; fake player I/O does not qualify native audible playback. Standalone and preflight evidence is recorded below.

Draft: exact-head GitHub CI is unverified (Code Review requires GitHub reconnection). The private frozen audio, speaker truth, enrollment and model receipts used by #23461/#23463 are absent here; last measured speaker-quality gates still fail. These safety fixes do not establish model accuracy or Mike's recovery. No deployment or customer-data changes. Related quality work remains #23461 and #23463; backend merge and deployment are still required.

Failure-Class: FC-offline-merge-clock-offset-dup
Refs #23364
Refs #22755
Keep #23364 open for the wider quality and released-build acceptance; this overlap fix alone does not close Mike’s complete report.

Combined runtime verification: all 87 tests in backend/tests/integration/test_batch_pipeline_projection_firestore.py passed on loopback Firestore 1.21.0 (Python 3.11.15). This includes chronological ordering, competing transactions, restart/replay, manual and privacy authority, multipart PCM seeks and the real HTTP sync-status boundary. Four original failures reproduced on unchanged main c10d3ca; fixture fixes retain existing contracts rather than altering production retry or quality rules.

Standalone branch verification: 63 allocator/sync safety tests through backend/test.sh and 37 replay-tool tests passed. Pinned Python 3.11.15 backend typecheck: 0 errors.

Reproduction commands (from the repository root, after make setup; loopback emulator only):

printf '%s\n' tests/unit/test_stt_speaker_identity.py tests/unit/test_safety_wal_dual_write.py > /tmp/mike-tests.txt
BACKEND_UNIT_TEST_FILE_LIST=/tmp/mike-tests.txt BACKEND_PYTEST_WORKERS=2 bash backend/test.sh
PYTHONPATH=backend backend/.venv/bin/python -m pytest backend/tests/unit/test_sync_live_dedupe_replay_tool.py -q
(cd backend && PYTHON=.venv/bin/python bash scripts/typecheck.sh)
OMI_PR_BODY_FILE=/path/to/this-pr-body.md make preflight

Local manifest preflight: 32 selected checks passed. The failure-class history ratchet reports a local shallow-history skip, so its full-history CI verdict remains unqualified. No Release Eligibility or remote CI pass is claimed.

Published head: bf45fc2; normal bounded pre-push gate passed.

…peaker IDs across sync scopes (BasedHardware#23364)

- Allow unidentified speakers (person_id=None, is_user=False) to corroborate clock offsets, join consecutive live windows in _live_windows, and dedupe in _fuzzy_survivors while preserving separation between known and unknown speakers.
- Reuse conversation-local speaker_id for already-identified owner (is_user=True) and known person (person_id) segments across sync scopes in ConversationSpeakerIdAllocator instead of minting a fresh speaker_id on every uploaded sync chunk.
- Add unit tests covering unidentified speaker overlap deduplication, multi-segment live window joining, and cross-scope known speaker ID reuse.

Failure-Class: FC-offline-merge-clock-offset-dup
Fixes BasedHardware#23364
Fixes BasedHardware#22755
@ocakciomursel-pixel
ocakciomursel-pixel force-pushed the fix/sync-live-overlap-speaker-dedupe-23364 branch from c49b727 to defe5d1 Compare October 23, 2026 09:02
@Git-on-my-level

Copy link
Copy Markdown
Member

Verdict: correct and well-scoped fix for both regressions; leaving formal sign-off to a human maintainer because this widens the deletion predicate in the live+sync merge path.

  • backend/utils/sync/merge_dedupe.py — _both_unidentified_speaker / _compatible_speaker is the right shape: an owner (is_user=True) still never matches an unidentified segment, and known persons still only match themselves; matching widens only when both sides carry no identity. The change stays confined to the fuzzy_live_overlap fleet path (_live_windows and both phases of _fuzzy_survivors); the exact-range and text+slop paths are untouched. The existing guards (unique-anchor requirement, >=2 anchors agreeing within 2s, the 8-token minimum in fuzzy_live_match, 2s deletion tolerance) still bound the new matching.
  • backend/utils/stt/speaker_identity.py — _owner_speaker_id / _person_speaker_ids reuse directly fixes the per-chunk ID minting across sync:<job>:0 scopes. Skipping speaker_label_source == 'carried' and the sentinel 99 in _remember_identity is the right conservative call, and the setdefaults keep hydrate-time bindings authoritative.
  • backend/tests/unit/test_safety_wal_dual_write.py — reproduces the exact Hundreds of speakers and duplicated lines on 1-on-1 conversations (regression since Sept), plus one visit split into many conversations #23364 shape: owner line too short (<8 tokens) to anchor, two consecutive unidentified live windows joined, offset corroborated by two anchors, only the genuinely new line surviving.
  • backend/tests/unit/test_stt_speaker_identity.py — pins owner reuse across two sync scopes, person reuse, and that a genuinely unknown speaker still mints a fresh ID (12).

Notes:

  • UX: 1-on-1 conversations with an unidentified second speaker stop getting every non-owner line duplicated after offline sync, and speaker counts stop inflating per uploaded chunk.
  • Blast radius: a wrong drop would need two different unidentified people in one conversation saying near-identical >=8-token lines within ~2s of the corroborated clock offset — narrow, but real in group settings.

Still wanted (non-blocking): a >=3-party test with distinct unidentified speakers asserting a repeated common phrase is not dropped; a hydrate case where persisted history already holds multiple stale owner IDs, pinning which one the first-wins _owner_speaker_id keeps.

USER IMPACT: conversations with unidentified speakers no longer show duplicated lines or inflated speaker counts after syncing offline recordings with live transcripts.

Human review: the merge-dedupe deletion predicate now treats any two unidentified segments as compatible — maintainer sign-off on that multi-party trade-off before merge would be good.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@Git-on-my-level Git-on-my-level added backend Backend Task (python) needs-maintainer-review Needs a human maintainer to sign off before merge labels Oct 23, 2026
@aryanorastar
aryanorastar marked this pull request as draft October 24, 2026 04:15
Failure-Class: FC-offline-merge-clock-offset-dup

Verified 63 file-isolated tests through backend/test.sh; combined projection/arbitration and fractional PCM seek checks also passed against the local Firestore emulator. Frozen speaker-quality benchmark remains unverified; keep related PRs draft.
Keep the standalone overlap PR independent of the later voice-link API. Exercise repeated assign behavior directly.

Failure-Class: FC-offline-merge-clock-offset-dup
Git-on-my-level added a commit that referenced this pull request Oct 24, 2026
)

* fix(episodes): every LLM transcript labels voices densely, never raw 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]>

* test(backend): guard every LLM formatter against raw speaker-id labels

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]>

* test(backend): pre-load utils.speaker_display for isolated models load

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]>

* test(parakeet): align Helm contracts with floor-8 rollout

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]>

* test(backend): defer Helm contract repair to main #23472

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]>
@Git-on-my-level

Copy link
Copy Markdown
Member

Verdict: the production change is sound and conservatively guarded — the red Backend unit suite on this head is a pre-existing main breakage, not from this diff (verified: the same five test_parakeet_helm_contract.py failures occur on main 4b4e35f, the exact base your CI merged into; main has since gone green again).

File-by-file:

  • backend/utils/stt/speaker_identity.py — reuse ordering is correct: the persisted (scope, speaker) binding is consulted before any identity hint, so a later hint can never renumber a committed voice (test_persisted_scope_binding_wins_over_a_later_owner_hint pins this). Gating reuse to str(scope).startswith('sync:') and skipping speaker_label_source == 'carried' matches the stated intent. One consequence to keep in mind: _remember_identity also fires for final:batch: assignments, so a batch owner allocation can establish _owner_speaker_id for later sync reuse — the owner-unification looks intended, but it is the one cross-scope bridge worth a maintainer's eye.
  • backend/utils/sync/merge_dedupe.py — _compatible_speaker widening fuzzy dedupe to unidentified↔unidentified pairs is the actual fix, and the two new guards are the right defenses against dropping genuine speech: _duration_compatible (duration ratio ≤ 0.25) and the unique-occurrence check that discards candidates when {item['members']} is not a single set. _same_live_voice requiring equal speaker_id AND speaker_id_scope for anonymous joins is correctly strict; the sentinel is excluded both explicitly and by the equality check.
  • Robustness nit: _duration_compatible indexes left['end'] / left['start'] / right['duration'] directly while the surrounding code is .get-defensive — an incoming segment missing start/end would now raise KeyError inside the merge path. Consider defensive reads or an explicit input contract.
  • backend/tests/unit/test_stt_speaker_identity.py + test_safety_wal_dual_write.py — good adversarial coverage: duration-mismatched text kept, repeated occurrences kept, batch abstention preserved, anonymous windows not joined across different scoped voices.
  • backend/docs/listen_pusher_pipeline.mdx — each claim in the new paragraph matches the code (sync-only reuse, carried-label exclusion, batch registry authority, duration + unique-occurrence requirements).

Performance: no new queries or external calls; the added checks are O(1) per candidate pair.
USER IMPACT: conversations where a live session and a later synced recording overlap should stop showing duplicated unidentified speech, and speaker numbering stays stable across sync uploads instead of minting a new speaker for every chunk.

Still wanted before this leaves draft: (1) rebase/CI re-run on the now-green main so the unit suite reflects this diff rather than the helm-contract breakage; (2) defensive .get handling (or a stated contract) for _duration_compatible inputs; (3) keep the maintainer sign-off this already carries — transcript-merge semantics can silently drop user speech if these guards ever regress, so a human should own that risk before merge.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@ocakciomursel-pixel

ocakciomursel-pixel commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks @Git-on-my-level! Updated in 86c019aaa2:

  1. Merged current main so the Backend unit suite runs on the fixed test_parakeet_helm_contract.py baseline.
  2. Made _duration_compatible in backend/utils/sync/merge_dedupe.py .get(...)-defensive (catching (TypeError, ValueError) and returning False when start, end, or duration is missing/None) and added unit assertions in test_unknown_fuzzy_match_requires_compatible_duration.

@ocakciomursel-pixel
ocakciomursel-pixel marked this pull request as ready for review October 24, 2026 14:19
Git-on-my-level added a commit that referenced this pull request Oct 25, 2026
…23462)

* fix(episodes): every LLM transcript labels voices densely, never raw 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]>

* test(backend): guard every LLM formatter against raw speaker-id labels

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]>

* fix(speakers): add typed identity, count and presentation guardrails

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

* chore(api): refresh speaker display contract snapshot

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

* chore(clients): regenerate safe speaker metadata types

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

* docs: align historical reload pointer with main

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

* fix(notes): People names bind to a speaker only with this conversation's evidence

A People record, lexicon spelling, profile, memory or old meeting can no longer
authorize a participant name. Calendar attendees overlapping the conversation,
this conversation's roster/tile names and affirmative owner corrections still do.
Enforced in the persisted notes contract independent of packet rollout; agent
output is repaired, unsupported names become "a speaker" or hedged heard names.

Failure-Class: notes-identity-leak

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

* fix(notes): type identity name lists for the backend typecheck

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

* test(speakers): repair CI loaders and canonical display assertions

Load the real speaker presentation modules in the isolated date-validation harness, expect canonical c0 keys in wake-word rendering, and remove the duplicate Dart test import.

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

* test(app): drop duplicate import in speaker names test

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

* test(backend): wake-word renderer expects opaque speaker prompt keys

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

* fix(notes): defer known_spellings import so isolated models loads stay light

notes_packet imported known_spellings at module scope, pulling the dream
store and People database into every conversation_processing import; the
isolated action-item test then failed at collection. Import it at the call,
and pre-load the speaker display modules the models now import.

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

* test(backend): isolate spelling database reads in date harness

Load the real known-spelling helper with explicit empty database adapters so notes-packet imports do not pull the dream-agent runtime into action-item date tests.

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

* fix(app): count distinct participant identities with shared names

Deduplicate named participants by People record ID so repeated diarization IDs count once while different people with the same display name retain separate participant counts. Preserve the existing transcript heading regression assertion.

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

* test(backend): remove adapters superseded by lazy spelling import

The published notes packet repair now defers its database-dependent spelling import until it is used. Keep the date harness minimal instead of eagerly loading the helper with extra database mocks.

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

* perf(test): avoid counter subprocesses in isolated worker polling

Keep the active worker count in the parent shell and update it with the existing PID arrays. Every 20ms polling iteration previously forked twice for command substitution merely to count workers. File isolation, status handoff, crash detection and timing budgets remain intact.

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

* test(ci): retain main full-scan speaker exemption boundary

The canonical identity authority passes the full raw-speaker scan without an extra exemption. Keep main full-scan coverage unchanged alongside the broader changed-file identity ratchet.

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

* test(backend): preserve distinct labels in whole-transcript hash assertion

Main changed this regression to render all segments in one transcript. Retain its stronger A/B and six-distinct-output assertions; the old per-segment A/A expectation was kept incorrectly during the speaker-authority merge. Digest and attribution checks remain intact.

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

* perf(test): wait for tracked worker completions without busy polling

A feature shard still exceeded the unchanged 720-second wall guard at 762s after counter-fork removal. Bash 5.1+ can wait for any tracked child; retain the atomic status-file and liveness reaper, with polling on older Bash. This removes the remaining periodic jobs/sleep subprocesses from Linux CI while preserving per-file isolation and failure detection.

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

* test(backend): synchronize heartbeat drain readiness explicitly

The drain test assumed a 50ms sleep meant renewal had begun; a loaded runner returned the response before the heartbeat reached renewal. Wait for an asyncio.Event set at the blocked renewal entry. Keep the renewal-reached, cancellation and sub-5-second drain assertions unchanged.

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

* perf(test): avoid unused plugins in isolated pytest workers

A full feature shard still spent 638s in isolated pytest sessions and exceeded the unchanged 720s step budget. Keep core xdist and asyncio, skip the unused loop-on-failure plugin, and load pytest-httpserver only in files referencing its fixture. Preserve unified/batched plugin behavior and explicitly test both isolated and unified plugin states.

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

* fix(backend): type defensive retrieval and duration boundaries accurately

Retain None and non-string input guards without strict typecheck errors. Keep the public tool schema unchanged.

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

* fix(backend): retain nullable query narrowing before text validation

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

* test(backend): initialize Wrapped router dependencies in the class fixture

Keep all four error-sanitization assertions and the unchanged CPU limit. Measure the status behavior in the call phase rather than charging its cold dependency import to one test.

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

* fix(backend): normalize result text explicitly and load pure test dependencies normally

Keep the input guards and output contract, remove production file-loader fallbacks added for the isolated test, and register the real pure modules in that fixture so dataclass annotations resolve correctly.

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

* test(backend): load real result-bound helpers in the product-info fixture

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

* test(backend): initialize isolated payment router in fixture setup

Preserve fresh per-test isolation and every proration/402/no-write assertion. Keep endpoint calls under the unchanged one-second CPU guard without charging cold router imports and mock construction to the call phase.

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

* fix(notes): preserve contact mentions and developer speaker identities

Restrict identity repair to unsupported participant bindings, exempt owner
names and protect owner aliases. Add a default-on identity repair kill
switch across notes paths and remove repair-only People catalog reads.
Preserve developer API participant IDs, wire shape and speaker names;
retain MCP opaque display identities and the owner's real speaker name.

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

* test(speakers): fix timestamps in raw-identity assertions

Use deterministic timestamps in serialized presentation fixtures so clock microseconds cannot look like leaked raw speaker IDs.

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

* test(ci): align fixture setup with current main

Retain the same real-module imports, isolated IO setup and behavioral assertions while removing textual conflicts with the current main fixtures. No production code change.

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

* test(ci): keep merged fixtures coherent with current main

Retain the single module-scoped payment fixture and its per-test mock reset from current main. Accept the optional speaker-rendering keyword in pagination IO stubs. Keep every payment and pagination assertion intact.

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

* fix(ci): avoid adjacent additions while preserving guardrail coverage

Name the default-on notes kill switch SPEAKER_IDENTITY_REPAIR_ENABLED so its generated registry entry is separate from concurrently merged flags. Move the existing episode speaker-order test away from the insertion point used by the offline-sync tests. Keep the same behavior and assertions.

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

* test(ci): compose capture evidence and speaker fixture imports

Keep the current-main capture-evidence imports alongside the speaker presentation imports in the isolated action-item date fixture. Retain every date-validation assertion.

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

* test(ci): isolate speaker stubs from evolving episode reset fixture

Keep speaker-name IO stubs in a separate autouse fixture so current main can add its reset and receipt setup without conflicting. Preserve the same test behavior and all assertions.

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

---------

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

* fix(episodes): every LLM transcript labels voices densely, never raw 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]>

* test(backend): guard every LLM formatter against raw speaker-id labels

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]>

* fix(speakers): add typed identity, count and presentation guardrails

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

* chore(api): refresh speaker display contract snapshot

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

* chore(clients): regenerate safe speaker metadata types

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

* docs: align historical reload pointer with main

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

* fix(notes): People names bind to a speaker only with this conversation's evidence

A People record, lexicon spelling, profile, memory or old meeting can no longer
authorize a participant name. Calendar attendees overlapping the conversation,
this conversation's roster/tile names and affirmative owner corrections still do.
Enforced in the persisted notes contract independent of packet rollout; agent
output is repaired, unsupported names become "a speaker" or hedged heard names.

Failure-Class: notes-identity-leak

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

* fix(notes): type identity name lists for the backend typecheck

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

* test(speakers): repair CI loaders and canonical display assertions

Load the real speaker presentation modules in the isolated date-validation harness, expect canonical c0 keys in wake-word rendering, and remove the duplicate Dart test import.

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

* test(app): drop duplicate import in speaker names test

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

* fix(speakers): defer short live epoch ordinals and gate acoustic grouping

Failure-Class: FC-generated-presentation-contract-bypass

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

* test(speakers): align inherited assertions with typed prompt identities

Failure-Class: FC-generated-presentation-contract-bypass

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

* test(backend): wake-word renderer expects opaque speaker prompt keys

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

* fix(speakers): keep live excerpt names bound to their evidence

Preserve trusted manual episode name projections without using a bound
excerpt name as the fallback label for unbound speech of that provider voice.

Failure-Class: FC-generated-presentation-contract-bypass

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

* fix(notes): defer known_spellings import so isolated models loads stay light

notes_packet imported known_spellings at module scope, pulling the dream
store and People database into every conversation_processing import; the
isolated action-item test then failed at collection. Import it at the call,
and pre-load the speaker display modules the models now import.

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

* test(backend): isolate spelling database reads in date harness

Load the real known-spelling helper with explicit empty database adapters so notes-packet imports do not pull the dream-agent runtime into action-item date tests.

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

* fix(app): count distinct participant identities with shared names

Deduplicate named participants by People record ID so repeated diarization IDs count once while different people with the same display name retain separate participant counts. Preserve the existing transcript heading regression assertion.

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

* test(backend): remove adapters superseded by lazy spelling import

The published notes packet repair now defers its database-dependent spelling import until it is used. Keep the date harness minimal instead of eagerly loading the helper with extra database mocks.

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

* perf(test): avoid counter subprocesses in isolated worker polling

Keep the active worker count in the parent shell and update it with the existing PID arrays. Every 20ms polling iteration previously forked twice for command substitution merely to count workers. File isolation, status handoff, crash detection and timing budgets remain intact.

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

* test(ci): retain main full-scan speaker exemption boundary

The canonical identity authority passes the full raw-speaker scan without an extra exemption. Keep main full-scan coverage unchanged alongside the broader changed-file identity ratchet.

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

* test(backend): preserve distinct labels in whole-transcript hash assertion

Main changed this regression to render all segments in one transcript. Retain its stronger A/B and six-distinct-output assertions; the old per-segment A/A expectation was kept incorrectly during the speaker-authority merge. Digest and attribution checks remain intact.

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

* perf(test): wait for tracked worker completions without busy polling

A feature shard still exceeded the unchanged 720-second wall guard at 762s after counter-fork removal. Bash 5.1+ can wait for any tracked child; retain the atomic status-file and liveness reaper, with polling on older Bash. This removes the remaining periodic jobs/sleep subprocesses from Linux CI while preserving per-file isolation and failure detection.

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

* test(backend): synchronize heartbeat drain readiness explicitly

The drain test assumed a 50ms sleep meant renewal had begun; a loaded runner returned the response before the heartbeat reached renewal. Wait for an asyncio.Event set at the blocked renewal entry. Keep the renewal-reached, cancellation and sub-5-second drain assertions unchanged.

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

* perf(test): avoid unused plugins in isolated pytest workers

A full feature shard still spent 638s in isolated pytest sessions and exceeded the unchanged 720s step budget. Keep core xdist and asyncio, skip the unused loop-on-failure plugin, and load pytest-httpserver only in files referencing its fixture. Preserve unified/batched plugin behavior and explicitly test both isolated and unified plugin states.

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

* fix(backend): type defensive retrieval and duration boundaries accurately

Retain None and non-string input guards without strict typecheck errors. Keep the public tool schema unchanged.

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

* fix(backend): retain nullable query narrowing before text validation

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

* test(speakers): qualify swapped provider labels after listen reconnect

Exercise enrolled and unenrolled guests through real idle reopen and a fresh listen matcher. Hydrate persisted wire rows, swap provider numbers, and require fresh acoustic evidence before names reappear. Anonymous cross-replica aliases remain an explicit follow-up.

Failure-Class: FC-generated-presentation-contract-bypass

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

* test(speakers): qualify legacy live labels with placed audio clocks

Keep unplaced live rows unnamed and retain dense-label coverage for five-second voices after integrating the reconciled prerequisite regression suite.

Failure-Class: FC-generated-presentation-contract-bypass

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

* test(backend): initialize Wrapped router dependencies in the class fixture

Keep all four error-sanitization assertions and the unchanged CPU limit. Measure the status behavior in the call phase rather than charging its cold dependency import to one test.

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

* fix(backend): normalize result text explicitly and load pure test dependencies normally

Keep the input guards and output contract, remove production file-loader fallbacks added for the isolated test, and register the real pure modules in that fixture so dataclass annotations resolve correctly.

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

* test(backend): load real result-bound helpers in the product-info fixture

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

* test(web): await the scheduled task-row hover control

The full preflight suite exposed an existing immediate getByTitle race. Framer Motion schedules onHoverStart through frame.postRender, so await the rendered snooze control before exercising the double-click contract. Product behavior and assertions are unchanged.

Failure-Class: none

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

* test(backend): initialize isolated payment router in fixture setup

Preserve fresh per-test isolation and every proration/402/no-write assertion. Keep endpoint calls under the unchanged one-second CPU guard without charging cold router imports and mock construction to the call phase.

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

* fix(speakers): retain qualified live labels across moment deltas

Treat an existing conversation-scoped voice ledger token as prior display qualification. Incremental moments contain only new speech, so a short reply must not erase an established ordinal. Regressions cover short and unplaced continuations, a new epoch, and a different conversation.

Failure-Class: FC-generated-presentation-contract-bypass

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

* fix(notes): preserve contact mentions and developer speaker identities

Restrict identity repair to unsupported participant bindings, exempt owner
names and protect owner aliases. Add a default-on identity repair kill
switch across notes paths and remove repair-only People catalog reads.
Preserve developer API participant IDs, wire shape and speaker names;
retain MCP opaque display identities and the owner's real speaker name.

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

* test(speakers): fix timestamps in raw-identity assertions

Use deterministic timestamps in serialized presentation fixtures so clock microseconds cannot look like leaked raw speaker IDs.

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

* test(ci): align fixture setup with current main

Retain the same real-module imports, isolated IO setup and behavioral assertions while removing textual conflicts with the current main fixtures. No production code change.

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

* test(ci): keep merged fixtures coherent with current main

Retain the single module-scoped payment fixture and its per-test mock reset from current main. Accept the optional speaker-rendering keyword in pagination IO stubs. Keep every payment and pagination assertion intact.

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

* test(speakers): align external route fixture with rendering contract

Accept the explicit preserve_api_values keyword in the offline external-list route speaker-name stub. The prerequisite calls this mode for released developer API identity compatibility; the real route assertions stay unchanged.

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

* fix(ci): avoid adjacent additions while preserving guardrail coverage

Name the default-on notes kill switch SPEAKER_IDENTITY_REPAIR_ENABLED so its generated registry entry is separate from concurrently merged flags. Move the existing episode speaker-order test away from the insertion point used by the offline-sync tests. Keep the same behavior and assertions.

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

* test(ci): compose capture evidence and speaker fixture imports

Keep the current-main capture-evidence imports alongside the speaker presentation imports in the isolated action-item date fixture. Retain every date-validation assertion.

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

* test(ci): isolate speaker stubs from evolving episode reset fixture

Keep speaker-name IO stubs in a separate autouse fixture so current main can add its reset and receipt setup without conflicting. Preserve the same test behavior and all assertions.

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

* fix(speakers): defer provisional cross-epoch owner competition

Keep short continuity accepts out of cross-scope competition until both voices have the grouping evidence floor, while preserving same-scope contention and strict acoustic groups. Cover the reconnect plus idle-reopen owner regression and policy boundaries.

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
@Git-on-my-level

Copy link
Copy Markdown
Member

Verdict: a careful, well-guarded fix for the #23364 live+sync overlap — I found no blocking defects, but it needs a human maintainer sign-off before merge because it widens the conditions under which transcript segments get dropped during sync merge.

Per-file notes:

  • backend/utils/stt/speaker_identity.py — the new reuse path in assign() is tightly gated: it only fires for scopes starting with sync: whose speaker_label_source != 'carried'; a persisted (scope, label) binding still wins, and final:batch: voices never reuse (test_persisted_scope_binding_wins_over_a_later_owner_hint and test_batch_owner_hint_cannot_bypass_an_abstained_acoustic_link pin both). _remember_identity() correctly skips the reserved sentinel 99 and carried labels. One design note: owner identity is first-hint-wins (_owner_speaker_id is set once), so an early misattributed is_user hint sticks for later sync chunks — looks intentional, but worth knowing.
  • backend/utils/sync/merge_dedupe.py — _compatible_speaker admits unidentified-vs-unidentified only; _same_live_voice joins anonymous live windows only on an identical persisted (speaker_id, speaker_id_scope) pair; _duration_compatible adds a <=25% duration-ratio gate; and the new unique-occurrence check (len({members}) != 1 -> keep the segment) prevents deleting a later genuine re-saying. Orientation nit: _duration_compatible(segment, item) expects the incoming segment (start/end) on the left and the window (duration) on the right — both call sites comply, and misuse fails closed (returns False -> segment kept), but a keyword-arg or docstring would make that contract explicit.
  • backend/tests/unit/test_safety_wal_dual_write.py — the main regression test reproduces the exact Hundreds of speakers and duplicated lines on 1-on-1 conversations (regression since Sept), plus one visit split into many conversations #23364 shape (owner line <8 tokens so it cannot anchor; >=8-token unidentified lines anchor the clock offset with 0.14s spread); the duration gate and the repeated-occurrence guard each get a dedicated test. Good coverage of the new gates.
  • backend/tests/unit/test_stt_speaker_identity.py — covers owner reuse across chunks with differing SPEAKER_n labels, person reuse, fresh IDs for unknown speakers, persisted-binding precedence over a later owner hint, and batch abstention.
  • backend/docs/listen_pusher_pipeline.mdx — the new paragraph matches the code (reuse limited to legacy sync: scopes, acoustic/manual authority retained, duration + unique-occurrence gates for anonymous replay removal). Accurate as written.

Safety of the deletion direction: anchors require exact token equality plus a unique occurrence, >=2 anchors agreeing within 2s, fuzzy matches still require >=8 tokens (short backchannels are never deduped), and every new gate fails toward keeping the segment. No security, secrets, or dependency surface; the OMI_SPEAKER_ID_SENTINEL import introduces no cycle, and the Backend unit suite plus Backend Hermetic Merge Gate are green at this head.

USER IMPACT: after a live session overlaps an offline sync upload, the other participant's lines should no longer appear twice, and a known person keeps one stable speaker across synced chunks instead of showing up as a new speaker per upload.

Still wanted as a reviewer (non-blocking): a cross-voice collision test (two different unidentified speaker_ids in one scope both fuzzily matching one incoming segment), and confirmation that no caller reaches the anchor path with caller-trusted estimated_offset_seconds on segments lacking start/end (those fail closed today, which is the right direction).

Leaving for human maintainer review: this deliberately broadens when transcript segments may be dropped during live+sync merge (data-integrity call for #23364), and the PR is coordinated with #23461/#23463 whose speaker-quality gates reportedly still fail.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@Git-on-my-level Git-on-my-level added the positive-signal Automation verified a genuine fix/quality contribution label Oct 25, 2026
@Git-on-my-level

Copy link
Copy Markdown
Member

Verdict: the core fix is correct, tightly guarded, and verified against the head — no blocking issues from me; this still needs human maintainer sign-off before merge (it is one piece of the stacked #23364 sequence and it widens the fleet dedupe deletion surface).

What I verified (by executing the head's merge/allocator code against the new tests' scenarios, all passing):

  • backend/utils/stt/speaker_identity.py — assign() reuses a persisted owner/person speaker_id only for new legacy sync: scopes; carried labels and final:batch: scopes are excluded, and the persisted (scope, label) binding still wins before any reuse lookup. _remember_identity correctly ignores the sentinel (99) and carried labels, so a late is_user/person_id hint cannot renumber a committed voice. Owner id 10 is reused across sync_0000/sync_0001, the known person maps to 11, an unknown participant mints 12.
  • backend/utils/sync/merge_dedupe.py — _compatible_speaker now lets unidentified pairs corroborate the clock offset and dedupe (the actual Hundreds of speakers and duplicated lines on 1-on-1 conversations (regression since Sept), plus one visit split into many conversations #23364 fix), _same_live_voice restricts anonymous live-window joins to a single persisted scoped voice, and _duration_compatible (25% ratio) plus the single-occurrence ambiguity gate in _fuzzy_survivors keep the deletion surface narrow. Known-speaker dedupe behavior is unchanged.
  • backend/tests/unit/test_safety_wal_dual_write.py and backend/tests/unit/test_stt_speaker_identity.py — the new regressions pin each behavior above; I reproduced all eight scenarios against the head's production code.
  • backend/docs/listen_pusher_pipeline.mdx — the added paragraph matches the code (reuse only for new sync: scopes; batch abstention; duration + unambiguous-occurrence gates for anonymous replay removal).

One residual, accepted edge worth a follow-up test if field reports ever show it: identical verbatim 8+ token speech by a different unidentified voice within the ~2s post-offset tolerance and 25% duration ratio is still removed as replay — the uniqueness gate protects against repeated live occurrences, not a single cross-voice match. Real-world likelihood is low given the exact/near-exact token requirement.

Performance: constant-time predicates per candidate; no new queries or external calls. Cost: none. Blast radius: the fleet live+sync merge path (fuzzy_live_overlap) and sync speaker numbering — the failure modes are dropped or retained transcript lines, and both directions are gated as above.

USER IMPACT: conversations with unidentified participants should stop showing the same lines twice when live and offline transcripts overlap, and speaker labels stay stable across uploaded sync chunks.

Still wanted (non-blocking): a regression test for the cross-voice verbatim edge above if it ever appears in reports.

Leaving for human maintainer review: sign-off is needed for this piece of the #23364 offline-sync sequence and for the widened deletion surface in the merge path.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@Git-on-my-level
Git-on-my-level merged commit 0f55260 into BasedHardware:main Oct 27, 2026
52 checks passed
Git-on-my-level added a commit that referenced this pull request Nov 4, 2026
Git-on-my-level added a commit that referenced this pull request Nov 4, 2026
…lout and a kill switch (#24477)

* docs(hardware): add the visual guide "How the Omi pendant works"

Picture-first on-ramp for contributors: an animated scene of where audio goes (live, saved, lost), the real exploded view and KiCad-rendered mainboard, nine behaviour cards tied to where each lives on the board, a playable day, and the questions to ask before a pendant decision.

Mintlify does not serve raw HTML, so the page mounts as a JSX snippet; the board renders are static SVGs produced by omi/hardware/consumer/explainer/build_explainer.py from the KiCad sources.

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

* docs(hardware): UI evidence for the pendant guide

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

* pre-push: validate manifest paths against HEAD for sparse checkouts

Cone-mode sparse worktrees do not materialise out-of-cone paths, so a
literal trigger or command path that is real at HEAD fails
validate_manifest's working-tree existence check, and every sparse
checkout hard-fails pre-push at manifest resolution with hundreds of
'explicit trigger path does not exist' errors before any check runs.

Validate against the HEAD tree as well as the working tree: present in
either passes; absent from both still fails closed (typos unchanged).
head_tree_paths() lists HEAD once per invocation, not once per path.

* feature-flag-registry: accept prereg docs tracked at HEAD in sparse checkouts

Same class as the manifest validation fix: the registry check requires
prereg docs to exist on the working tree, and a cone-mode sparse checkout
does not materialise out-of-cone paths, so feature-flag-registry failed
in any sparse lane whose cone excludes the prereg doc. Accept a prereg
path that exists on disk or is tracked at HEAD; neither still fails.

* feature-flag-registry: scan flag reads at HEAD in sparse checkouts

The read scanner iterates tracked paths but skipped any file absent from
the working tree, so a cone-mode sparse checkout reported every app/web
flag as 'stale registry entry'. Read sources (and chart manifests) from
disk first, falling back to the HEAD blob; an alias with no read on disk
or at HEAD still fails. Uncommitted deletions are judged against HEAD,
which is what the pushed tree will contain.

* check-manifest-contract: read manifest test modules at HEAD in sparse checkouts

The drift guard that proves registered test commands actually execute
cases read test modules from the working tree only, so a cone-mode
sparse checkout failed check-manifest-contract with 'does not exist' for
every out-of-cone test module. Read disk first, HEAD blob second; absent
from both is still an offender.

* product-invariants: accept guards tracked at HEAD in sparse checkouts

The registry audit fails every locked invariant whose guard file is
absent from the working tree, and guards live across all surfaces, so a
cone-mode sparse checkout failed product-invariants on every push.
Existence now counts the HEAD tree as well; a guard in neither still
fails closed.

* failure-class: accept prevention artifacts tracked at HEAD in sparse checkouts

canonical_prevention_artifact paths are guard files across every
surface; a cone-mode sparse checkout does not materialise out-of-cone
paths, so validate failed on every push from a sparse lane. Existence
now counts the HEAD tree as well; a path in neither still fails.

* dead-code-ratchet: skip cone-excluded areas instead of failing sparse checkouts

Each area scanner fails when its entry tree is missing from the working
tree. A cone-mode sparse checkout legitimately excludes whole areas
(app/, desktop/macos/agent, desktop/windows), so the ratchet failed on
every push from a sparse lane even though none of those files can have
changed there. Skip areas whose entry paths carry the skip-worktree bit
(tracked, cone-excluded): they carry no signal in this worktree and CI's
dense run still enforces them. User deletions keep their 'H' tag and
keep failing closed; a skipped area also never rewrites its baseline.

* client-compat: read the OpenAPI doc at HEAD in sparse checkouts

The C10 check reads docs/api-reference/app-client-openapi.json from the
working tree; docs/ is outside every code surface's sparse cone, so a
cone-mode sparse lane crashed pre-push. Read disk first, HEAD blob
second.

* desktop-flow-lint: skip cone-excluded flows directory in sparse checkouts

The lint fails when desktop/macos/e2e/flows is missing, which every
cone-mode sparse checkout without the desktop surface is. Skip with a
note when the directory carries the skip-worktree bit (tracked,
cone-excluded — dense CI enforces it); deletions keep failing.

* perf(backend): profile batch worker stages and connect queue-age scaling input

* fix(monitoring): declare batch worker scrape and reviewed ready-age adapter rule

- Inventory batch-pipeline-worker-metrics in expected-targets.prod.yaml.
- Add the omi_batch_pipeline_ready_age_seconds external rule to the reviewed
  adapter upgrade expectation (diff_prod_adapter.py), rejecting any modified
  live copy.
- Contract fixture models the pre-upgrade live config and finds the listen
  rule by name instead of by list position; add exact/modified/live-drift
  tests for the new rule.

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

* fix(testing): forward stage timings through the gauntlet CPU worker shim

run_process now constructs SynchronizedWorker(..., timings=timings); the
Sync Cloud Tasks gauntlet's CpuSynchronizedWorker override rejected that
keyword, so batch-worker-1 exited before readiness.

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

* fix(backend): measure prefetched decode at its executor

The fetch_decode timer previously wrapped prefetch.take(), so under the
production IO concurrency it measured only the later Future.result() wait;
a decode overlapping earlier GPU work appeared nearly free. Wrap the decode
callable submitted to the prefetch executor instead, keep the no-prefetch
fallback timing decode directly, and document the measurement point.

* ci-flake: keep desktop Linux runtime apt install off the network when warm

The 'Linux package · helper smoke' job's 'Install Linux runtime
dependencies' step downloads ~35 MB of debs plus package indexes from
azure.archive.ubuntu.com on every run. When that mirror is throttled the
downloads alone exceed the step's 5-minute budget and the job dies:
run 39846837408 attempt 1 (PR #23335, 2026-10-22; the same SHA passed on
rerun with the step finishing in ~14 s), run 37693118159 (main push,
2026-10-07, every fetch Ign) and run 33911765703 (PR, 2026-09-04) all
timed out identically — an infra flake, not a regression.

Mirror the fix proven for the backend twin of this flake (#23308):
cache the downloaded .deb closure keyed on the runner image with a
restore-keys fallback across ImageVersion bumps, replay warm caches with
dpkg -i (zero network on the hot path — apt-get update fetches indexes
even when every deb is local), and keep bounded apt only as the cold
path and as repair when the replay fails. Single job, no matrix, so the
save step has no concurrent same-key race to gate.

.github is edited only for this flake's own step; no workflow is added,
per the 2026-10-22 CI flake-fix and caching direction.

* ci-flake: load utils.task_sync once per file in cloud export dedup tests

The fast-unit CPU duration guard failed this file twice on CI (1.04s and
1.08s over the 1.00s fail budget; both runs passed on re-run). Each of the
four tests ran its own stub_modules + load_module_fresh pair, and the block
teardown evicts every transitively imported module (httpx and friends), so
every test re-paid the full import inside the guard's measured call phase:
0.50-0.68s CPU on a quiet runner, 0.78-1.08s under the file-isolated
runner's saturation, sitting on the 1.0s cliff.

utils.task_sync has no module-level mutable state, so one module-scoped
import shared by the four tests is behaviorally identical. The per-test
store/create_calls/fail_on move onto a mutable _Harness the stub closures
dispatch through, and each test seeds it first. The single import lands in
the first test's setup phase, which the guard deliberately does not charge
(tests/conftest.py measures the call phase only so shared file setup is not
misattributed), matching the module-scoped stub_modules pattern already
used by tests/unit/test_sync_reprocess_coalesce.py.

Measured locally (nice -n 19, guard thresholds 0.1/1.0): before, the file
warned at 0.11-0.36s CPU per test; after, no guard output at all, also with
six parallel pytest processes saturating the machine, and file wall time
1.18s -> 0.27s. Test isolation unchanged: sibling task_sync files pass in
the same process before and after this file.

* ci: cache apt runtime packages and retime Linux runtime-deps step

The build-linux job's 'Install Linux runtime dependencies' step downloads
~35 MB of .debs from azure.archive.ubuntu.com every uncached run; when
runner<->mirror throughput degrades (~68 KB/s avg in job 120062237675)
the download alone exceeds the 5-minute step budget while every
connection keeps streaming, so the per-request apt timeouts cannot catch
it. Same signature on main 2026-10-07 (job 113037996050); the re-run of
the same job on the same PR code succeeded.

Cache the .deb archives (seed /var/cache/apt/archives, download-only,
capture, unpack) so steady-state installs download nothing but version
changes, and raise the step budget to 10 minutes to cover cold-cache
runs at the worst observed throughput (34.6 MB / 68 KB/s ~ 8.5 m). Stall
bounds and the 20-minute job ceiling are unchanged.

* ci: raise Linux runtime-deps step budget to 20 minutes on new slow-mirror evidence

This PR's own first run (job 120074210159) missed the apt cache (first run
with the new key) and streamed the deb pool at ~40-45 KB/s — worse than
the 68 KB/s the 10-minute budget was sized from — timing out mid-download
at Get:30 of 30 (~14.4 min of pure download needed at that pacing).

20 minutes covers ~32 KB/s effective throughput while reserving 2 minutes
for index fetch and unpack, and is idempotent for warm-cache runs, which
download nothing and finish in seconds. Note the budget must cover the
cold path even though cache misses are rare: the key hashes this workflow
file, so every edit re-cold-starts the cache.

* feat(deploy): drift check compares serving revisions by value hash

check_cloud_run_env_drift.py now reads what is serving instead of
spec.template: Cloud Run revisions from status.traffic (resolving
latestRevision entries and split traffic) and, with --gke, the GKE
ReplicaSets that hold ready pods for backend-listen, pusher and
batch-pipeline-worker. Each serving env is compared with the manifest,
rendered deploy state or chart values by key name and by a truncated
SHA-256 of the value or secret reference. Values are never printed and
hashes of sensitive-looking keys are redacted. The report flags when the
template differs from what is serving.

Report-only by default; --strict exits 1 on drift and 2 on fetch or
render errors for use after a train. Fixtures replay the 2026-10-18
23:50Z template-versus-serving misread.

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

* fix(deploy): address review — envFrom ConfigMap coverage and drift-check hardening

- GKE envFrom: resolve the ConfigMaps serving containers bulk-load (live
  kubectl read or offline fixture) and join their keys in the name/hash
  comparison; missing/out-of-date keys are drift, unresolvable refs
  report INVENTORY, and live-vs-chart reference drift is flagged (P1).
- Unresolved deploy-time bindings are now presence-checked: a None
  expected hash skips only the value comparison, never the key check.
- --rendered-state must exist and contain a services mapping; no silent
  fallback to the raw manifest.
- --strict exit precedence: fetch/render errors (2) outrank drift (1);
  expected-state render failures return 2 instead of a traceback.
- Offline snapshots require a top-level env list; a statusless template
  document is refused instead of being misread as serving.
- --no-cloud-run without --gke/--gke-workload is a usage error.
- Secret-ref hashes keep the project in project-qualified references
  (cross-project rebinds are visible) and include the normalized
  optional flag.
- Published env fingerprints are built from redacted placeholders for
  sensitive keys; full fingerprints stay internal for equality checks.

* fix(deploy): address review round 2 — envFrom provenance, prefixes, exact-state keys

- Live envFrom ConfigMap data cannot prove what already-running pods
  resolved at container start (K8s never refreshes envFrom; a ConfigMap
  update carries no trustworthy last-write timestamp). Live envFrom keys
  now report INVENTORY instead of asserting OK; offline fixtures are
  snapshots and still compare exactly (P1).
- envFrom prefix is part of the reference: a prefixed source expands to
  PREFIX_KEY and its identity carries the prefix, so rebinding cfg to
  prefix: X_ + cfg is visible reference drift, not a silent match.
- With --rendered-state, provisional env_var bindings the renderer
  omitted (unset at deploy time, incl. secret env_var resolving empty)
  are dropped from the expected set instead of being inherited from the
  raw manifest as name-only false drift.
- --cloud-run-state / --gke-state loads moved inside the handled error
  section: malformed fixtures return exit 2 under --strict, never an
  uncaught exception misread as drift.

* fix(deploy): compare explicit env entries that shadow unproven envFrom

Live GKE reads mark every envFrom ConfigMap reference unproven, so the
flat skip dropped all manifest ConfigMap keys from the value comparison —
including keys the serving ReplicaSet sets through explicit env entries,
whose values are knowable (explicit env shadows envFrom; the serving
spec is immutable). A stale serving literal on an overlapping key such
as STT_SERVICE_MODELS could therefore pass --strict with only INVENTORY.

ServingTarget now records its explicit env key names and the per-target
skip excludes them: keys whose effective value comes exclusively from
envFrom keep the INVENTORY downgrade, shadowing keys are compared by
hash like any other explicit entry.

* fix(deploy): per-target envFrom provenance, prefixed key expansion, optional-aware identities

Review round 3 (Codex P2 x4) on the GKE envFrom provenance model:

- Live-only drift now excludes every key contributed by an unproven envFrom
  source on that target, not only keys already declared expected: a ConfigMap
  key added after the ready pods started must not read as unallowlisted
  live-only drift.
- Expected ConfigMap keys expand with the reference's prefix: the
  `name#prefix` identity is parsed instead of compared with the bare ConfigMap
  name, so a prefixed chart reference is resolved, not reported unresolved
  with phantom live-only keys.
- envFrom references are compared per serving target instead of as a union:
  during a mixed rollout a still-serving ReplicaSet without the reference no
  longer hides behind the new ReplicaSet's matching reference, and expected
  envFrom keys are excused only on targets that hold the degraded reference.
- configMapRef optionality joins the reference identity (omitted normalizes to
  false): `optional: true` on the serving side is reference drift, because it
  changes what a missing ConfigMap does to the pod.

* fix(deploy): reject a rendered state missing a checked service

Review follow-up: a rendered state whose top-level services mapping omits a
manifest service, or carries a non-mapping entry for it, silently fell back
to the raw manifest for that service. Deploy-time env_var bindings then
degraded to name-only checks while the command claimed exact-state
validation. Every manifest service must now have a valid rendered entry.

* fix(deploy): validate rendered env lists and envFrom source ordering

Review follow-up round 2:

- A rendered state service entry without an env list (missing, null, or
  non-list) is rejected instead of silently re-sourcing expected values from
  the raw manifest; the renderer always emits an env list per service.
- envFrom reference order is now compared: the K8s API resolves the last
  envFrom source when several export the same key, so a reordered reference
  list changes the effective environment and is reported as reference drift
  instead of passing as the same set. Multi-source envFrom key merging in
  envfrom_entries() follows the same last-source-wins rule.

* fix(deploy): harden rendered-state validation, envFrom duplicates and optional refs

Review follow-up round 3:

- Malformed entries inside a rendered env list (null, non-mapping, missing
  name) are rejected instead of silently skipped: the renderer only emits
  named mappings, and skipping would keep the manifest expectation for the
  corrupted key while reporting OK.
- --allowlist-file loading moves inside the operational-error boundary: a
  missing or malformed allowlist is an exit-2 input failure, not drift and
  not a traceback.
- Duplicate envFrom sources are preserved end to end: K8s resolves the last
  source for overlapping keys, so [A, B, A] and [A, B] are different
  effective environments and must not normalize to the same reference tuple.
- An optional envFrom reference whose ConfigMap is NotFound live resolves to
  an empty unproven contribution (INVENTORY) instead of a workload-wide
  fetch ERROR: K8s permits the pod to run without it.

* fix(deploy): scope envFrom suppression per source, compare template refs, accept deployed helm args

- Missing-key suppression now covers only the keys a degraded expected envFrom
  reference contributes (tracked per reference), so a snapshot that proves
  ConfigMap A while omitting B still reports keys missing from the proven A
  instead of skipping the whole expected envFrom set.
- The template-vs-serving comparison includes the ordered envFrom identities:
  rebinding ConfigMap A to B with identical data no longer passes as
  "Template = serving: yes".
- Expected GKE renders accept the exact deployed override inputs via
  --gke-helm-arg / --gke-helm-arg-file (the argv format the listen deploy
  workflow writes), so an intentionally overridden rollout is not reported as
  drift against repository defaults.

All three covered by regression tests that fail on the previous code.

* fix(deploy): scope helm override args to their workload and redact values from helm failures

- Override arguments (--gke-helm-arg / --gke-helm-arg-file) are now scoped to a
  single workload via --gke-helm-arg-workload (default backend-listen, the argv
  file's producer): an argv generated from one chart's env indices must not be
  applied to a different chart, where the same index can name another variable
  or fail the render.
- A failing helm template no longer surfaces CalledProcessError's default str()
  (full argv, including literal --set-string values) into markdown/JSON/summary
  reports; the error is re-raised redacted.

Both covered by regression tests that fail on the previous code.

* fix(deploy): forward envFrom optionality on the template path, compare template identities unconditionally, disambiguate JSON keys

- The Deployment-template envFrom expansion forwards configMapRef.optional to
  resolution, so a missing optional ConfigMap is an empty contribution instead
  of a workload-wide fetch ERROR (matching the ReplicaSet loop).
- The template-vs-serving envFrom identity comparison no longer short-circuits
  on an empty template identity list: a template that dropped the reference
  while a serving ReplicaSet still references an empty ConfigMap is exactly
  the divergence the field exists to reveal.
- The JSON report keys results by platform and name, so checking a Cloud Run
  service and a GKE workload sharing a name no longer silently overwrites one
  platform's entry.

All three covered by regression tests that fail on the previous code.

* fix(deploy): keep explicit configMapKeyRef values unproven, cache NotFound distinctly, track envFrom secret identities

Address review round 5 (Codex P2s):

- Explicit env entries bound through valueFrom.configMapKeyRef prove the
  reference in the immutable pod spec, never the data the container resolved
  at start (ConfigMap updates require a pod restart). On live reads these
  keys are now excluded from value comparison and reported as INVENTORY via
  explicit_unproven_keys instead of a verified OK/DRIFT from unknowable data.
- An optional reference to a missing ConfigMap no longer caches {} under the
  name: the NotFound fact is cached distinctly so a later REQUIRED reference
  to the same name fails with ERROR/exit 2 instead of reading the optional
  caller's empty result from the shared cache.
- envFrom sources are parsed once into spec-ordered descriptors; secretRef
  sources join the reference comparison as opaque secret:<name> identities
  (contents never read) on the serving, template, values and helm paths, so
  an unexpected serving Secret bulk-load is reference drift instead of
  silence. Interleavings are compared in spec order (last-source-wins).
- Inline --set*=NAME=value helm tokens are redacted like the bare argv shape;
  values containing '=' (base64 padding, connection strings) redact in full.
- An exact --rendered-state that omits a required env_var binding is now
  rejected: the renderer fails rather than omit one, so only explicitly
  provisional omissions may drop out of the expected set.
- The sensitive-key regex is case-insensitive: api_key, dbPassword and
  MyServiceToken digests are redacted like uppercase names.
- Keys contributed by an expected envFrom source the repository cannot
  enumerate are excused from live-only drift on targets holding the same
  reference (INVENTORY), not unallowlisted drift failing --strict.

Seven regression tests; all 58 unit tests pass via backend/test.sh.

* fix(deploy): require a value source in rendered entries; redact *_KEY and OAUTH digests

Address review round 6 (Codex P2s):

- A rendered-state env entry must carry exactly one of value or
  valueFrom: the renderer always emits one of them, and an entry with
  neither was hashed as an empty literal, so a corrupted state matching
  an empty serving value could report OK. Neither/both now raise an
  operational input error.
- The sensitive-key regex adds _KEY and OAUTH alternatives so declared
  manifest secrets accidentally deployed as literals (ADMIN_KEY,
  FAL_KEY, MCP_OAUTH_CLIENTS_JSON) get redacted digests like other
  credentials; non-credential *_KEY names remain covered by the same
  redaction rather than published.

Two regression tests; all 60 unit tests pass via backend/test.sh.

* fix(deploy): compare keyref binding identities, honor envFrom last-source-wins, redact SALT, reject override tokens in values render

Address review round 3 (chatgpt-codex-connector):

- Explicit configMapKeyRef bindings now compare by reference identity
  (ConfigMap name, key, optionality) in addition to name: the immutable
  pod spec proves the binding, so a rollout that rebinds a key to a
  different ConfigMap/key is drift; only a matching binding stays
  value-unproven on a live read (INVENTORY).
- Value comparison honors K8s envFrom last-source-wins: a key whose
  effective source is an external reference the repository cannot
  enumerate is no longer compared against the repo ConfigMap's manifest
  digest (false drift / strict exit 1 on a correct rollout). An explicit
  env entry shadowing the source keeps the key compared.
- SALT joins the sensitive-key regex: DREAM_AGENT_FEEDBACK_SALT is a
  declared manifest secret; an accidental literal deployment would
  otherwise publish its deterministic digest.
- --gke-render values now rejects --gke-helm-arg/-file override tokens as
  an operational error (exit 2, per workload) instead of silently
  comparing an overridden rollout against repository defaults.

Six regression tests added; suite: 66 passed.

* fix(deploy): flag a live keyref swap of a proven expected literal

Codex P2 (r4341399125): a key the chart renders as a literal (or any
non-keyref source) that serving binds through configMapKeyRef was
subtracted from value comparison as explicit_unproven, while
expected_keyref_hashes — which only holds expected keyref keys — could
not flag it either, so the value-source change vanished into INVENTORY
with a --strict exit 0.

The immutable pod spec proves the live binding and the repository
proves the expected source, so compare them directly. Their hashes live
in disjoint domains (value: vs configmap:), so a source change always
shows as a mismatch; an expected source the repository cannot prove
(None hash, deploy-time binding) still skips the comparison — name-only,
no false drift.

test_gke_live_explicit_configmap_keyref_values_stay_unproven now
mirrors the binding identity on the expected side: the resolved data
stays unproven (ConfigMap edits after pod start, without a rollout, do
not drift), while a literal-vs-keyref source swap is provable drift.

* fix(deploy): honor opaque envFrom overrides, reject foreign rendered keys, resolve secret aliases

Codex review round 7 (r4342784015/4021/4028/4033/4039):

- envFrom last-source-wins now tracks keys a later opaque Secret source may
  override: those keys stay value-unproven (INVENTORY) instead of asserting
  the earlier ConfigMap's data, and a trailing known source re-proves them.
- A rendered state that declares a key the manifest does not bind is rejected
  instead of merged; merging hid exactly the live-only drift this checker
  exists to detect.
- Rendered valueFrom entries must match the renderer's only nested shape
  (secretKeyRef with non-empty name/key); anything else is the documented
  operational error, not a hash-domain comparison.
- Values-mode pusher envFrom expectations read runtimeConfigMapName (the only
  field its deployment template uses) instead of the dead .Values.envFrom.
- Cloud Run cross-project secrets resolve their secretKeyRef alias through
  the run.googleapis.com/secrets annotation before hashing, on both serving
  revisions and the template, so a correct deployment no longer reports a
  value mismatch.

* fix(deploy): degrade form-ambiguous alias mismatches and unresolved-source shadows to INVENTORY

Codex review round 8 (r4343951882, r4343951890):

- The platform normalizes run.googleapis.com/secrets annotation resources to
  project numbers while repository state may carry the project ID: a value
  mismatch on an alias-resolved key is form-ambiguous, not proven drift, so
  those keys now degrade to INVENTORY (alias_unproven_keys) instead of
  failing --strict. Matching forms still compare OK.
- An envFrom source whose data the snapshot omits is as opaque as a Secret:
  it may override any earlier known source's key (last-source-wins), so
  earlier keys stay value-unproven until a later known source re-exports
  them.

* fix(deploy): confine alias degradation and opaque shadows to provable ambiguity

Codex review round 2 (PR #22389):

- Alias-resolved secret references now compare by a canonical (project-stripped)
  hash: only a difference confined to the projects/<id|number> qualifier —
  including the bare-name manifest form — degrades to INVENTORY; a secret name
  or version difference stays proven drift (test_cloud_run_secret_alias_{version,
  name}_difference_is_real_drift).
- expected_cloud_run_env derives the canonical map and inspect_services_drift
  wires it through, so the degradation fires for every caller (the None default
  previously left it empty and never degraded).
- A prefixed opaque envFrom source (Secret or unresolved ConfigMap) can only
  shadow earlier keys its prefix can reach, so unprefixed keys stay
  value-comparable (test_gke_prefixed_{secret_source,unresolved_configmap}_
  shadows_only_matching_keys).

* fix(deploy): surface alias uncertainty, excuse Secret-suppliable missing keys, reject stale rendered literals

Codex review round 3 (PR #22389):

- JSON and markdown reports serialize alias_unproven_keys, so an INVENTORY
  driven by project-form ambiguity is explainable from the payload alone.
- A prefixed Secret envFrom source may supply an expected key absent from the
  earlier known sources: its contents are never readable, so the absence is
  unproven and excused from the missing check (prefix-scoped; unresolvable
  ConfigMap siblings still attribute their expected keys — proven sources'
  missing keys stay drift).
- Rendered-state entries that contradict a manifest-owned literal or fixed
  secret reference are rejected: the renderer emits those unchanged, so a
  stale state can no longer replace the manifest hash unchecked and mask
  repository drift behind an equally stale serving revision.

* fix(deploy): prove alias project equality, excuse opaque-supplied missing keys, redact validation hashes

Codex review round 4 (PR #22389):

- Alias comparison now keeps the project segment and degrades to INVENTORY only
  for genuine form ambiguity: project ID vs number (either direction) or an
  implicit bare name vs a qualified reference. Two different project numbers or
  IDs are provably different projects and stay real drift
  (test_cloud_run_secret_alias_unequal_{numeric_projects,project_ids}_is_real_drift).
- The missing-key excuse extends to opaque ConfigMap sources (unprefixed
  unresolved later source may supply any expected name), still scoped by
  prefix-reachability and to sources without a known key set; the legacy
  anti-blanket-suppression case now pins the prefix boundary
  (test_gke_missing_key_excuse_stops_at_the_opaque_source_prefix,
  test_gke_unprefixed_unresolved_configmap_may_supply_missing_expected_keys).
- The rendered-state contradiction error redacts digests for sensitive keys via
  display_hash before the message reaches stderr
  (test_rendered_state_contradiction_redacts_sensitive_hashes).

* fix(deploy): reject duplicate rendered environment names

An exact --rendered-state declaring the same binding name twice passed
every structural validation: rendered_names collapsed the duplicate and
the later entry silently won the expected-hash merge. Deploy-time env_var
bindings carry no manifest hash to contradict, so a corrupted state
ending on a stale value could match a stale serving revision and report
OK. The renderer emits each binding exactly once, so duplicates are now
rejected as an operational input error.

* fix(deploy): excuse manifest-only provisional omissions, keep template envFrom lookup best-effort

Manifest-only mode now mirrors the renderer's provisional contract: a
provisional env_var unset in the environment is legitimately omitted at
deploy time, so it must not enter the declared set as a name-only
requirement — that reported false missing drift and a strict exit 1 for
a valid deployment. Bindings the environment resolves stay required.

GKE template envFrom expansion is best-effort now: a failed rollout can
leave the Deployment template referencing a ConfigMap that no longer
exists while the previous ReplicaSet still serves, and the propagated
kubectl NotFound errored the whole workload before any serving
ReplicaSet was inspected. The lookup failure degrades template context
to unproven (template_matches_serving None) instead.

* fix(deploy): reject rendered source-type swaps, normalize the backfill overlay

A corrupted rendered state could represent a manifest env binding as
valueFrom.secretKeyRef or a manifest secrets binding as a literal;
deploy-time env_var bindings have no manifest hash to contradict, so the
swap bypassed the contradiction check and a serving revision carrying
the same invalid source reported OK. The renderer emits each section
with its own source type; validate that before adopting the hash.

The sync-backfill worker deploys through an overlay the renderer cannot
see (sync-backfill-lifecycle rewrites SYNC_TASKS_HANDLER_URL and
SYNC_TASKS_OIDC_AUDIENCE to the worker service's own URL after the
shared render), so the rendered state's values never reach Cloud Run for
backend-sync-backfill. Those keys compare name-only on -sync-backfill
services; presence stays required.

* fix(deploy): keep backfill overlay value checks, alias lookup by name only, optionality in alias form

Codex review round 9 (r4348673531/3546/3557):

- The sync-backfill overlay no longer erases the expected hashes: the
  lifecycle action defines the value deterministically (the worker
  service's URL plus /v2/sync-jobs/run), so both sides normalize only the
  project-number segment and the comparison stays a value check. A URL
  pointing at backend-sync, an old service, or the wrong path is drift
  instead of a presence-only pass.
- Secret alias resolution now pairs the annotation lookup with
  secretKeyRef.name only (the platform's documented contract); the
  env-entry-name fallback could rewrite a live binding through an
  unrelated annotation entry and report a false OK.
- The alias comparison form includes secretKeyRef.optional, so a live
  binding flipped from required to optional is real drift; only the
  project-identifier representation difference still degrades to
  INVENTORY.

Four regression tests added; the stale env-name-keyed annotation fixture
in the project-form degradation test now keys by the declared lookup
name.

* ci: key apt cache on runner image and raise job budget to 30m

Address Codex review of c5e2116:

1. Cache key pinned the workflow file hash, which stays an exact match
   forever (actions/cache never re-saves on exact hit): cached .debs
   would freeze at first-saved versions as Ubuntu publishes updates,
   and every workflow edit gratuitously cold-started the cache. Key on
   ${ImageOS}-${ImageVersion} plus a literal package-list token instead,
   matching the scheme already established in PR #23344; the restore-key
   prefix carries still-current .debs across runner image bumps.

2. The step budget raise (10 -> 20) ignored the pre-existing job-level
   timeout-minutes: 20 on build-linux. Worst case cold apt (14.4 min
   measured pacing) + ~70s setup + ~5m packaging/smoke exceeds 20 min,
   cancelling the job mid-packaging; a cancelled job never saves the
   cache (save-always: false), so every retry stays cold. Raise the job
   budget to 30 so the cold path fits and the cache actually warms.

* fix(deploy): degrade privateEnv-replaceable listen keys, reject rendered optional fields, flag explicit bindings lost to envFrom

- backend-listen STT_CAP_DISPATCH_* values can be replaced at deploy time from
  LISTEN_PRIVATE_VALUES_YAML (chart privateEnv); without the exact override
  argv the checked-in defaults are not proven deployed values, so they degrade
  to presence-only (ops/drift_check.py contract) instead of false-drifting a
  valid rollout under --strict.
- Rendered-state validation now requires the renderer's exact secretKeyRef
  shape (name and key only); a carry-along field such as optional is rejected
  instead of silently skipping the manifest contradiction check for
  env_var-backed secrets.
- A chart-explicit env key dropped from the serving spec while envFrom still
  supplies the name is flagged as explicit_binding_lost drift; previously the
  provable spec divergence vanished into INVENTORY with --strict exit 0.

* feat(stt): add private production-path quality scorecard

Failure-Class: none

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

* feat(stt): qualify private local evaluation and artifact provenance

Keep decoded capture durations and persisted overlapping groups honest, use the shared conversation speaker allocator, verify model reference provenance, and add held-out enrollment diagnostics.

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

* test(stt): fence cached policy and reference provenance

Count allocated conversation voice IDs across unit scopes, and reject mismatched source crops or model locks before WER.

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

* feat(stt): verify immutable local inference archives

Validate original source, crop, configuration and payload hashes without changing inference output or requiring a centroid enrichment implementation.

Failure-Class: FC-independent-owner-voice-accepts

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

* feat(stt): reuse verified baseline inference with honest receipts

Preserve original inference identity while rerunning persisted projection, without repeating private audio inference.

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

* fix(ci): pin and bound native audio dependency fetches

* perf(backend): reduce isolated unit test startup and image scan work

* fix(stt): type optional local batches and heterogeneous scorecards

Failure-Class: none

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

* test(stt): collect pure evaluator dependencies before timed calls

Keep the unit CPU guard focused on the exercised behavior while preserving the production projection calls.

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

* test(stt): collect remaining projection dependencies before timing

The exact guarded runner now passes all 19 evaluator tests without changing duration budgets or exercised projection behavior.

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

* docs(eval): keep the model environment outside source staging

Use the external evaluation environment in the runnable command, matching the private-artifact and runtime-image guidance.

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

* test(eval): isolate the decision-mill letter tool contract

Use fixed synthetic tool output and verify the complete invocation so CI never depends on a personal decision-mill installation. Real local task generation retains the authoritative installed tool.

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

* fix(eval): bind cached inference to effective worker switches

Retain original archive identities with explicit switch evidence and use package imports for isolated viewer tests.

Failure-Class: none

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

* fix(eval): capture all worker disposition and handoff switches

Failure-Class: none

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

* refactor(stt): relocate local projection hooks for upstream composition

Move the optional injected keyword-only arguments before the existing publish
argument. Defaults, callers and execution behavior stay the same. The reviewed
candidate combines cleanly with current main without importing its changes.

Failure-Class: none

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

* docs(listen): record T3b on/100 serving in live-stt-routing runbook

Follow-up ruled by the two-lane lead with #23516 (18:53Z): fold the
rollout-wording updates into a small docs PR with no re-review loop. The
runbook still described stage 1 (on/90, static 10%) as the live state and
named on/100 as the rollback direction, which is now the serving state.
Record the 2026-10-24 T3b rollback of the static expansion, mark the stage
table historical (stages 2-4 not planned), and name back to on/90 as the
remaining abort step.

* perf(llm): omit server-derived L1 fields from generation schema

* ci(deploy): name the requester on every backend dispatch

Prod run 40214727824 (gcp_backend.yml workflow_dispatch, prod,
cloud-run-only, f3e669f, 10-25 17:04Z) could not be traced to any
session: every agent dispatches as the shared account and nothing in
the run says who asked or why.

- workflow_dispatch input requested_by (string, required): lane label
  or session that requested this dispatch. The REST API does not
  enforce required string inputs, so validate-production-boundary fails
  closed with ::error on prod when it is empty or whitespace, and
  echoes requested_by=<value> into the log.
- run-name renders environment, mode and requester, falling back to
  the event name and actor for non-dispatch triggers.
- test_workflow_contracts.py pins the input contract, the run-name
  reference, and the prod rejection of an empty requester (hermetic
  bash run of the boundary step).
- ci-budget.yaml: refresh the dispatch-input inventory for the new
  input and record the conventional one-minute bump plus rationale on
  every gcp_backend.yml job (dispatch count is unchanged; the gate
  requires an explicit budget change for any input change).

Dispatchers must pass -f requested_by=... once this merges; infra
updates bin/omi-deploy-prod right after (a dispatch in between fails
closed, which is intended).

* perf(backend): defer heavy LLM provider imports out of per-file test startup

Backend unit shards run one pytest process per test file, and every file
that reaches utils/llm/clients paid for the Anthropic SDK, the
langchain-anthropic binding, and (via utils/llm/providers) the google gRPC
stack at import time, even though those clients are only constructed on
use. With ~1/3 of the 2314-file suite importing this chain, full-suite
shards carried ~763 redundant provider imports, which is part of why shard
walls now drift past the 720s regression budget (flaky overages of 727s,
746s, and 841s on 2026-10-26 with every test passing).

Resolve the bindings on first use instead: construction sites go through
materialization helpers, module __getattr__ keeps from-imports and
mock.patch targets working, and TYPE_CHECKING imports keep the pyright
lane unchanged (0 errors). Interleaved A/B on the same host: importing
utils.llm.clients drops from a median 1.31s to 0.90s (-31%) and 3167 to
2014 loaded modules per affected process; at runner speed that removes
roughly 20s of wall from a full-suite shard, permanently, and shrinks the
slow tail that trips the budget.

* ci(deploy): extend the requester gate to prod traffic repair

Luna round 1 on #23694 (P1): repair-traffic-only skips
validate-production-boundary, so a prod traffic mutation could run
without a requester when the REST API omits the required input.
The repair-traffic Validate Environment Input step now fails closed on
an empty or whitespace requested_by for prod and echoes it into the
log, exactly like the boundary step. Contract test covers the repair
path hermetically.

* chore(ops): prepare dry-run source image retention policy

Render a local cleanup-policy proposal that retains deployed and rollback
digests, named releases and recent versions. Keep all images whenever
reference coverage is incomplete. No cloud writes or active apply path.

* perf(llm): trim redundant prompt fields and reuse exact Vertex embeddings

* perf(llm): separate notes dedupe for synthetic model qualification

* chore(ops): hold registry proposal until OCI graph coverage is complete

Require explicit OCI manifest graph coverage alongside runtime, Jobs and
rollback evidence. A missing graph attestation keeps every image. Add the
reviewer's regression scenario and document the fifth coverage surface.

* perf(llm): remove the retired embedding runner import

* perf(llm): stage embedding reuse until the batch outcome is known

* docs(backend): add why-headers to hot backend files

State what each file owns and the non-obvious constraint it upholds, with
links to the owning ARCHITECTURE/runbook docs. Comments only; no code
changes.

* docs(app): add why-headers to hot app files

State what each file owns and the non-obvious constraint it upholds, with
links to the owning contract docs. Comments only; no code changes.

* docs(desktop): add why-headers to hot macOS Swift files

State what each file owns and the non-obvious constraint it upholds, with
links to the owning contract docs. Comments only; no code changes.

* check: require purpose headers on new first-party source files

Fails when a file added in the diff (backend/*.py, app/lib/*.dart,
desktop/macos/Desktop/Sources/*.swift, desktop/macos/agent/src/*.ts)
lacks a header: Python module docstring first, or >=2 comment lines
before the first non-import code. Excludes tests, generated files,
__init__.py and files under 40 lines, thresholds justified in the
script. Registered in both local and ci lanes with a test suite.

Instance: #14527 merged the 231-line headerless
app/lib/backend/http/api_result.dart (the C3 typed-result contract).

* docs(macos): trim AGENTS.md, move detail to owning docs

desktop/macos/AGENTS.md: 535 lines / 46,552 bytes -> 348 lines / 29,402
bytes, budget ratcheted 560/47,000 -> 380/32,000.

Moved, not deleted, per .github/agent-docs/doc-maintenance.md:
- INV-6 write-path contract, PR definition of done, gauntlet gate policy,
  and live-vs-hermetic table -> docs/chat-continuity-write-path.md
  (cross-linked with product/invariants/chat-continuity.md); the guide
  keeps the invariant and the core never-rules inline. The gauntlet
  script pointers that named the old AGENTS.md sections now point at the
  new doc.
- Product analytics integrity contract -> docs/analytics-integrity.md;
  privacy and product-authority hard rules stay inline.
- Release-train mechanics, signed-smoke scope, recovery, backend
  deployment workflows, and the Codemagic CLI -> docs/release.md (merged
  with its existing promotion/recovery detail); the guide keeps the
  operator never-rules inline.
- Firebase quick-connect snippet -> docs/firebase-connection.md.
- Changelog guidelines -> changelog/README.md; the kind:none
  anti-footgun stays inline. Added a kind:none fragment for this
  internal-only edit per that rule.
- Agent-runtime stamp-cache detail and incomplete_runtime_payload ->
  README.md, which already owned the fast lane, dev-feedback loop, and
  suite worker isolation (those paragraphs are now cited, not duplicated).

Dropped as generic or duplicated with a verifiable owner: pinned
swift-format/SwiftLint versions (wrapper scripts), test-quality marker
syntax (check_desktop_test_quality.py), ps aux | grep Omi, the
dev-instance primary-checkout note (script header).

Safety rules (production bundle protection, named bundles, signing/TCC,
backend URL env rules, never/must clauses) remain inline.

* check: reword new-file header docstring to avoid a deferred-work marker

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

* docs(app): declare comment-only header changes as internal

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

* docs: correct header claims and restore smoke safeguards after review

Header check now rejects empty docstrings and marker-only comments, and no
longer treats a rename as a new file. Corrects three headers that overstated
what the code guarantees, keeps the signed-smoke safeguards visible in the
macOS guide, and fixes the incident citation's line count.

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

* feat(firmware): promote tested CV1 images with staged rollout

* fix(firmware): identify OTA cohorts and preserve blocked version safety

* test(firmware): initialize OTA request test environment

* fix(firmware): bind CV1 promotion to the tested attempt and bytes

* docs(api): export firmware rollout device_id to the app-client contract

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

* chore(desktop): regenerate API types for firmware device_id

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

* chore: regenerate TypeScript API types for firmware device_id

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

* fix(ci): exercise extracted CV1 OTA staging and publication guards

* fix(ci): read complete immutable Swift blobs for UI approval

* chore: keep safe_mode.c on main's canonical clang-format

The branch carried a brace-style-only delta that CI's clang-format
rejects; the snapshot initializer is semantically identical either way,
so main's formatting wins.

* fix: give the emulator proof's fake consumer clock a monotonic reading

Main's lease-hold cap (#24554) reads time.monotonic() on entering the
heartbeat loop, but this proof injects a frozen SimpleNamespace clock
that only carried time(). Pin monotonic at T0 so the cap stays inert
and the transient-retry semantics under test are unchanged. Same-root
failure is currently red on main's own backend-emulator-proofs run.

* chore: land main's canonical safe_mode.c formatting

The previous fix was re-styled by the local pre-commit hook's newer
clang-format (19+ changed cast-designated-initializer spacing), which
CI's clang-format 18 then rejects. Commit main's exact blob with the
hook pinned to clang-format 18 so local hooks and CI agree.

* test: record the #24392 uncertain-paid-submission contract for Soniox 5xx

#24392 documented that a 5xx from the paid transcription POST is
uncertain and stays held (submitted=True, no duplicate transcription),
but the stale assertion in test_batch_vendor_clients.py still expected
submitted=False, which is why main's own Backend Unit Tests shard 3/8
has been red since it landed. Explicit refusals (402 credit, 429 rate)
keep submitted=False; only the uncertain 5xx case moves.

* Drop native-audio-replay-deps lane: main evolved the inline replay design, helper script superseded

* Restore main's suite-wide pytest plugins: per-file gating keeps the Werkzeug import chain out of isolated files

* fix(eval): label unnamed viewer voices through the SpeakerLabeler authority (#23381); raw ids stay transport keys

* fix(ci-budget): close the build-image rationale string the dispatchtag union left open

* fix(eval): import the labeler from the display authority and keep tainted voice ids out of interpolations

* fix(firmware): guard the changelog array expansion for bash 3.2 under set -u

* fix(tests): match the deferred-SDK clients.py/providers.py seams — stale source grep and guardrail inventory

* test(enrichment): match main's emulator clock stub — monotonic advances with the consumer clock

* test(lifecycle): restore main's PhaseMetrics gauge expander and the blocked_byok row metric the fold's merges dropped

* fix(explainer): match SCRIPT tags case-insensitively when extracting the embedded script (CodeQL Bad HTML filtering regexp)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: David Zheng <[email protected]>
Co-authored-by: David Zhang <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backend Backend Task (python) needs-maintainer-review Needs a human maintainer to sign off before merge positive-signal Automation verified a genuine fix/quality contribution

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants