Skip to content

fix: retry safe Soniox recovery HTTP failures before held settlement - #24392

Merged
Git-on-my-level merged 2 commits into
mainfrom
lane/sonioxerr
Nov 4, 2026
Merged

Git-on-my-level merged 2 commits into
mainfrom
lane/sonioxerr

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Nov 2, 2026 •

Copy link
Copy Markdown
Member

Soniox recovery settled a transient HTTP failure after one request. After an empty Modulate response, that left retained audio held and hid Soniox's HTTP class behind the original empty_asr failure.

Retry safe upload/read failures and explicit 429 refusals up to three HTTP attempts with 1s/2s backoff inside the existing 120s deadline. Polls keep their transcription id; an accepted or uncertain paid POST is never resubmitted. Keep credit/auth refusals, malformed replies and exhausted attempts held, and log only the closed error kind, bounded HTTP status and paid-submission state. The synchronous adapter now preserves those fields too.

This is on by default, with no new flag or workflow. It needs the backend-sync/recovery-handler release; the lead owns merge and deployment. It does not reopen historical held units or add an operator route. Rollback: deploy the previous backend source.

Validation: failing-first targeted runner produced 23 failures and 3 passes before implementation. The targeted backend shard passed all 252 tests across six files through backend/test.sh, BACKEND_PYTEST_WORKERS=1, nice -n 19 and bin/omi-heavy; all 36 selected make preflight checks passed. The final explicit-exhaustion correction passed the full canonical backend typecheck and all 35 adapter regressions again. Synthetic HTTP tests cover recovery, exhaustion, deadline/cancellation, permanent credit refusal and uncertain paid submission; a recovery-level regression checks retained speech and no duplicate submission.

Product invariants: INV-DATA-1. The production data plane, credentials and privacy bindings stay in place; the same fenced recovery intent owns retries and held audio.

Failure-Class: FC-recoverable-provider-failure-terminal

View guided diff Turn on auto-fix

Keep retries inside the original deadline and paid intent. Retain the
closed error kind/status for diagnosis and hold credit refusals or
uncertain paid submissions without issuing a duplicate transcription.

Failure-Class: FC-recoverable-provider-failure-terminal
Make the bounded request loops raise after exhaustion so their return
types cannot include None at the transcription/receipt boundary.

Failure-Class: FC-recoverable-provider-failure-terminal
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-11-02T13:45:13.368063Z
We couldn’t complete this review. Comment @codex review to try again.
3134504 PR opened
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

8 issues found across 7 files

Confidence score: 3/5

  • In soniox_batch.py, a semaphore timeout can mark a transcription as submitted even though client.request never ran. Set submitted only for failures from the HTTP call itself.
  • Retries of ambiguous uploads in soniox_batch.py can leave untracked Soniox files because cleanup only knows the final successful attempt. Use upload idempotency or avoid retrying ambiguous uploads.
  • The recovery release note names backend-sync instead of backend-integration, and the linked runbook still says HTTP POSTs are never retried. Correct both so operators deploy the right service and understand the 429 exception.
  • The tests leave production async recovery and retry behavior under-verified: they miss async 503/402 recovery cases, failover=True, and the three-attempt bound for GETs. Add coverage for those paths.
Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="backend/tests/unit/test_soniox_batch_async.py">

<violation number="1" location="backend/tests/unit/test_soniox_batch_async.py:156">
P2: This test never verifies retries for the `poll` or `transcript` GETs, so a regression that removes safe-read retries still passes. Assert the relevant GET path occurs three times for those stages.</violation>
</file>

<file name="backend/docs/listen_pusher_pipeline.mdx">

<violation number="1" location="backend/docs/listen_pusher_pipeline.mdx:7320">
P2: This new contract contradicts the linked recovery runbook, which still says no HTTP POST is retried. Update the runbook to document the explicit 429 retry exception so operators do not treat the intended behavior as an unsafe duplicate submission.</violation>
</file>

<file name="backend/docs/listen_pusher_pipeline/changes/2026-11-02-soniox-recovery-http-retry.md">

