Repository navigation
Target fresh-audio recovery at near-owner and undecided voices - #21222
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. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b57dfe8b3c
ℹ️ 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 bounds is None: | ||
| return | ||
| for lo, hi in sorted(ranges): | ||
| positions = ring.proven_byte_ranges(max(lo, self.audio_watermark), hi) |
There was a problem hiding this comment.
Avoid rescanning the full audio ring for every range
When an exhausted voice accumulates up to 128 disjoint pending intervals, this invokes proven_byte_ranges once per interval, and each invocation walks every span in the ring. Because receiver.py records one span per decoded frame, a 120-second ring of 20 ms frames can require roughly 128 × 6,000 iterations for a single match; this took about 80 ms locally and runs synchronously inside _match_unmapped. Repeated matches for exhausted voices can therefore block the listen event loop and delay unrelated WebSocket and health-check work. Traverse the ranges and spans together once, or move the CPU work through the prescribed executor.
AGENTS.md reference: backend/AGENTS.md:L254-L264
Useful? React with 👍 / 👎.
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_diagnostics` with 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_embedding` is untouched to keep clear of the concurrent `lane/matcher-voice-recovery` work. CI follow-up (run 38158732376): - Shard 4's four authority-veto cases already passed the spent-embedding and exit-counter assertions. Only the superseded anonymous log-string assertion failed (line 1303). It now checks the attributed generation summary; every accounting assertion remains intact. No reservation or budget source changed. - Shard 2 observed task starts rather than completions before asserting owner recovery. Reuse only the deterministic test fix from #21222 / b57dfe8: force rejected completion before awaited owner authority, wait for both completions, and retain ordering/token assertions. - Shard 1: classify the new server-authored metadata field as non-projection-family in the pinned schema guard. Also strip it from raw-dict list/integration redaction and cover both locked/unlocked views. - Shard 3: the historical resolver baseline predates diagnostics. Exclude only this additional internal field from the identity-projection comparison, alongside match scores. All PCM byte, cache, identity, evidence, and label checks remain. A separate inherited E2E failure appeared after main merged #21227: nine memory-read admission failures also occur on main at a36fe08 ([baseline run](https://github.com/BasedHardware/omi/actions/runs/38160204944)). 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): - P2: early `schedule_finalization` could stamp `stop=finalized` and consume the once-only standalone write while the generation remained open. Checkpoints now emit `live_checkpoint` logs without mutating or claiming the persisted summary. `boundary_snapshot` requires `closed`, 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. - P3: first enqueue, profile-load, score-generation, comparison, and publication observations use `live_progress`; actual refusals retain `live_refusal`. The first-reason-per-generation bound remains, and budget refusal logging still reuses #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.sh` selection expands to 47 files, including the original suites, all previous CI failures, and every controller/refresh unit neighborhood. At committed head `b7a8771859cf4edeb5e675e8a5fcbbf5fa8aed31`, **2,442 tests passed across 47 files**, exit 0, and full backend typecheck passed with zero errors. Exact-head **`make preflight` passed 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](https://firebase.google.com/docs/firestore/query-data/index-overview)). This is configuration only: applying destructive exemptions requires the separate approved `field-exemptions` operation; 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/main` `62033e86cb1dd870fd3eb5373b79583f91409c06` without rebasing or rewriting history. The only conflict is `backend/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-head **`make preflight` passed all 34 checks** (115.40 seconds), exit 0. Normal push hooks remain enabled; terminal CI will be verified after publication.
# 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. -->
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e53ce05ddc
ℹ️ 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".
| reason = matcher._rejectors.recovery_denial(voice) | ||
| if reason is not None: | ||
| RECOVERY_DENIALS.labels(reason=reason).inc() | ||
| return True |
There was a problem hiding this comment.
Check the hard cap before recording eligibility denials
When a voice has already reached MAX_RECOVERED_VOICE_ATTEMPTS and a later profile recheck makes its retained decision clearly far, this branch increments RECOVERY_DENIALS for every subsequent match even though the hard attempt ceiling—not eligibility—is sufficient to reject it. That contradicts the documented metric contract that attempt-ceiling refusals are excluded and can inflate experiment results for long-running exhausted voices; return the hard-cap result before classifying an eligibility denial.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 377bf2aa06
ℹ️ 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 voice not in self.comparisons and voice not in self.recovery_decided and decision is None: | ||
| return None |
There was a problem hiding this comment.
Treat manual rejections as completed decisions
When a voice is manually rejected before it has an automatic comparison, _allow_authority_publication() records it only in RejectorHistory.manual, while each match returns before creating a _voice_decisions or comparisons entry. After the twelfth reservation, this condition therefore treats the explicitly rejected voice as undecided and can grant both recovery tranches, spending up to six additional embedding requests and shared socket tokens even though every result will be rejected again by the same manual authority. Include the manual-decision state in this eligibility check so such voices cannot recover solely because their automatic row is absent.
Useful? React with 👍 / 👎.
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. -->
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:
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.