Repository navigation
fix: make owner recognition refusals attributable - #21235
Conversation
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
| @model_serializer(mode='wrap') | ||
| def _serialize_match_scores(self, handler, info): | ||
| data = handler(self) | ||
| if info.mode == 'python' and self.owner_recognition_diagnostics: |
There was a problem hiding this comment.
🔒 Agentic Security Review
Severity: MEDIUM
The wrap serializer re-injects owner_recognition_diagnostics into default Python model_dump(). Official JSON responses omit it (exclude=True / mode='json'), but production integration sinks do not: conversation_to_dict() uses that Python dump and only strips speaker_match_scores; redact_conversation_for_integration() also leaves this field in place. Developer webhooks and installed-app payloads therefore POST uid, conversation/socket/recording ids, speaker scopes, owner-profile availability, and private-cloud/endpoint refusal reasons to third-party URLs.
Impact: Internal owner-recognition diagnostics leave the first-party boundary on every conversation_created webhook and app-integration dump, even though they are documented as omitted from client JSON/schema.
Reviewed by Cursor Security Reviewer for commit 7ae53d1. Configure here.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7ae53d1079
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if key not in rows or row.get('sequence', 0) >= rows[key].get('sequence', 0): | ||
| rows[key] = row | ||
| return normalize( | ||
| { | ||
| 'live': list(rows.values()), |
There was a problem hiding this comment.
Preserve current generations when capping merged diagnostics
When a stale processing snapshot is merged after a concurrent live update, distinct incoming rows are appended after all current rows and normalize() retains the last four. For example, merging four current generations with four different generations from the stale snapshot discards every current generation and restores only the stale ones, contradicting the intended monotonic merge and losing the live attribution this change is meant to preserve. The cap should prioritize current rows while using sequence numbers only to replace matching keys.
Useful? React with 👍 / 👎.
| if owner_diagnostics.FIELD in write_data: | ||
| payload[owner_diagnostics.FIELD] = write_data.pop(owner_diagnostics.FIELD) | ||
| _merge_owner_diagnostics(payload, existing) |
There was a problem hiding this comment.
Merge diagnostics even when processing omits transcripts
When persist_processing_result_with_lifecycle() handles a server_recovery result, it removes transcript_segments before calling this helper, so the existing early return prevents these new merge lines from running. The later transaction.set(..., merge=True) then writes the processor's stale owner_recognition_diagnostics field wholesale, which can overwrite concurrent live generations or the stored first-resolver summary; diagnostic merging needs to occur independently of whether transcript segments are present.
Useful? React with 👍 / 👎.
| elif raw.get('person_id') or raw.get('is_user'): | ||
| _observe_refusal(speaker, 'already_labeled', raw.get('speaker_id_scope')) | ||
| elif raw.get('speaker_id') in speaker.speaker_to_person: | ||
| _observe_refusal(speaker, 'already_mapped', raw.get('speaker_id_scope')) |
There was a problem hiding this comment.
Attribute segments that lack a speaker ID
When speaker identification is enabled and profiles are loaded, a transcript segment whose optional speaker_id is None falls through this helper without recording any reason, after which should_queue_speaker_embedding() rejects it because the ID is missing. These inputs therefore remain unattributed even though missing_speaker is explicitly part of the diagnostics contract; handle the missing ID before testing map membership.
Useful? React with 👍 / 👎.
| prior = getattr(conversation, 'owner_recognition_diagnostics', None) or {} | ||
| live = contract.normalize(prior).get('live', []) | ||
| row['socket'] = live[-1].get('socket', '') if live else '' |
There was a problem hiding this comment.
Carry the recording ID into resolver summaries
For a processed conversation with retained live diagnostics, the resolver copies only the socket from the live generation even though that row also contains the recording ID. Consequently resolver_exit logs and the persisted first_resolver summary lose recording-level attribution, contrary to the documented claim that resolver exits carry the same attribution as live refusals; copy the selected row's recording value as well.
Useful? React with 👍 / 👎.
| except Exception: | ||
| pass # Optional diagnostics cannot alter the function's result or exception. |
There was a problem hiding this comment.
Report resolver-diagnostic merge failures
If sanitizing or merging existing diagnostic metadata raises, this new fail-open branch silently drops the first-resolver summary, so operators cannot tell that the persisted diagnosis was lost. Keep the resolver observational, but call the shared record_fallback helper before continuing rather than swallowing the degradation without telemetry.
AGENTS.md reference: backend/AGENTS.md:L312-L312
Useful? React with 👍 / 👎.
| except BaseException: | ||
| if row is not None: | ||
| row.add('failed') | ||
| row.observe('extraction_failed') |
There was a problem hiding this comment.
Do not classify cancellation as extraction failure
When a live match is cancelled while _extract_query() is awaiting the embedding executor, asyncio.CancelledError is caught here because it derives from BaseException, so the summary increments failed and records extraction_failed; the outer observe_match wrapper then also records cancelled. Drain or shutdown cancellation is therefore misreported as a provider/extraction failure. Let CancelledError propagate separately so only the cancellation reason is recorded.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c16159a45e
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| OMI_SPEAKER_ID_MATCH_EXITS_TOTAL.labels(reason=reason).inc() | ||
| if reason != 'embedding_budget': | ||
| logger.info('speaker_id_exit reason=%s speaker=%s session=%s', reason, speaker_id, self._session_log_id()) | ||
| self.diagnostics.observe(reason, self._voice_scopes.get(speaker_id, '')) |
There was a problem hiding this comment.
Preserve attribution for exits after generation stop
When a match crosses a rollover or drain boundary, clear()/stop() closes its diagnostic row before the post-await _drop_reason() records stale_generation (and cancellation can follow the same path). LiveGeneration.observe() then returns immediately for the closed row, while this change removed the previous speaker_id_exit log, leaving only an anonymous Prometheus increment and no UID/conversation/socket attribution for precisely these late exits. Emit a bounded attributed log for the selected old generation without mutating its frozen summary.
Useful? React with 👍 / 👎.
| except Exception: | ||
| observation.observe('flush_failed') |
There was a problem hiding this comment.
Report failed boundary diagnostic writes
When this metadata-only write fails after the normal drain path has called diagnostics.stop(), the generation is already closed, so observation.observe('flush_failed') is a no-op and the exception is swallowed without any log or fallback metric. Because boundary_snapshot() has already permanently claimed the attempt, the lost diagnostic is never retried and operators receive no indication of the degradation; record the failure through the shared fallback helper before continuing.
AGENTS.md reference: backend/AGENTS.md:L312-L312
Useful? React with 👍 / 👎.
| if owner_diagnostics.FIELD in write_data: | ||
| payload[owner_diagnostics.FIELD] = write_data.pop(owner_diagnostics.FIELD) | ||
| _merge_owner_diagnostics(payload, existing) |
There was a problem hiding this comment.
Recompute score presence after the size guard
When a processing payload contains generated scores and diagnostics, this merge stamps the live row with scores='present', but both processing callers run _guard_match_score_size() afterward. If the completed document crosses the 900 KiB guard, that later step deletes speaker_match_scores while leaving the diagnostic marker unchanged, so the persisted attribution falsely reports that its supporting scores survived; correlate score presence only after the final size guard or clear the marker when the guard drops the field.
Useful? React with 👍 / 👎.
| if row is not None and not row.closed: | ||
| row.data['scope'] = contract.identifier(segment.get('speaker_id_scope', '')) | ||
| return await fn(self, speaker_id, segment) |
There was a problem hiding this comment.
Keep each match scope task-local
Concurrent speaker matches share one LiveGeneration, so storing the current segment scope directly in row.data before awaiting the wrapped matcher is racy. Another match can overwrite this value while the first is awaiting embedding or authority; early exits then pass an empty scope because _voice_scopes is not populated until later, causing the first refusal log to be attributed to the other task's scope. Carry the segment scope in task-local context or pass it explicitly when recording the exit.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b34bff626b
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if ( | ||
| document_size.estimate_firestore_document_bytes(candidate, path if isinstance(path, str) else None) | ||
| <= 900 * 1024 | ||
| ): | ||
| payload[owner_diagnostics.FIELD] = value |
There was a problem hiding this comment.
Report size-guard diagnostic drops
When an existing conversation makes the candidate exceed 900 KiB, this branch silently leaves the already-popped diagnostics out of the payload. The content write proceeds, but operators receive no fallback event explaining why the new diagnostic record disappeared, making this capacity degradation indistinguishable from a pipeline that produced no diagnostics; record the rejection through the shared fallback helper before omitting the field.
AGENTS.md reference: backend/AGENTS.md:L312-L312
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b7a8771859
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| # transaction still clears a projection that is actually on the | ||
| # document (a finalize overlapping capture). | ||
| invalidate_client_processing=False, | ||
| **({'owner_recognition_diagnostics': diagnostic_snapshot} if diagnostic_snapshot else {}), |
There was a problem hiding this comment.
Handle failed identity-bearing diagnostic flushes
When the final drain has any speaker identity state, the closed diagnostic snapshot is only piggybacked on update_conversation_segments; if that Firestore call raises, the outer final-flush handler merely logs, and unlike the metadata-only branch above, this path neither claims/persists the boundary snapshot nor emits the shared fallback event. Because the socket then tears down without another flush, a transient failure permanently loses the terminal summary specifically for sessions that produced identity state; record the degradation and preserve a metadata-only fallback path for this branch.
AGENTS.md reference: backend/AGENTS.md:L312-L312
Useful? React with 👍 / 👎.
| self.diagnostics.profile( | ||
| diagnostic_generation, | ||
| eligible, | ||
| self._owner_load_failed, | ||
| USER_SELF_PERSON_ID in self.person_embeddings, |
There was a problem hiding this comment.
Do not classify missing profiles as load failures
For an eligible user with no stored owner embedding, the branch above records profile_missing and sets _owner_load_failed = True; passing that same boolean here makes LiveDiagnostics.profile() immediately record profile_failed as well. Invalid stored embeddings similarly produce both profile_invalid and profile_failed, so routine absence or malformed data inflates the operational-failure bucket and leaves the generation's latest reason as a generic failure instead of the specific cause. Track exceptions separately or suppress profile_failed when a missing/invalid reason was already recorded.
Useful? React with 👍 / 👎.
# Restore live matcher scheduling and query cadence After #21181's listen rollout, the supplied matched five-hour owner-identification rate fell from 35.5% to 29.6% at similar conversation volume. The analysis identified scheduling and evidence-trajectory changes as plausible contributors, without establishing causality. This PR restores the scheduling/query cadence preceding #21181 while retaining its budget instrumentation and all current authority/stale-generation guards. The separately approved listen deployment rollback is outside this PR. The freshly fetched main snapshot, including diagnostics #21235 (`314037874f`), is merged through a normal two-parent merge commit; no rebase or force-push is used. Each provider update gets its own bounded FIFO metadata entry. No untried, near-owner, duration or age priority applies, and same-voice updates are not coalesced. Restore the original runner/task admission order and existing per-voice lock serialization. A dequeued update contributes its own interval to the existing minimum-evidence accumulation; successful extraction clears pending metadata and does not autonomously requeue unselected leftovers. A subsequent provider update is required to drive another query. Already embedded audio stays covered, so overlapping updates cannot fabricate evidence. The FIFO wrapper snapshots enqueue-time matcher generation and keeps only timing/identity metadata. Generation/conversation and final authority fences remain in place. Thresholds, margins, manual veto, contention, the 12-attempt voice cap, the socket's 16-token burst and 240/hour refill, and the 16-task ceiling are unchanged. This does not include #21222 voice recovery. ## Telemetry compatibility The metric schemas, reservation/extraction accounting, exclusive caps and first-block log from #21181 remain intact. All merged #21235 diagnostics hooks are preserved: profile/begin, match/query decorators, live comparisons, budget observations, evidence pending, scores/publication progress, refusal observations, checkpoint/stop and generation binding. `queue.qsize()` counts FIFO provider updates, including separate entries for one voice: - `omi_speaker_id_budget_exits_total{cap=voice|socket|both}` counts exclusive denied reservations. Summing caps equals legacy `embedding_budget` exits. Repeated denials are not distinct exhausted owners. - `omi_speaker_id_embedding_attempts_total{outcome=reserved|succeeded|failed}` counts spent reservations and encoding/extraction completions, including failure/cancellation. Completion may lag reservation; failures spend quota without refunds. - `omi_speaker_id_budget_voices_total{cap=voice|socket|both}` counts the first denial per numeric voice/matcher generation; `omi_speaker_id_budget_sockets_total{cap=voice|socket|both}` counts the first denial of any kind per socket. Each labels that first cap, not every later cap transition. - `speaker_id_budget_first_block` retains uid/socket/recording/conversation/generation/scoped speaker/attempts/tokens/evidence and pending seconds/cap. One line per first blocked voice-generation, no repeated budget log per update. No text/audio/embedding payloads. UID remains in logs only. Each of the four metric families retains three closed labels: 12 counter series plus 12 `_created` series per target. No user, socket, conversation, generation or speaker labels are added. Owner-target decision events are not a count of GPU calls or true-owner voices; pending reductions alone do not demonstrate recognition improvement. ## Regression coverage and validation The real runner pins last-token FIFO in both arrival orders for a tried owner needing its final initial-evidence clip versus an untried non-owner, and for an untried owner versus a tried rejector. A long unresolved turn extracts one centered query, does not self-requeue or spend again without a provider update, and still queries uncovered audio when an ordinary update arrives. Additional checks pin separate short-update extraction, overlap deduplication, a 100-update queue cap, metadata-only entries, and queued generation/conversation rejection. - Credential-isolated `backend/test.sh` after merging main: **479 passed across 16 files**, including both FIFO diagnostics cases, all merged live/resolver diagnostics tests and existing scheduling, telemetry, budget, authority and publication regressions. - Negative control against unchanged #21181 through the same harness: the tried-owner-first case, untried-owner-behind-rejector case, and long unresolved buffer fail (3 failed, 2 passed). All pass on the restored scheduler. - Relevant `backend/scripts/run-unit-ci.sh` shards `6/2` (FIFO diagnostics) and `6/4` (cadence): **1,293 and 1,395 tests passed**, 52 files each; Pyright zero errors. Exact-head `make preflight`: **32 checks passed** on `5c899a76c1234211e128620d90bed8270db7be10` in 820.79 seconds. All backend test entrypoints use Google credentials/project unset and a fresh private `CLOUDSDK_CONFIG`. Publication uses the full pre-push hook with no skip hatch. Failure-Class: new Adds `FC-live-speaker-scheduling-regression` with reusable real-runner guards in `backend/tests/unit/test_speaker_queue_fairness.py` and the existing telemetry/budget suites. The old fairness/coalescing assertions are replaced with the restored cadence contract. The only merge conflict was the old priority-test authority latch; keep the FIFO regressions instead of restoring that retired fixture. New diagnostics tests execute the real FIFO runner: two short updates create two query attempts, one sufficiently evidenced owner comparison, progress/refusal records and a rollover stop with two pending same-voice entries. A second test records a short-window refusal and socket-budget denial before a drain snapshot, without extraction or comparison. Closed rows reject stale FIFO work without painting a successor generation. Diagnostics call/decorator ASTs in matcher, transcripts and conversation controller match current main exactly. Product invariants affected: none (`scripts/pr-preflight --suggest` and metadata validation). ## Reviewer risks Restoring FIFO also restores its tradeoffs: repeated updates can occupy multiple queue/task slots, same-voice tasks wait on the existing lock, a full 100-entry queue can drop later updates, and a late untried owner has no priority over earlier rejectors. This is deliberately the earlier scheduling behavior; no fairness guarantee or owner-coverage uplift is claimed. Calls and latency can change within unchanged caps, and queries remain bounded at ten seconds. Unselected leftovers require a future provider update, so a voice can remain unresolved when updates stop. Production recovery must be judged separately with matched owner outcomes, combined single-speaker/identified share, actual reservation volume, contention and latency. No production records/logs or api.omi.me calls were used. #21235 is integrated with its hooks and accounting intact. #21222 is untouched and must be rebased separately later. FIFO pending-queue counts are documented as update counts. <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/BasedHardware/omi/pull/21281?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="View guided diff" src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a> <a href="https://www.cubic.dev/action/auto-fix/pr/BasedHardware/omi/21281?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F21281&source=description" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"><img alt="Turn on auto-fix" src="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"></picture></a> <!-- End of auto-generated description by cubic. -->
Restore recognition opportunities for ordinary voices without applying broad priority or coalescing to the restored FIFO scheduler. An already proven rejector with 80 queued updates now has one pending entry behind a late owner; the tried owner still receives its final initial-evidence clip in original arrival order against untried voices. Only three completed, sufficiently evidenced comparison rounds that clearly reject every enrolled candidate can prove a rejector in the current generation. A completed accept, near-owner result, margin ambiguity, contention or invalid/empty comparison prevents proof for that generation. Pending evidence, failed requests and duplicate audio never count as completed rounds. Current distances are rechecked, and known manual authority prevents demotion. Proof resets on rollover. Proven rejectors coalesce only pending timing ranges and the latest segment ID, without crossing generation/conversation/provider-scope fences; ordinary updates keep separate FIFO entries and unchanged clip selection. Rejectors cannot reserve the last two socket tokens. No autonomous leftover self-requeue, new tokens, refunds, refill change or recovery tranches are added. The existing 12 attempts/voice, 16 socket burst, 240/hour refill, 16 tasks and ten-second query cap remain enforced. This cannot raise the GPU request ceiling; actual use may redistribute toward ordinary voices. Thresholds, margins, manual veto, contention and stale/authority fences stay unchanged. All #21181 counters/first-block logs and #21235 query/comparison, budget, progress/refusal and qsize stop hooks remain compatible. Telemetry: - omi_speaker_id_rejector_demotions_total{action="deferred|coalesced"}: deferred counts newly created/converted pending rejector entries placed behind ordinary work; coalesced counts updates absorbed into an existing rejector entry. Repeated inspection does not recount them. This measures scheduling opportunities, not accepts or saved GPU requests. - omi_speaker_id_rejector_tail_denials_total{reason="reserved_tail"}: otherwise-admissible rejector requests denied at the shared tail, spending neither token nor voice attempt. Actual voice/socket exhaustion still uses the old cap split, whose sum continues to equal the legacy embedding_budget count. The distinct rejector_tail_reserved exit/diagnostic reason is added to the closed vocabulary. - The two new counters have three preinitialized total series and three created series per target, with closed labels and no UID/socket/recording/conversation/scope/speaker labels. Existing four budget/extraction counter families retain their 12 total plus 12 created series. The new exit reason adds one possible legacy exit series (and created series); no existing meaning is changed. UIDs remain only in the existing bounded logs. Expected benefit: compare owner_identified excluding single_speaker_all_owner against same-hour prior days at comparable conversation volume after the restored scheduler deployment has settled. Positive demotion/tail-denial rates establish opportunity; owner comparisons/accepts per conversation should rise without increased false-owner contention, while reservation/extraction and GPU request rates per conversation stay within unchanged ceilings. The new counters alone do not prove recognition improvement. No production data/log reads or api.omi.me calls were used. Validation: exact head 81b415a passed all 32 make preflight checks in 1,211.36 seconds. Relevant run-unit-ci.sh shard 6/4 passed 4,592 tests across 292 selected files, with zero typecheck errors. The 502 matcher-focused cases across 17 files passed with an isolated rollover-file retry after an initial CPU-time guard failure. Both real-runner revocation paths assert extraction only of (40,44) for the revoked voice, followed by the ordinary voice's (50,55), excluding the old (30,34) pool. All tests used backend/test.sh or its documented CI wrapper, with Google credentials/project stripped and temporary CLOUDSDK_CONFIG. An additional unchanged-main messaging QA file passed all 24 assertions but repeatedly hit its existing 0.30-second CPU-time guard (0.38–0.42s) in an unrelated projection test; no guard/allowlist/test source was changed. Normal pre-push hooks passed, including all 32 preflight checks (727.29s), zero-error typecheck, runtime-image closure, all 36 changed-file cases and OpenAPI/app-client compatibility. Terminal exact-head CI is green: 12 successful workflows and all 60 current checks completed, with no pending/failure/cancellation. All six backend shards, guardrails, stack gauntlet, hermetic E2E and hygiene passed; prior and retry evidence is in result-targeted-A.md. Failure-Class: FC-live-speaker-scheduling-regression This instance-fix PR keeps the existing violated_contract and all other registry narrative unchanged. It only re-adds test_speaker_targeted_fairness.py as a canonical guard artifact, as permitted by the protocol. The approved ordinary/proven-rejector contract narrowing will land through the separate registry-only lifecycle PR #21331; the validator is unchanged. ## Product invariants affected none Reviewer risks: an already dequeued task stays under its existing voice lock/task ceiling; demotion applies to pending entries. Under sustained ordinary work, rejectors can wait longer. Coalesced rejector audio may change their subsequent centroid within unchanged thresholds. Manual protection uses authority already observed by the matcher; the final receipt/veto gate still independently controls every publication. PR B/#21222 recovery changes are excluded and will wait until PR A merges. The rejection-history/tail primitive is isolated in speaker_rejector.py and timing union in speaker_queue.py; speakers.py stays at 1,495 lines without a line-count exception. Current origin/main (543e520) was merged normally. The only conflict was the unrelated Telegram clock regression; main's current relative in-window timestamp fixture was kept intact, replacing the branch's older clock seam. No guard, timeout, force-push or skip hatch is used. Earlier and superseded validation is recorded in result-targeted-A.md. Review follow-up: deferred entries retain their earliest enqueue order and latest segment ID. Before merging, the queue captures that latest update's original start/end/duration (including when merging an already pooled entry). On manual or close-profile proof revocation, it drops pooled ranges and restores that interval before ordinary clip selection. The two real-runner revocation tests now assert (40, 44) only for that voice, excluding the formerly pooled (30, 34). The approved fractional tail cutoff remains <=2, with no other scheduler or decision-policy changes. <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/BasedHardware/omi/pull/21298?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="View guided diff" src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a> <a href="https://www.cubic.dev/action/auto-fix/pr/BasedHardware/omi/21298?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F21298&source=description" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"><img alt="Turn on auto-fix" src="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"></picture></a> <!-- End of auto-generated description by cubic. -->
Target fresh-audio recovery at voices that still have a plausible owner match or have not reached a completed decision. After the initial twelve attempts, a current calibrated owner near-miss or undecided voice can receive at most two +3 tranches. Proven rejectors and completed clearly-far voices receive none; a voice that becomes ineligible cannot spend unused extra attempts from an existing tranche. Current profile rechecks may change eligibility without renewing the allowance or freshness ledger. Merged fetched origin/main 7cc32e0 (including #21235 diagnostics, #21298 targeted scheduling and #21331 contract revision) into the existing lane/matcher-voice-recovery branch. This reuses #21222, preserves its reviewed history and introduces no rebase or force-push. Ordinary FIFO cadence, proven-rejector coalescing/tail policy, revoked-proof latest-original clip selection and no autonomous self-requeue all remain intact. Rollover fix after Grok review: snapshot a bounded already-decided marker with retained quota before clear(). Across profile/donor awaits, a missing current decision cannot become undecided and grant recovery. A current rebuilt near-owner row may qualify again; uncarried quota resets the marker. It supplies neither identity authority nor rejector scheduling proof. Real-runner tests cover extraction finishing before restore and restore finishing before extraction, with an owner actually accepted on attempt twelve: no query/grant/token spend, unchanged checkpoints, and the carried three-clip centroid preserved. Eligibility reuses the existing completed-comparison ledger, any already-decided carried/manual row and the unchanged owner_near_miss predicate: owner nearest, distance in [0.65,0.70), existing runner-up gap >=0.10, and no accepted/contended result. Other completed non-near results receive no extra quota. No acceptance threshold, margin, manual veto, contention, stale/authority rule or new authority read is introduced. Grok-approved freshness/selection is retained: >=10 distinct physical PCM seconds after the checkpoint; 30-second monotonic cooldown; at most two grants; independent hard ceiling 18/voice-generation; post-watermark gapped phrases pooled first up to ten seconds, with older fallback only below the unchanged evidence minimum. A grant checkpoints all current PCM only when the selected post-checkpoint query can actually be reserved under its increased allowance. Duplicates, overlap, forged timestamps, prebuffered/evicted credit, ring replacement, scope changes and lifecycle churn cannot renew credit or tranches. Failures/cancellation spend both voice and socket quota. The shared 16-token burst/240-per-hour refill, 16-task ceiling and ten-second queries are unchanged. Telemetry: - omi_speaker_id_recovery_tranches_total{tranche="first|second"} counts each grant once with its first synchronous reservation. - omi_speaker_id_recovery_acceptances_total{target="owner|person"} counts the first automatic acceptance per voice-generation after a successful extra extraction. It excludes manual, stale, failed and contended results, and does not recount reinstatement or carried state. - omi_speaker_id_recovery_denials_total{reason="proven_rejector|clearly_far|completed_not_near_owner"} counts attempted extra reservations refused by eligibility, including grant requests and unused attempts in an already open tranche. Proven rejector uses the unchanged three-round proof; clearly_far covers a completed clear rejection before that proof; completed_not_near_owner covers other decided results outside the current calibrated predicate, including retained decided voices whose current row is absent during refresh. Denials spend nothing and do not advance grant checkpoints. Freshness/cooldown/socket/tranche/attempt refusals are not included in this eligibility family and keep existing cap telemetry. These are refusal events, not unique voices or saved GPU calls. - Recovery adds seven preinitialized total series and seven created series per target with closed labels. #21181 budget/extraction families, first-block log and cap-sum/legacy equality, #21235 diagnostics, and #21298's three rejector series remain compatible. No UID/socket/recording/conversation/generation/scope/speaker labels or new log payloads. Maximum extra GPU allowance is six calls per qualifying voice-generation (+50%), each <=10 seconds, all within the unchanged socket envelope 16 + 240*t for t hours since creation. Actual GPU utilization may rise inside that envelope. Production benefit is not established by tests or the new counters: compare owner_identified excluding single-speaker at comparable-volume same-hour baselines, owner comparisons/accepts per conversation, first/second grant and denial rates, demotion/tail-denial incidence, extraction failures, contention and reservations/GPU calls per conversation. No production data/log reads or api.omi.me calls were used. Validation for rollover revision 377bf2a: 599 focused tests across 22 files, including 36 recovery cases; relevant run-unit-ci.sh shard 6/1 passed 5996 tests across 293 selected files with zero typecheck errors. Exact committed-head make preflight passed all 32 checks in 271.57s. The new two-interleaving real-runner test failed twice on the reviewed head and passes with the guard. Tests use backend/test.sh (or the documented CI wrapper), stripped GOOGLE credentials and temporary CLOUDSDK_CONFIG. Initial shard exceeded the standard CPU guard in unchanged sync-capture permutation tests; the same-guard focused reproduction and full shard rerun passed without allowlist/limit changes. Initial preflight hit the 1500-line file ratchet; a one-line comment shortening fixed it without executable changes or exception. Normal push hooks passed, including all 32 preflight checks (142.88s), zero-error typechecking, runtime closure, changed-file tests and OpenAPI compatibility. Terminal exact-head source CI is green: 12 successful workflow runs and 60 completed checks (34 success, 26 expected skips), with no pending/failure/cancellation. All six backend unit shards, guardrails, hermetic E2E, listen stack gauntlet and CodeQL passed; no skip hatch, rebase or force-push. Failure-Class: new The new FC-live-speaker-fresh-recovery definition owns the bounded allowance/provenance/eligibility primitive and registers the real-runner, budget and telemetry guards. Root cause: fixed initial quotas can stop a still-plausible or undecided voice before usable clean PCM arrives; broad recovery would also spend scarce requests on already clear rejections. Durable prevention: preserved physical/capture high-watermarks plus current decision eligibility at each extra reservation, independent hard caps and real-runner guards for gapped selection, no checkpoint on old fallback, allowance overshoot, actual scope changes, carried limits, each denial reason, withdrawn unused quota, retained decided rows and profile rechecks. ## Product invariants affected none Reviewer risks: previously decided retained voices fail closed during refresh until a current decision is rebuilt; this can conservatively deny an opportunity while profiles are incomplete. Truly-owner speech whose current completed result is clearly far is intentionally excluded until current profile revalidation changes eligibility; finished-conversation recognition remains independent. Recovery affects clip selection only after initial exhaustion; its centroid may differ, under unchanged identity rules. An already reserved in-flight call spends quota even if eligibility/authority later changes, with existing publication guards still deciding acceptance. Timestamp reordering/eviction can conservatively lose fresh credit. Denied voices can retain ordinary FIFO work until they meet the unchanged proven-rejector rules; this PR adds no scheduling priority or retry. No merge/deployment is performed by this PR publication.
Fix a deterministic false short-window refusal in live speaker matching:
full received PCM spans lost their last sample when epoch-time
subtraction was truncated back to bytes. In a
receiver-capture/send-proof-to-FIFO-runner reproduction, exactly 2+2+1
seconds of audio produced one extraction and no owner comparison.
Preserving the stored span's integer end now delivers all five seconds,
three initial queries and an owner decision under the existing policy.
One shared byte-window primitive corrects exact full-span ends for both
extraction and physical byte proof. Interior endpoints retain the
existing PCM16 floor; actual gaps, eviction and unavailable/unplaced
capture windows remain refused. Transient restored-sample metadata stays
inside the existing bytes contract; provider timestamps, stored
transcript/audio fields, wire formats, thresholds/margins, manual veto,
contention, authority/stale-generation fences, FIFO/proven-rejector
behavior and recovery ledger are unchanged.
The new
omi_speaker_id_pcm_windows_restored_total{reason="full_span_rounding"}
counts selected candidate windows whose true received PCM reaches their
current extraction floor while the old floored byte count on those
selected windows would not. It is emitted before quota admission; it
counts neither GPU reservations nor unique voices, owner comparisons, or
recognition gains. The single preinitialized closed reason adds one
total series (the shared runtime metrics endpoint suppresses created
series). No IDs or content are metric labels or new log fields.
Recovery's newer pool uses the caller's same floor for this observation,
avoiding an insufficient-new-pool/fallback count. Existing
#21181/#21235/#21298/#21222 telemetry stays compatible.
Production read-only evidence: source main b8076ba, primary listen
6ef38cd; current one-hour aggregate counters show ~34.7k Soniox
outside-send refusals, ~20.4k explicitly wire-race-unplaceable
intervals, ~7.85k short-window matcher exits. The dominant placement
refusals are intentionally fail-closed under an uncertain reported
finalize clock. This PR repairs the independent physical-window defect;
it does not clamp untrusted provider timestamps, enlarge the ring, alter
flags or claim those Soniox intervals are newly placeable. All reads
used server-side Prometheus sums plus whitelisted deployment metadata,
no account transcripts/audio/embeddings/log rows, no api.omi.me, no
deployment or merge.
Request bounds remain twelve initial attempts, at most eighteen with
already-approved eligible recovery, 16 tasks and ten seconds of
PCM/query, all through the unchanged 16-token socket burst and 240/hour
refill. Maximum GPU calls cannot rise beyond those bounds; realized
calls can rise as false minimum refusals disappear (the five-second test
spends 3 versus 1), or fall if an owner accepts earlier and stops
retrying. Failures still spend. Production owner uplift is unmeasured;
this is not a forecast that recovers the unplaced cohort. After
deployment compare restored candidate windows, short exits, actual
reservations/comparisons and owner accepts per conversation;
owner_identified excluding single-speaker vs comparable-volume same-hour
prior-day baselines, plus failures/contention/GPU.
Validation: new test suite 19 cases (four additional cases after the
broader run) and broader 29-file matcher/capture/recovery/authority
suite 778 cases pass through credential-stripped backend/test.sh. Before
the fix all six complete-span/rate cases plus the real runner failed.
Canonical make setup provisioned this worktree's Python 3.11 environment
and refreshed the branch to then-current main. Committed head
2c6f61b passed 32/32 exact-head make
preflight in 491.18s and relevant run-unit-ci shard 2/6 passed 5,398
cases across 293 selected files, with zero typecheck errors. Normal push
hooks passed, including 32/32 preflight (546.30s), zero-error typecheck,
runtime closure, changed-file tests and OpenAPI compatibility.
Exact-head GitHub Actions are terminal green: all 12 workflow runs
succeeded; all six backend shards, guardrails, E2E/gauntlet and security
passed. The first guardrail attempt passed all 2,040 tests then exceeded
its 10-minute total job limit during wrap-up; rerunning only that job
and its dependent aggregator succeeded on unchanged head, without any
timeout/allowlist or source change. The external Cubic check is neutral
because its monthly quota is exhausted; no automated review completion
is claimed. No skip hatch or force-push.
Failure-Class: new
FC-audio-ring-full-span-rounding-loss records integer whole-span
delivery and physical-proof parity with real-runner and
gap/partial/eviction guards. The shared byte-window primitive removes
the repeated arithmetic cause; this is same-clock quantization, not the
existing independent-clock failure class. No existing registry
definition or validator changes.
## Product invariants affected
none
Reviewer risks: realistic epoch-end correction changes a tiny portion of
the PCM and can move a query across an existing evidence floor; actual
utilization/timing can change inside unchanged caps. The candidate
counter is a comparison against old flooring on currently selected
windows, not a historical counterfactual of all scheduler/evidence
states or causal recognition saved. Dominant unplaced refusals remain;
current diagnostics cannot identify what share of production short exits
are true short utterances vs physical truncation vs this rounding
defect. New direct regression cases use synthetic audio and mocked
embeddings; production identity accuracy is not established. No
release/deployment is authorized by this PR.
<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/21353?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="View guided diff"
src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a>
<a
href="https://www.cubic.dev/action/auto-fix/pr/BasedHardware/omi/21353?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F21353&source=description"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"><img
alt="Turn on auto-fix"
src="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->




Owner-recognition refusals previously lacked the account/conversation attribution needed to explain single-speaker misses. Add bounded generation summaries for live admission, extraction, comparison, and stop points, plus attributed resolver exits that distinguish cloud sync being off from an unconfigured embedding endpoint.
Persist metadata-only
owner_recognition_diagnosticswith separate live generations and an immutable first-resolver summary. The shared whitelist/merge primitive caps encoded metadata at 8 KiB, retains at most four generations/eight scopes, excludes client JSON/schema, and preserves current live sequences during processing writes. No transcript, PCM, embeddings, distances, or secrets enter this field. UID remains outside Prometheus labels.Matching, thresholds, reservations, queue ordering, and identity labels remain unchanged. Reuse #21181's cap counters and first-block log;
_reserve_embeddingis untouched to keep clear of the concurrentlane/matcher-voice-recoverywork.CI follow-up (run 38158732376):
A separate inherited E2E failure appeared after main merged #21227: nine memory-read admission failures also occur on main at a36fe08 (baseline run). Merged current main without rewriting history, then reset only the process-wide memory admission allowance in the existing E2E state-isolation fixture. Each case retains the real default burst/refill/in-flight limits; cases no longer consume each other's allowance. No production memory or matching policy changed. The same merge also exposed two memory-cursor unit failures: synthetic sequential page requests exhausted the shared allowance. Their fixture now injects a fresh allowance clock advancing one second per admission, modeling the real refill rather than changing burst/in-flight limits or request budgets. The hydration regression now starts with one admissible document, spends it during the failed scan, then verifies the real hydration charge overruns it while retaining the row; the previous zero-at-entry setup was correctly refused by the new admission gate. The dedicated resilience unit suite still tests actual admission exhaustion. The exemption reconciler's pinned expected set and convergence assertions now include the newly declared map exemption.
Grok follow-up (reviewed head b34bff6):
schedule_finalizationcould stampstop=finalizedand consume the once-only standalone write while the generation remained open. Checkpoints now emitlive_checkpointlogs without mutating or claiming the persisted summary.boundary_snapshotrequiresclosed, and all controller refresh paths flush the old frozen generation after the matcher's existing clear. No drain, queue, reservation, threshold, or label policy changed. The regression holds a real extraction in flight through the early checkpoint, completes an owner comparison before actual refresh/clear, then verifies one closed rollover write contains that comparison and final pending counts. The reentrant/failure test now refuses open checkpoints and claims the drained summary once. Failed optional writes log against the closed generation, not its successor.live_progress; actual refusals retainlive_refusal. The first-reason-per-generation bound remains, and budget refusal logging still reuses fix: attribute speaker budget blocks and schedule queued voices fairly #21181. Parameterized coverage repeats each progress reason 100 times and checks one progress log, zero refusal logs, then a real refusal.Validation: the credential-scrubbed
backend/test.shselection expands to 47 files, including the original suites, all previous CI failures, and every controller/refresh unit neighborhood. At committed headb7a8771859cf4edeb5e675e8a5fcbbf5fa8aed31, 2,442 tests passed across 47 files, exit 0, and full backend typecheck passed with zero errors. Exact-headmake preflightpassed all 34 checks (178.27 seconds), exit 0, before push. Ordinary pre-push hooks remain enabled.Firestore: live summaries piggyback on existing identity writes; the first resolver uses the existing processing write. Standalone diagnostic boundary persistence claims at most ONE attempt per CLOSED socket/conversation/generation before awaiting I/O, including failed attempts. Open finalization checkpoints and active segment-loop flushes add none; repeated/concurrent drain and rollover boundaries cannot retry. For N generations, at most N successful extra document updates can advance the revision, hence at most N such updates can conflict with overlapping late-repair CAS attempts. This is a structural bound, not a measured production collision rate. The rollover write now follows generation closure after finalization is requested, so a late repair that read its revision before this write can abstain; a repair reading afterward is unaffected. There is at most one such extra revision advancement per generation. Transaction contention may repeat reads; it cannot commit extra updates. Frozen summaries can still piggyback without extra writes; a failed standalone attempt can leave only logs until a later existing write.
The metadata map is unqueried and should have a single-field index exemption. This PR declares it in the registry and generated manifest, inherited by descendants (Firestore documentation). This is configuration only: applying destructive exemptions requires the separate approved
field-exemptionsoperation; none were applied to a live project here. Metadata stays capped at 8 KiB (four generations/eight scopes), with a conservative 900 KiB document guard; native map/index overhead is additional. No diagnostic collection, per-segment write, or backfill.Why isn't this a shared primitive instead? It is: one metadata contract and generation/pass observer provide the bounded logging, sanitation, and monotonic merge behavior used by all touched boundaries.
Failure-Class: none
This closes matcher/resolver diagnostic attribution rather than changing a known matching failure class. The billed-read attribution class uses its existing RPC probe and is not the violated contract here.
Product invariants affected
none
Line-Count-Exception: backend/database/conversations.py | 3838 -> 3906 | Attach optional metadata to the existing transaction owners so current content and concurrent diagnostics merge atomically; avoid moving unrelated persistence authority.
Line-Count-Exception: backend/routers/listen/speakers.py | 1493 -> 1516 | Minimal observation hooks only; keep reservation logic and the concurrent matcher budget lane untouched. The reusable observer lives in a separate module.
Line-Count-Exception: backend/routers/listen/transcripts.py | 1508 -> 1560 | Admission, identity-flush and existing drain-boundary observation only; moving the transcript workflow would expand the approved diagnostic scope.
Line-Count-Exception: backend/utils/conversations/speaker_resolution.py | 1608 -> 1644 | Add pass-local reason/count hooks at the existing exits while preserving resolver policy and control flow; the summary primitive is separate.
Line-Count-Exception: backend/database/firestore_index_registry.py | 2160 -> 2162 | Add one unqueried diagnostics map exemption to the authoritative registry; splitting index authority would expand this two-line declaration.
Main merge after Grok's VERDICT MERGE on b7a8771: merge current
origin/main62033e86cb1dd870fd3eb5373b79583f91409c06without rebasing or rewriting history. The only conflict isbackend/tests/unit/test_speaker_queue_fairness.py: preserve this lane's authority-wait interleaving and main's extraction-wait interleaving using one rejector-completion event, retaining all completion, arrival-order, label, and token assertions. Production files merge automatically; no new matching or budget policy changes. Main also brings harness-only burst isolation changes (64 tokens) alongside this lane's per-test reset; production defaults remain unchanged. Main now runs six backend unit shards. Affected tests and exact-head preflight will be rerun before normal push and terminal CI verification.Main-merge head:
f80ff1720cbc049830306e615faee86bacf373f5. Normal pre-commit hooks passed with pinned toolchains; inherited app/web/workflow files match main exactly. The credential-scrubbed 50-file affected backend suite passed: 2,475 passed, 4 emulator-gated skips, exit 0. Full backend typecheck passed with zero errors. Exact-headmake preflightpassed all 34 checks (115.40 seconds), exit 0. Normal push hooks remain enabled; terminal CI will be verified after publication.