<violation number="1" location="backend/docs/listen_pusher_pipeline/changes/2026-11-02-soniox-recovery-http-retry.md:29">
P2: This release instruction names the wrong service for the recovery handler. The recovery Cloud Tasks audience and provider-STT handler are `backend-integration`, so following this note could deploy `backend-sync` while leaving the handler on the pre-retry code; name `backend-integration` explicitly in the rollout and rollback guidance.</violation>
</file>

<file name="backend/tests/unit/test_batch_pipeline_second_provider.py">

<violation number="1" location="backend/tests/unit/test_batch_pipeline_second_provider.py:127">
P2: This integration test covers only the synchronous recovery path, so a regression in async retry or error-to-held mapping could ship while the production serving path remains untested. Run the same 503/402 scenarios through `recover_async` as well.</violation>
</file>

<file name="backend/tests/unit/test_soniox_recovery_retry.py">

<violation number="1" location="backend/tests/unit/test_soniox_recovery_retry.py:76">
P2: These async retry tests do not exercise the production recovery surface: `provider_stt` passes `failover=True`, but every async call here uses the default `False`. A regression in failover admission can therefore leave backend-sync recovery broken while this suite stays green; pass `failover=True` in each async invocation (or parameterize the admission surface).</violation>
</file>

<file name="backend/tests/unit/test_soniox_batch.py">

<violation number="1" location="backend/tests/unit/test_soniox_batch.py:131">
P2: This regression test does not verify the three-attempt bound for `poll` and `transcript` reads. Assert that the failing GET path is called exactly three times; otherwise an over-retry regression can pass this test.</violation>
</file>

<file name="backend/utils/stt/soniox_batch.py">

<violation number="1" location="backend/utils/stt/soniox_batch.py:238">
P2: Retrying an upload after an ambiguous timeout or 5xx can create an untracked Soniox file; cleanup deletes only the ID from the final successful attempt. Use an upload idempotency mechanism or avoid retrying ambiguous upload outcomes.</violation>

<violation number="2" location="backend/utils/stt/soniox_batch.py:246">
P2: The async path marks a transcription as submitted when its semaphore wait times out, even though `client.request` was never called. Set `submitted` only for exceptions from the actual HTTP call, not timeout or admission failures before it.</violation>
</file>

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

assert sum(method == 'POST' and path == '/v1/transcriptions' for method, path in calls) == (
0 if stage == 'upload' else 1
)
assert sum(method == 'POST' and path == '/v1/files' for method, path in calls) == (3 if stage == 'upload' else 1)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: This test never verifies retries for the poll or transcript GETs, so a regression that removes safe-read retries still passes. Assert the relevant GET path occurs three times for those stages.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/tests/unit/test_soniox_batch_async.py, line 156:

<comment>This test never verifies retries for the `poll` or `transcript` GETs, so a regression that removes safe-read retries still passes. Assert the relevant GET path occurs three times for those stages.</comment>

<file context>
@@ -150,5 +150,8 @@ async def sleep(_):
+    assert sum(method == 'POST' and path == '/v1/transcriptions' for method, path in calls) == (
+        0 if stage == 'upload' else 1
+    )
+    assert sum(method == 'POST' and path == '/v1/files' for method, path in calls) == (3 if stage == 'upload' else 1)
     assert 'PRIVATE_SENTINEL' not in caplog.text
</file context>
Suggested change
assert sum(method == 'POST' and path == '/v1/files' for method, path in calls) == (3 if stage == 'upload' else 1)
assert sum(method == 'POST' and path == '/v1/files' for method, path in calls) == (3 if stage == 'upload' else 1)
assert sum(
method == 'GET'
and path == (
f'/v1/transcriptions/{TRANSCRIPTION}'
if stage == 'poll'
else f'/v1/transcriptions/{TRANSCRIPTION}/transcript'
)
for method, path in calls
) == (3 if stage in {'poll', 'transcript'} else 0)

ledger and single paid-intent fences apply. No paid POST is retried. The result
ledger and single paid-intent fences apply. Recovery HTTP requests have at most
three attempts with 1s/2s backoff within the existing 120s deadline. A paid
transcription POST retries only an explicit 429 refusal; a transport error or

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: This new contract contradicts the linked recovery runbook, which still says no HTTP POST is retried. Update the runbook to document the explicit 429 retry exception so operators do not treat the intended behavior as an unsafe duplicate submission.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/docs/listen_pusher_pipeline.mdx, line 7320:

<comment>This new contract contradicts the linked recovery runbook, which still says no HTTP POST is retried. Update the runbook to document the explicit 429 retry exception so operators do not treat the intended behavior as an unsafe duplicate submission.</comment>

<file context>
@@ -7315,7 +7315,12 @@ proposal supported by synthetic tests, not labeled evidence about held audio.
-ledger and single paid-intent fences apply. No paid POST is retried. The result
+ledger and single paid-intent fences apply. Recovery HTTP requests have at most
+three attempts with 1s/2s backoff within the existing 120s deadline. A paid
+transcription POST retries only an explicit 429 refusal; a transport error or
+5xx on that POST is uncertain and remains held. Uploads and reads may retry
+transient 429/5xx/transport errors; polls keep the same transcription id.
</file context>

The synchronous adapter now preserves the same typed error fields as async.

This ships on with no new flag, environment variable, workflow or data change.
Rollback is to redeploy the previous backend source. Backend-sync (including

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: This release instruction names the wrong service for the recovery handler. The recovery Cloud Tasks audience and provider-STT handler are backend-integration, so following this note could deploy backend-sync while leaving the handler on the pre-retry code; name backend-integration explicitly in the rollout and rollback guidance.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/docs/listen_pusher_pipeline/changes/2026-11-02-soniox-recovery-http-retry.md, line 29:

<comment>This release instruction names the wrong service for the recovery handler. The recovery Cloud Tasks audience and provider-STT handler are `backend-integration`, so following this note could deploy `backend-sync` while leaving the handler on the pre-retry code; name `backend-integration` explicitly in the rollout and rollback guidance.</comment>

<file context>
@@ -0,0 +1,37 @@
+The synchronous adapter now preserves the same typed error fields as async.
+
+This ships on with no new flag, environment variable, workflow or data change.
+Rollback is to redeploy the previous backend source. Backend-sync (including
+the recovery Cloud Tasks handler) needs the release; this is not a worker fix.
+The live WebSocket adapter is unchanged. Source contract:
</file context>
Suggested change
Rollback is to redeploy the previous backend source. Backend-sync (including
Backend-integration (including the recovery Cloud Tasks handler) needs the release; this is not a worker fix.

)
)
client, binding, artifacts, _, _, recovery = second_setup(setup, monkeypatch, legacy_dependencies, soniox=second)
assert recovery.recover('bad', binding.owner_id) == expected

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: This integration test covers only the synchronous recovery path, so a regression in async retry or error-to-held mapping could ship while the production serving path remains untested. Run the same 503/402 scenarios through recover_async as well.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/tests/unit/test_batch_pipeline_second_provider.py, line 127:

<comment>This integration test covers only the synchronous recovery path, so a regression in async retry or error-to-held mapping could ship while the production serving path remains untested. Run the same 503/402 scenarios through `recover_async` as well.</comment>

<file context>
@@ -108,6 +108,36 @@ def test_second_provider_error_stays_failed_held(setup, monkeypatch, legacy_depe
+        )
+    )
+    client, binding, artifacts, _, _, recovery = second_setup(setup, monkeypatch, legacy_dependencies, soniox=second)
+    assert recovery.recover('bad', binding.owner_id) == expected
+    job = row(client)
+    assert job['recovery']['recognizers']['soniox']['outcome'] == ('words' if status == 503 else 'error')
</file context>


if asynchronous:
async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
words, _ = await module.transcribe_async(b'synthetic', 5, client=client, semaphore=semaphore, sleep=sleep)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: These async retry tests do not exercise the production recovery surface: provider_stt passes failover=True, but every async call here uses the default False. A regression in failover admission can therefore leave backend-sync recovery broken while this suite stays green; pass failover=True in each async invocation (or parameterize the admission surface).

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/tests/unit/test_soniox_recovery_retry.py, line 76:

<comment>These async retry tests do not exercise the production recovery surface: `provider_stt` passes `failover=True`, but every async call here uses the default `False`. A regression in failover admission can therefore leave backend-sync recovery broken while this suite stays green; pass `failover=True` in each async invocation (or parameterize the admission surface).</comment>

<file context>
@@ -0,0 +1,177 @@
+
+    if asynchronous:
+        async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+            words, _ = await module.transcribe_async(b'synthetic', 5, client=client, semaphore=semaphore, sleep=sleep)
+    else:
+        words, _ = module.transcribe(b'synthetic', 5, client_factory=sync_client(handler), sleep=sleeps.append)
</file context>

module.transcribe(b'synthetic', 5, client_factory=client(handler), sleep=lambda _: None)
assert sum(m == 'POST' and p == '/v1/transcriptions' for m, p in calls) <= 1
assert sum(m == 'POST' and p == '/v1/files' for m, p in calls) == 1
assert sum(m == 'POST' and p == '/v1/transcriptions' for m, p in calls) == (

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: This regression test does not verify the three-attempt bound for poll and transcript reads. Assert that the failing GET path is called exactly three times; otherwise an over-retry regression can pass this test.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/tests/unit/test_soniox_batch.py, line 131:

<comment>This regression test does not verify the three-attempt bound for `poll` and `transcript` reads. Assert that the failing GET path is called exactly three times; otherwise an over-retry regression can pass this test.</comment>

<file context>
@@ -128,8 +128,10 @@ def handler(request):
         module.transcribe(b'synthetic', 5, client_factory=client(handler), sleep=lambda _: None)
-    assert sum(m == 'POST' and p == '/v1/transcriptions' for m, p in calls) <= 1
-    assert sum(m == 'POST' and p == '/v1/files' for m, p in calls) == 1
+    assert sum(m == 'POST' and p == '/v1/transcriptions' for m, p in calls) == (
+        0 if failure == 'upload' else 3 if failure == 'create' else 1
+    )
</file context>

raise SonioxBatchError()
return response.json()
nonlocal submitted
for attempt in range(1, MAX_HTTP_ATTEMPTS + 1):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Retrying an upload after an ambiguous timeout or 5xx can create an untracked Soniox file; cleanup deletes only the ID from the final successful attempt. Use an upload idempotency mechanism or avoid retrying ambiguous upload outcomes.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/utils/stt/soniox_batch.py, line 238:

<comment>Retrying an upload after an ambiguous timeout or 5xx can create an untracked Soniox file; cleanup deletes only the ID from the final successful attempt. Use an upload idempotency mechanism or avoid retrying ambiguous upload outcomes.</comment>

<file context>
@@ -181,19 +228,37 @@ def transcribe(
-                raise SonioxBatchError()
-            return response.json()
+            nonlocal submitted
+            for attempt in range(1, MAX_HTTP_ATTEMPTS + 1):
+                remaining = deadline - clock()
+                if remaining <= 0:
</file context>

try:
response = client.request(method, BASE_URL + path, timeout=min(20, remaining), **kwargs)
except Exception:
if (method, path) == ('POST', '/transcriptions'):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: The async path marks a transcription as submitted when its semaphore wait times out, even though client.request was never called. Set submitted only for exceptions from the actual HTTP call, not timeout or admission failures before it.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/utils/stt/soniox_batch.py, line 246:

<comment>The async path marks a transcription as submitted when its semaphore wait times out, even though `client.request` was never called. Set `submitted` only for exceptions from the actual HTTP call, not timeout or admission failures before it.</comment>

<file context>
@@ -181,19 +228,37 @@ def transcribe(
+                    try:
+                        response = client.request(method, BASE_URL + path, timeout=min(20, remaining), **kwargs)
+                    except Exception:
+                        if (method, path) == ('POST', '/transcriptions'):
+                            submitted = True
+                        raise
</file context>

@Git-on-my-level
Git-on-my-level merged commit af704d6 into main Nov 4, 2026
65 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/sonioxerr branch November 4, 2026 07:32
Git-on-my-level added a commit that referenced this pull request Nov 4, 2026
Main's head (a5ccd17) fails two of its own checks, which every branch
based on it inherits: the pl397 emulator-proof fixtures lack the
time.monotonic clock the consumer's lease hold now reads, and the Soniox
503-at-submission test still asserts the pre-#24392 contract (5xx at the
paid step now preserves paid uncertainty: submitted=True).
Git-on-my-level added a commit that referenced this pull request Nov 4, 2026
Main's head (a5ccd17) fails two of its own checks, which every branch
based on it inherits:

- The pl397 emulator-proof fixtures clock enrichment_consumer.time with a
  SimpleNamespace carrying only time(); the consumer's lease hold now also
  reads time.monotonic(). Add monotonic to the injected clock.
- test_soniox_refusal_at_submission_is_typed_and_not_submitted still
  expects submitted=False for a 503 at POST /transcriptions, but #24392
  deliberately preserves paid uncertainty on 5xx (submitted=True, see the
  request() comment in utils/stt/soniox_batch.py). Keep 402/429 in the
  unbilled test and pin the 5xx contract in its own test.
Git-on-my-level added a commit that referenced this pull request Nov 4, 2026
Main's head (a5ccd17) fails two of its own checks, which every branch
based on it inherits: the pl397 emulator-proof fixtures lack the
time.monotonic clock the consumer's lease hold now reads, and the Soniox
503-at-submission test still asserts the pre-#24392 contract (5xx at the
paid step now preserves paid uncertainty: submitted=True).
Git-on-my-level added a commit that referenced this pull request Nov 4, 2026
… 5xx

#24392 documented that a 5xx from the paid transcription POST is
uncertain and stays held (submitted=True, no duplicate transcription),
but the stale assertion in test_batch_vendor_clients.py still expected
submitted=False, which is why main's own Backend Unit Tests shard 3/8
has been red since it landed. Explicit refusals (402 credit, 429 rate)
keep submitted=False; only the uncertain 5xx case moves.
Git-on-my-level added a commit that referenced this pull request Nov 4, 2026
* feat(batch): add auto-language route receipts

Persist content-free script and route counts for the marked mobile native
auto-language cohort. Preserve legacy result and work-item serialization for
non-cohort jobs during rollout.

* test: align inherited main CI with its own current contracts

Main's head (a5ccd17) fails two of its own checks, which every branch
based on it inherits: the pl397 emulator-proof fixtures lack the
time.monotonic clock the consumer's lease hold now reads, and the Soniox
503-at-submission test still asserts the pre-#24392 contract (5xx at the
paid step now preserves paid uncertainty: submitted=True).
Git-on-my-level added a commit that referenced this pull request Nov 4, 2026
…ng wait (#24509)

* fix(speakers): rename across recording with batch selection and editable regeneration

Failure-Class: new

* fix(speakers): validate scoped carry data and selected sibling scopes

Failure-Class: new

* test(speakers): verify recorded ordering, selection flow and fixture UI evidence

* test(speakers): finish picker animation before asserting batch persistence

* test(speakers): bind widget transport to an explicit hermetic environment

* fix(speakers): fence stale voice proofs and preserve recording identities

Failure-Class: new

* test(speakers): exercise episode HTTP admission with real receipt fan-out

* fix(speakers): preserve overlapping live saves and register fallback query coverage

Failure-Class: new

* chore(speakers): keep extracted ownership and render lint clean

* fix(speakers): type recording options and remove unused carry imports

* fix(speakers): preserve stable legacy transcript identities across recording edits

* chore(speakers): refresh API contracts and document recording receipt ordering

* fix(speakers): fence and bound recording rename outcomes

* fix(speakers): decode member outcomes without empty defaults

* fix(speakers): record disabled-server fallback consistently

* fix(speakers): narrow retry receipt entries for type safety

* fix(speakers): classify recording routes as first-party API

* fix(speakers): preserve learning events after assignment commits

* fix(speakers): align recording wire and observer contracts

* fix(speakers): generate and consume typed recording responses

* fix(speakers): discover legacy recording members and report coverage

* fix(speakers): report conservative recording rename coverage

* fix(speakers): require creation provenance for complete recording coverage

* fix(speakers): wrap transcript selection labels without truncation

* Restore backend unit runner contract from main

* test: align inherited main CI with its own current contracts

Main's head (a5ccd17) fails two of its own checks, which every branch
based on it inherits:

- The pl397 emulator-proof fixtures clock enrichment_consumer.time with a
  SimpleNamespace carrying only time(); the consumer's lease hold now also
  reads time.monotonic(). Add monotonic to the injected clock.
- test_soniox_refusal_at_submission_is_typed_and_not_submitted still
  expects submitted=False for a 503 at POST /transcriptions, but #24392
  deliberately preserves paid uncertainty on 5xx (submitted=True, see the
  request() comment in utils/stt/soniox_batch.py). Keep 402/429 in the
  unbilled test and pin the 5xx contract in its own test.
Git-on-my-level added a commit that referenced this pull request Nov 4, 2026
…lout and a kill switch (#24477)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Review follow-up round 2:

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

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

Review follow-up round 3:

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

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

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

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

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

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

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

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

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

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

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

Address review round 5 (Codex P2s):

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

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

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

Address review round 6 (Codex P2s):

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

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

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

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

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

Six regression tests added; suite: 66 passed.

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

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

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

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

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

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

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

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

Codex review round 8 (r4343951882, r4343951890):

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

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

Codex review round 2 (PR #22389):

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

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

Codex review round 3 (PR #22389):

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

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

Codex review round 4 (PR #22389):

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

* fix(deploy): reject duplicate rendered environment names

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

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

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

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

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

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

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

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

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

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

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

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

Address Codex review of c5e2116:

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

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

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

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

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

Failure-Class: none

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

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

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

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

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

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

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

* feat(stt): verify immutable local inference archives

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

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

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

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

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

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

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

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

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

Failure-Class: none

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Failure-Class: none

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

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

Failure-Class: none

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

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

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

Failure-Class: none

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* test(firmware): initialize OTA request test environment

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

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

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

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

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

* chore: regenerate TypeScript API types for firmware device_id

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: David Zheng <[email protected]>
Co-authored-by: David Zhang <[email protected]>
Dimank92 pushed a commit to Dimank92/omi that referenced this pull request Nov 4, 2026
* feat(batch): add auto-language route receipts

Persist content-free script and route counts for the marked mobile native
auto-language cohort. Preserve legacy result and work-item serialization for
non-cohort jobs during rollout.

* test: align inherited main CI with its own current contracts

Main's head (a5ccd17) fails two of its own checks, which every branch
based on it inherits: the pl397 emulator-proof fixtures lack the
time.monotonic clock the consumer's lease hold now reads, and the Soniox
503-at-submission test still asserts the pre-BasedHardware#24392 contract (5xx at the
paid step now preserves paid uncertainty: submitted=True).
Git-on-my-level added a commit that referenced this pull request Nov 6, 2026
* fix: route critical pipeline failures through verified page alerts

Promote batch timeliness, gate critical backlog and vendor signals, and
export bounded guard failure logs for a page-tier metric rule.

Failure-Class: FC-grafana-alert-import-omits-gated-rules

* fix: route critical pipeline failures through verified page alerts

Promote batch timeliness, gate critical backlog and vendor signals, and
export bounded guard failure logs for a page-tier metric rule.

Failure-Class: FC-grafana-alert-import-omits-gated-rules

* fix: route critical pipeline failures through verified page alerts

Promote batch timeliness, gate critical backlog and vendor signals, and
export bounded guard failure logs for a page-tier metric rule.

Failure-Class: FC-grafana-alert-import-omits-gated-rules

* fix: keep production native alerts out of development imports

Failure-Class: FC-grafana-alert-import-omits-gated-rules

Keep enrichment and guard Cloud Monitoring queries on the production import
path, preserve detached development definitions, and update batch apply docs.

* fix: defer finalization alert coverage to finaldwell

Remove the duplicate dead-letter stock page and reference #24533.

* test: align inherited main CI with its own current contracts

Main's head (a5ccd17) fails two of its own checks, which every branch
based on it inherits: the pl397 emulator-proof fixtures lack the
time.monotonic clock the consumer's lease hold now reads, and the Soniox
503-at-submission test still asserts the pre-#24392 contract (5xx at the
paid step now preserves paid uncertainty: submitted=True).

* fix(monitoring): regenerate the GMP inventory over the merged rule set and allowlist the grown telemetry contract leg

The merge unioned alert-rules.json across both lanes; the committed
migration inventory is now regenerated by monitoring_gmp_shadow.py
--inventory instead of a hand-merged count, and the dead-letter
producer-family contract leg that walks the full rule set is allowlisted
at its measured CI CPU time (1.03s vs the 1.00s guard limit; all 44
contract assertions pass).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant