Skip to content

Fixes boot - #6

Merged
Bentlybro merged 2 commits into
BasedHardware:mainfrom
Bentlybro:fix-boot
Mar 28, 2024
Merged

Bentlybro merged 2 commits into
BasedHardware:mainfrom
Bentlybro:fix-boot

Conversation

@Bentlybro

@Bentlybro Bentlybro commented Mar 28, 2024 •

Copy link
Copy Markdown
Contributor

this bit of code was preventing boot as it was waiting for serial, by removing it the device is now able to properly boot!

while (!Serial)
{
  delay(10);
}

things to note: removing this loop means we won't see the startup logs unless we directly restart it while its connected to serial

Update

added a 500ms wait to check if there is serial, if so connect to that if not start as normal

  unsigned long startMillis = millis();
  while (!Serial && millis() - startMillis < 500)
  {
    delay(10); // Short delay to prevent hanging in a tight loop
  }

@Bentlybro
Bentlybro marked this pull request as draft March 28, 2024 23:26
@Bentlybro
Bentlybro marked this pull request as ready for review March 28, 2024 23:44
@akshaynarisetti

Copy link
Copy Markdown
Contributor

Looks Good @Bentlybro, let’s merge this

@Bentlybro
Bentlybro merged commit f92dd90 into BasedHardware:main Mar 28, 2024
@Wladefant

Copy link
Copy Markdown
Contributor

nice

beastoin added a commit that referenced this pull request Aug 30, 2025
mdmohsin7 added a commit that referenced this pull request Oct 18, 2025
closes #3241

before:


https://github.com/user-attachments/assets/d00d815c-8419-4c1b-96fb-ec20365fba44

logs:

```
flutter: ----------------FIREBASE CRASHLYTICS----------------
flutter: Bad state: No element
flutter: 
#0      ListBase.firstWhere (dart:collection/list.dart:132:5)
#1      SharedPreferencesUtil.disableApp (package:omi/backend/preferences.dart:255:22)
#2      _AppDetailPageState._toggleApp (package:omi/pages/apps/app_detail/app_detail.dart:1129:13)
#3      _AppDetailPageState.build.<anonymous closure> (package:omi/pages/apps/app_detail/app_detail.dart:576:48)
#4      _AnimatedLoadingButtonState._handleOnPressed (package:omi/widgets/animated_loading_button.dart:38:27)
#5      _InkResponseState.handleTap (package:flutter/src/material/ink_well.dart:1204:21)
#6      GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:345:24)
#7      TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:758:11)
#8      BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:383:5)
#9      BaseTapGestureRecognizer.acceptGesture (package:flutter/src/gestures/tap.dart:353:7)
#10     GestureArenaManager.sweep (package:flutter/src/gestures/arena.dart:173:27)
#11
```

after:


https://github.com/user-attachments/assets/26ea5c91-e73a-44f4-ba76-4b804876c5df

<img width="1032" height="257" alt="Screenshot 2025-10-18 at 11 15
52 PM"
src="https://github.com/user-attachments/assets/44e4e46b-b654-4599-84ee-8ee0920b1cd3"
/>
beastoin added a commit that referenced this pull request Mar 16, 2026
Covers feature vector gap #6 (conversation sharing, priority 6).
Adds share button press step with native share sheet handling.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Glucksberg pushed a commit to Glucksberg/omi-local that referenced this pull request Apr 28, 2026
Glucksberg pushed a commit to Glucksberg/omi-local that referenced this pull request Apr 28, 2026
closes BasedHardware#3241

before:


https://github.com/user-attachments/assets/d00d815c-8419-4c1b-96fb-ec20365fba44

logs:

```
flutter: ----------------FIREBASE CRASHLYTICS----------------
flutter: Bad state: No element
flutter: 
#0      ListBase.firstWhere (dart:collection/list.dart:132:5)
#1      SharedPreferencesUtil.disableApp (package:omi/backend/preferences.dart:255:22)
BasedHardware#2      _AppDetailPageState._toggleApp (package:omi/pages/apps/app_detail/app_detail.dart:1129:13)
BasedHardware#3      _AppDetailPageState.build.<anonymous closure> (package:omi/pages/apps/app_detail/app_detail.dart:576:48)
BasedHardware#4      _AnimatedLoadingButtonState._handleOnPressed (package:omi/widgets/animated_loading_button.dart:38:27)
BasedHardware#5      _InkResponseState.handleTap (package:flutter/src/material/ink_well.dart:1204:21)
BasedHardware#6      GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:345:24)
BasedHardware#7      TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:758:11)
BasedHardware#8      BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:383:5)
BasedHardware#9      BaseTapGestureRecognizer.acceptGesture (package:flutter/src/gestures/tap.dart:353:7)
BasedHardware#10     GestureArenaManager.sweep (package:flutter/src/gestures/arena.dart:173:27)
BasedHardware#11
```

after:


https://github.com/user-attachments/assets/26ea5c91-e73a-44f4-ba76-4b804876c5df

<img width="1032" height="257" alt="Screenshot 2025-10-18 at 11 15
52 PM"
src="https://github.com/user-attachments/assets/44e4e46b-b654-4599-84ee-8ee0920b1cd3"
/>
Glucksberg pushed a commit to Glucksberg/omi-local that referenced this pull request Apr 28, 2026
Covers feature vector gap BasedHardware#6 (conversation sharing, priority 6).
Adds share button press step with native share sheet handling.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
choguun added a commit to choguun/omi that referenced this pull request Jun 25, 2026
CI lint fix (the only thing blocking merge):
- Ran black --line-length 120 --skip-string-normalization on 7 files that
  the Lint & Format Check job flagged. All 13 .py files now pass --check.

P1 #1: AutoRouter.swift:105 guard treated "model: null" as failure and
left stale cached pick active. If the endpoint reports 'no candidate for
this task today', the client would keep routing to yesterday's model.
Fix: explicitly handle null by clearing the cached pick (removeObject
for both keys). Also fixed invalidate(task:) to clear BOTH the pick and
the date (was: only the date). 2 new Swift tests cover both.

P1 BasedHardware#2: benchmark.py bench_endpoint_cached ignored get_or_refresh's return
value and relied on  side effects. On a cache hit, the loader
doesn't run, so tasks/models stay None and the next call crashes.
Fix: use the return value of get_or_refresh in an async helper.

P2 BasedHardware#3: invalidate(task:) now also clears the cached pick (was: only date).
Done as part of P1 #1.

P2 BasedHardware#4: Demo's 'Original weights' were hardcoded in main(); now read from
the task registry (weights_for(task_name)) so demo output tracks
benchmarks.example.json changes instead of going stale.

P2 BasedHardware#6: from_json didn't validate top-level shape (not a dict), or that
'tasks' is a list / 'models' is a dict. Would crash with AttributeError on
bad input. Now raises clean TaskValidationError/ModelValidationError.
Added 6 new tests (3 in task_registry, 3 in model_registry).

P2 BasedHardware#7: updated_at in the endpoint was datetime.now() — reported RESPONSE
time, not cache refresh time. Misleading for 'is this data fresh?' Added
last_loaded_at + last_loaded_wall_time() properties to DailyRefreshCache
(used by the endpoint).

P2 BasedHardware#8: _load_registries() does blocking JSON file I/O inside an async def,
which the project conventions forbid (per CLAUDE.md: 'no in-function
imports, never call sync file I/O inside async def'). Fix: wrap with
run_blocking(sync_executor, _load_registries) via a lazy _get_loader()
helper. The cache loader is now an async function that schedules the
sync I/O on the threadpool.

P2 BasedHardware#9: New test modules were not in backend/test.sh, so CI was skipping
them. Added explicit pytest invocations for all 6 auto-router test
files, right before the fair-use integration tests section.

P2 BasedHardware#10: README + docs/auto-router-demo.md used PYENV_VERSION=3.12.8 but
backend's .python-version declares 3.11. Updated to 3.11.11 (verified all
142 tests pass under 3.11.11 with pytest-asyncio installed).

Tests added: +8 (137 → 142 backend; 13 → 15 desktop)
Total: 142 backend + 15 desktop = 157 tests, all passing.

Cubic findings NOT addressed (subjective or already correct):
- P2 'Plan redefines the diff budget': per-task commits are correct.
- P2 'Acceptance criteria tie-breaking wrong': tie-breaking is in the
  endpoint, not scoring — cubic is wrong.
- P2 'UAT-FN-07 inaccurate': that finding is now resolved by
  test_auto_router_demo.py (added in this cycle).
- P2 'UAT-FN-01 outdated': the fix is real; the current code does NOT
  leak task names (verified via TestClient in test_auto_router_endpoint).
- P2 'Benchmark uses template data': intentional for v1; documented.
- P3 nits: docstring, diff-hygiene wording, test-count arithmetic.
choguun added a commit to choguun/omi that referenced this pull request Jun 25, 2026
…dead code)

Addresses 5 cubic P3 findings on PR BasedHardware#8349.

## P3 #1 (cubic): v1-only module docstring (now updated to cover v1-v4)

Same fix as v1's commit 6ce9fce, applied here.

## P3 BasedHardware#2 (cubic): benchmark.py has function-scoped `import asyncio`

Per backend AGENTS.md, imports should be at the module top level. The
benchmark.py had two `import asyncio` statements inside functions.

Fix: moved both to module top level. Removed the now-redundant in-function
imports. The `asyncio.run` calls now reference the module-level import.

## P3 BasedHardware#3 (cubic): demo/run.py top-level docstring is stale

The docstring mentioned "Demos 1-3 don't call the HTTP endpoint" but
Demo 4 (added in v2) DOES use FastAPI's TestClient to hit the live
endpoint. The docstring has been updated.

## P3 BasedHardware#4 (cubic): docs/auto-router-demo.md wrong metrics endpoint path

The Demo 4 row in the summary table said "GET /metrics" but the
actual route is "GET /v1/auto-router/metrics". Fixed.

## P3 BasedHardware#5 (cubic): README.md test inventory outdated (missing metrics)

The test tree at the top of README.md didn't include
test_auto_router_metrics.py (added in v2). Fixed by adding it.

## P3 BasedHardware#6 (cubic): Unused defaultsSuite in AutoRouterTests.swift

The setUp/tearDown created a unique UserDefaults suite per test but
never injected it. The tearDown tried to clean up using
`dictionaryRepresentation().keys.first ?? ""` as the domain name,
but keys.first returns a stored KEY (not the suite name), so the
cleanup was a silent no-op.

Fix: removed the setUp/tearDown entirely. Each test that writes via
`AutoRouter.shared.store(...)` cleans up via
`AutoRouter.shared.invalidate(task: ...)` at the end. A NOTE comment
documents the contract.

## Test results

- Backend: 175 tests pass
- Desktop: 15 AutoRouterTests pass (no count change, just cleanup)
- Black 26.5.1 clean
- Desktop build clean

## Not addressed (process artifacts)

- v1 review-report.md diff-hygiene / test-count inconsistencies
- v2 auto-router.mdx backend test total inconsistency
- v2 plan.md T-205 file count inconsistency
- v2 spec.md auth test guidance

These are stale AIDLC process artifacts from v1 that have been superceded
by v2/v3/v4 docs. Fixing them would be churn without value.
choguun added a commit to choguun/omi that referenced this pull request Jul 1, 2026
Seven findings from cubic-dev-ai on the R3.1 PR. Two findings are
out of scope for R3.1 (they were introduced in the R0 commits
already on this branch; those fixes are in PR BasedHardware#8739's history):

  - P1 #1 (route_artifacts.yaml:758): anthropic provider not
    registered. R0 scope; addressed in PR BasedHardware#8739.
  - P3 BasedHardware#9 (test_llm_gateway_config.py:42): '15 lanes total' comment
    should be '16 lanes total'. R0 scope; already fixed in commit
    0d3442d (use placeholder flag instead of dev_only).

Five findings addressed in this commit:

P1 BasedHardware#2 (shadow_metrics.py:139): Metrics sink failures are now
contained — try/except around increment/gauge calls logs a WARNING
and does not propagate. Observability is best-effort.

P1 BasedHardware#3 (shadow_cutover.py:178): Metrics recording is wrapped in
try/except at the chat() call site; a sink failure cannot break
the control response. Tested by
test_metrics_failure_does_not_break_response.

P2 BasedHardware#4 (shadow_metrics.py:132): Unbounded memory growth capped by
max_records_per_lane (default 10,000) as a memory safety net
alongside the time-based window eviction. Tested by
test_max_records_per_lane_caps_deque.

P2 BasedHardware#5 (shadow_metrics.py:163): Alert delivery failure now clears
the alerted state. The inner async fire coroutine catches its own
exception and discards the lane from _alerted_lanes so the next
divergence re-fires. Tested by
test_alert_sink_failure_clears_alerted_state.

P2 BasedHardware#6 (shadow_cutover.py:163): Control path failure now cancels the
gateway task (no orphaned work). Tested by
test_control_failure_cancels_gateway_task.

P2 BasedHardware#7 (shadow_cutover.py:135): divergence_threshold is now read —
ShadowCutover.__init__ applies the per-cutover threshold to the
metrics instance (overriding the metrics' default). Tested by
test_divergence_threshold_overrides_default and
test_no_threshold_override_keeps_default.

P2 BasedHardware#8 (shadow_cutover.py:164): Both paths now have INDEPENDENT
timeouts (asyncio.wait_for on each), so a slow gateway doesn't delay
the already-ready control response. Tested by
test_slow_gateway_does_not_delay_control.

Tests: 38 pass (was 30 pre-fix; +8 new).
eulicesl added a commit that referenced this pull request Jul 12, 2026
…oss, hub timer leak, sync data loss (bug sweep #6) (#9514)
TuEmb pushed a commit to TuEmb/omi that referenced this pull request Jul 22, 2026
The capture bridge fanned every non-owned capture event out to EVERY
non-capture window (bar/glow/insight-toast/capture), but the only consumers
that flow through this path are the MAIN window's LiveMirrorHost (`live`) and
main's own event tap (`meeting-capture-status`, handled upstream of window
routing). So during continuous recording every live-transcript line was
serialized and dispatched to ~4 windows that immediately dropped it
(perf-profile-2026-07-19.md hotspot BasedHardware#6).

routeCaptureEvent now targets non-owned events at the main window only,
matching how owned events (PTT/audio) target their owner. registerCaptureBridge
takes a getMainWc accessor (read live, like getCaptureWc) so a re-created main
window is always the target. Owned-event routing is unchanged.

No behavior change: LiveMirrorHost is main-window-only, and the
meeting-capture-status main-process tap runs before window routing, so both
sole consumers still receive their events. `capture-window-restarted` is
unaffected — it originates in main via emitCaptureEventFromMain, a separate
path. Also drops the stale `vad-status` reference (no such event type exists).

Verified: unit tests (routeCaptureEvent main-only routing + owner drop);
live over CDP on an isolated dev instance — emitting 6 `live` ops from the
capture window delivered exactly 6 to the main window and 0 to glow/toast.
aryanorastar pushed a commit to aryanorastar/omi that referenced this pull request Jul 22, 2026
fix(windows): VAD engine initializes in dev (vite /public module-import limitation)
undivisible added a commit that referenced this pull request Aug 11, 2026
Definition of Done #6 — the new test command and manifest check need a guide.
Adds web/app/AGENTS.md (setup, quality-gate table, why lint is not in `check`,
where tests live) and its index row in the root AGENTS.md. Records that web/app
uses npm, not Bun: web/app/Dockerfile runs `npm ci` against package-lock.json,
so a competing lockfile would change what the production image installs.

Also states the parity boundary a reader needs before porting a desktop surface
— Rewind, Focus, Insights, floating bar, Bluetooth, and local file indexing
depend on macOS capture APIs with no browser equivalent, so the test is whether
the feature's data comes from a backend/routers/ endpoint or from local Swift
storage.

Registers the new file's size budget in check_agents_md_lean.py, as that check
requires.

Verification:
- `python3 .github/scripts/check_agents_md_lean.py` -> "ok: 8 AGENTS.md files
  within budget"

Failure-Class: none
undivisible added a commit that referenced this pull request Aug 11, 2026
Definition of Done #6 — the new test command and manifest check need a guide.
Adds web/app/AGENTS.md (setup, quality-gate table, why lint is not in `check`,
where tests live) and its index row in the root AGENTS.md. Records that web/app
uses npm, not Bun: web/app/Dockerfile runs `npm ci` against package-lock.json,
so a competing lockfile would change what the production image installs.

Also states the parity boundary a reader needs before porting a desktop surface
— Rewind, Focus, Insights, floating bar, Bluetooth, and local file indexing
depend on macOS capture APIs with no browser equivalent, so the test is whether
the feature's data comes from a backend/routers/ endpoint or from local Swift
storage.

Registers the new file's size budget in check_agents_md_lean.py, as that check
requires.

Verification:
- `python3 .github/scripts/check_agents_md_lean.py` -> "ok: 8 AGENTS.md files
  within budget"

Failure-Class: none
abunet added a commit to abunet/omi that referenced this pull request Aug 14, 2026
… backend

reconcile_mongo_indexes.py mirrors firestore.indexes.json into Mongo compound indexes (COLLECTION ->
_parent prefix, __name__ -> _id, ASC/DESC -> 1/-1) but was a CLI with no caller, so a self-hosted
Mongo deployment never created them: leaf collections hold every user's docs, so scoped queries and
counts collection-scanned in production (cubic PR 10887 BasedHardware#6).

Wire it into the existing startup reconcile pattern (main.startup_event): when STORAGE_BACKEND=mongo,
a best-effort background task provisions the indexes off the event loop. Idempotent (createIndex is a
no-op once they exist) and non-fatal (a slow/unready Mongo logs and does not block boot); a no-op on
the Firestore backend. Extracted create_planned_indexes(db) / reconcile_mongo_indexes() so main() and
the boot hook share one path. Firestore stays the reference backend (ADR-0003) — this only makes the
Mongo read path fast.

Verification:
- Live (mongo:7 replSet): reconcile_mongo_indexes() ensured all 41 planned indexes; 8/8 sampled
  present on the real db with matching keys; second run idempotent (same set, no error).
- Hermetic tests (7): create_planned_indexes issues one background create per plan item with the
  mapped keys/name and mirrors the full manifest; MONGO_URI-unset raises (the hook catches it).
- main.py compiles and imports the new symbol with no cycle; guards 0 (persistence/auth/object/vector).
- SELFHOST_NOTES documents the automatic provisioning + the manual re-run command.
abunet added a commit to abunet/omi that referenced this pull request Aug 15, 2026
…uery_group parity

Two coupled collection-group defects (cubic PR 10887 BasedHardware#338 + BasedHardware#5/BasedHardware#6):

- BasedHardware#338 (regression from the BasedHardware#8 scoped-query fix): the facade applied `_name_filter_value` (which
  reduces a _DocRef to its bare id, correct for a scoped query the store rebuilds as
  f"{collection}/{value}") to the collection-GROUP where() too. But query_group matches _id directly,
  and _id IS the full logical path (a group spans parents, no collection to prefix) — so the bare id
  matched nothing on Mongo. Add `_group_name_filter_value` (keeps the _DocRef's full .path) and use it
  in _GroupQuery.where.
- Fake query_group parity: FakeDocumentStore.query_group ignored __name__ filters (tested d["__name__"],
  a key no doc has -> zero rows) and silently combined an explicit field order_by with a document-name
  start_after keyset that both real adapters reject with NotImplementedError. A test could pass
  hermetically then break on Mongo/Firestore. The fake now handles __name__ against the full path and
  raises NotImplementedError for order_by+keyset, matching the adapters and the store contract.

Verification:
- Live on Mongo: `collection_group('state').where('__name__','==', DocRef)` returns ['s1'] (was [] when
  the DocRef was reduced to the bare id).
- Rewrote test_group_query_supports_order_by_and_start_after (it asserted the fake-only behavior the
  real adapters reject) to the real contract: order_by streams ordered, order_by+keyset raises. Added a
  group __name__ DocRef-bound regression test (==, and >=).
- test_firestore_facade 25, test_canonical_short_term_maintenance_cron 9, test_fair_use_store 14,
  test_firestore_query_contract 26 pass; guards 0.
Git-on-my-level added a commit that referenced this pull request Aug 17, 2026
…nes to Flash-Lite, fix the Pro demotion, cap server-paid output (#11764)

# Aggressive Gemini spend reduction: fit desktop demand under the Vertex
PT cap

## Why

The 5 GSU `gemini-2.5-flash` Vertex Provisioned Throughput reservation
(13,450 tok/s, $290.32/day, sunk to ~2027-05-28) is saturated 24/7:
measured desktop demand is **18,431 tok/s = 137% of the cap**, and the
27.4% that spills over is billed at PayGo Flash list price — the only
avoidable Gemini-Flash cash. There is no overnight trough to defer into
(0 of 408 measured hours below cap), downscaling screenshots saves
exactly zero tokens (measured, 12/12 frames), and halving every output
token in the fleet still would not fit. The only thing that fits is
moving whole low-value workloads onto `gemini-2.5-flash-lite`, which is
`shared`/on-demand on Vertex (measured `trafficType=ON_DEMAND`, 44/44
calls) and never competes with the reservation.

Evidence base (omi-knowledge-base,
`projects/vertex-pt-flash-spend/evidence/`):
`2026-08-17-workload-value-ranking.md` (rev 2),
`2026-08-17-overflow-destination-bakeoff.md` (210 measured calls),
`2026-08-17-cache-optimization-analysis.md`,
`2026-08-17-screenshot-resolution-experiment.md`, RCA. The decision
record for this PR: `2026-08-17-aggressive-savings-prescription.md`.

## What

One commit per surface:

1. **fix(backend): over-quota Pro demotes to Flash-Lite, not Flash.**
The 30/day Pro soft limit rewrote Insight onto `gemini-2.5-flash`,
silently dumping the most expensive tool loop (~11% of the reservation)
onto the saturated PT lane within the first hour of use. New
`_QUOTA_DEMOTION_MODEL` constant + regression test that the demotion
target can never be the PT pin.
2. **feat(backend): server-paid output cap 8192 → 2048** (default and
clamp). No shipped desktop client can send `maxOutputTokens`, so every
request inherited 8192 while output burns the reservation at 9×;
realistic per-lane budgets are 64–1024 visible tokens + thinking ≤1024
(thinking counts toward the limit on 2.5 models). Mean output is ~241
tokens — this bounds the paid tail, not typical behavior. **BYOK keeps
the 8192 default/clamp unchanged.**
3. **feat(desktop/windows): memory, insight (model+fallback), goals →
Flash-Lite**; tasks and focus stay on Flash. `modelPins.test.ts`
ratchets the reservation boundary.
4. **feat(desktop/macos): evict low-value lanes to Flash-Lite** via a
new `ModelQoS.Gemini.lightweight` pin: memory extraction, LiveNotes,
Goals (generate/progress/insight), task dedup, task prioritization,
HomeSuggestions; Insight's client-side transient fallback follows. Also
corrects the `ModelQoS` insight comment whose 2.34% CTR tuple reproduces
from no PostHog slice (measured 30d: insight 1.162% vs 0.68% fleet).
5. **feat(desktop/macos): memory extraction default cadence 600s →
1800s.** Worst-value lane on both fleet instruments (50.5% of
notification volume at 0.240% CTR; ~53 calls per stored memory).
User-chosen intervals are respected; 1800 is an existing ladder step.
6. **fix(desktop/macos): hash full captures at preview scale.**
`markCaptured` stored a full-resolution dHash into the history that
≤80px preview hashes are compared against; cross-scale aliasing reads as
"changed", defeating the preview-skip and triggering unnecessary full
captures and the Gemini calls behind them. New `previewScaleDHash` +
behavioral test.
7. Docs move with the code: `backend/docs/vertex-pt-flash.md` gains a
"keeping the reservation for work that must be Flash" section.

**Kept on the reservation, deliberately:** task extraction (60% of
burndown) — the bakeoff measured Flash-Lite extracting from a chat
sidebar at confidence 0.9 against an explicit prompt ban and silently
dropping one of two commitments; it has nowhere cheaper to go. Windows
focus (small, best lane CTR). macOS Insight's first 30/day stay on Pro.
**No task-lane cadence cuts**: once demand fits under the cap,
on-reservation tokens are marginally free — degrading the flagship lane
would save $0.

## Projected effect

Set #6 arithmetic from the value ranking: PT demand **18,431 → ~10,514
tok/s (78.2% of cap)** — PayGo Flash spillover → ~0 at current demand,
with headroom for the observed 1.15× intraday peak. Net Gemini cash
reduction roughly **$100–200/day** at current volumes (evicted lanes
cost 0.27× on Lite on-demand), plus the memory-lane cadence cut.
Absolute $ inherits the RCA's uncertainty; the tok/s arithmetic and cost
ratios are measured.

## Expected UX degradation (accepted, per David's mandate)

- Insight after the 30/day Pro quota runs on Flash-Lite (the largest
quality risk here — the bakeoff did not exercise Lite on the insight
tool loop specifically).
- Fewer memories: Lite fires ~42% as often as Flash on that lane
(measured as prompt-compliant restraint, but genuine coverage will drop)
and the timer is 3× slower.
- Dedup slightly worse (Lite missed 1 of 3 duplicate pairs).
- Possible extreme-tail truncation at 2048 output tokens; the mean
(~241) is unaffected.
- LiveNotes/prioritization/HomeSuggestions/goals: no detectable delta
measured; LiveNotes gets faster.

## Verification

- `backend/.venv/bin/pytest tests/unit/test_desktop_proxy.py` — **42
passed** (includes the new demotion regression test and the 5-case
server-paid/BYOK output-cap matrix driven through `_proxy` with a
capturing client).
- Windows: `pnpm test` (vitest, Node 22) — **5205 passed, 29 skipped**,
including the new `modelPins.test.ts`.
- macOS: `xcrun swift build -c debug --package-path Desktop` — clean
(Build complete, 258s); `xcrun swift test --filter
'ModelQoSTests|PreviewScaleDHashTests|SettingsAssistantControlsTests'` —
all suites passed (ModelQoSTests 18, PreviewScaleDHashTests 3,
SettingsAssistantControlsTests full suite; 0 failures).
- `make preflight` — **PASS, 34 checks** (including swift-format lint,
SwiftLint, e2e flow coverage, failure-class protocol, product
invariants, changelog contract).
- `scripts/failure-class validate` — OK (`declaration=new`, definition
added in this PR).
- Formatting: black (backend), swift-format wrapper (macOS), prettier
(windows) — all clean.
- Not exercised live: real Vertex traffic shift (requires deploy, out of
scope for this PR per the task boundary — do not deploy, do not merge).

## Follow-ups (named, not in this diff)

- **Task extraction → `gpt-5.6-luna`**: measurably better than Flash
(10/10 vs 9/10, −81% output) but needs the legacy tool-loop contract
ported onto the proactivity route; decision gate is a 50-labelled-frame
bakeoff (~$1 of calls).
- Thinking-budget cut (1024 → 256) once the billing export passes the
08-17 restore and the fleet reasoning share is measurable.
- 2304px defensive resolution cap for external-display captures (~145
tok/s, INFERRED).
- Prefix-cache restructuring (the byte-identical 4,211-token block;
stranded static chars at `TaskAssistant.swift:965-975`).
- Dead-code removals: `focus_sessions` (no writer, still synced/queried)
and `PTTTranscriptCleanupService.cleanup` (zero callers).
- Windows memory-cadence parity (its default lives in `appSettings` and
is a separate testable surface).
- `usageMetadata` + `x-omi-workload` proxy instrumentation to replace
the evidence base's inference layer with measurement.

Failure-Class: new

🤖 Generated with [Claude Code](https://claude.com/claude-code)


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/11764?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="Review in cubic"
src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->
kodjima33 added a commit that referenced this pull request Sep 1, 2026
…t history, semantic_search text fallback (#12565)

## Summary

Onboarding's ask demo ("Here's the fun part") now opens a bundled
three-door riddle page and the voice hub can actually answer all three
doors.

**Onboarding step**
- The page (`Resources/three-doors.html`) opens only from a new "Open
the doors" button; "Skip for now" appears only after it was opened.
"Open the doors again" reopens it.
- The page is rendered per user with the real push-to-talk chord and
this bundle's URL scheme (Launch Services drops fragments on `file:`
URLs, so the chord is baked into the HTML).
- Opening the doors starts Rewind capture with the home view's gates
(setting on, Screen Recording granted, keys loaded). Capture used to
start only after onboarding completed, so screen history was empty
during the demo.
- While the step is active the kernel gets the demo's content (riddles +
answers) as response context and the voice hub gets it in its system
instruction
(`RealtimeHubTools.systemInstruction(onboardingDemoContext:)`). Door 3
("last word of the first riddle") is answerable even before any frame is
OCR'd or embedded (measured on a named bundle: 156 s from capture start
to searchable text).
- Finishing opens `<scheme>://onboarding/doors-complete`: the app comes
forward and the step shows Continue. A "Back to Omi" button does the
same.
- Bridge action `onboarding_open_doors` drives the step without the
cursor.

**Screen text in chat history (voice turns)**
- The accepted `report_screen_observation` text is journaled as
`metadata.screen_context` on the user row; the kernel surfaces it per
turn as `recentTurns[].screenContext` (bounded to 800 chars, historical)
with a guidance line. "Do you remember what that page said?" resolves
from conversation history.

**semantic_search text fallback**
- When the vector pass returns nothing (embeddings flush in 60 s
batches), fall back to the screenshots FTS index, newest first, same OCR
preview and citations. Verified live: `vector returned 0 results` →
`text fallback returned 1 results`.

## Verification
- `swift test --filter
'ThreeDoorsDemoPageTests|VoiceTurnJournalTruthfulnessTests|HubSystemInstructionTests|KernelContractWireTests|MessageMetadataTests'`:
60 passed.
- `npx vitest run tests/context-snapshot.test.ts
tests/conversation-journal.test.ts tests/context-cache-delivery.test.ts
tests/context-snapshot-turn-revision-index.test.ts`: 92 passed.
- Named bundle `omi-doors` (this branch) exercised on the step:
`onboarding_open_doors` → page opened with rendered key, log
`SBOnboarding: screen history capture for the demo started`, log
`RealtimeHub: onboarding demo note included in voice instructions (533
chars)`; step screenshots before/after opening. Nik ran the three doors
by voice on builds #4–#6.
- UNVERIFIED in CI: the voice-lane answer itself depends on a spoken
turn.

## Product invariants affected

- INV-AGENT-*
- INV-AUTH-1
- INV-CHAT-1
- INV-VOICE-1

Failure-Class: none
Git-on-my-level added a commit that referenced this pull request Oct 20, 2026
…req / 35 ws per pod (#22934)

## Summary
D0b from `plan-d-realtime-gateway.md` §1/§5 and
`cost-gap-plan-2026-10-20.md` lever #6. Prod listen now scales on CPU.
Before this, only socket metrics drove scaling (22 ws/pod and 10
upgrades/pod). This is a config-only change to
`prod_omi_backend_listen_values.yaml`:

| autoscaling key | before | after |
|---|---|---|
| `targetCPUUtilizationPercentage` | (commented out) | **55** |
| `activeConnectionsPerPod` (ws guard) | 22 | **35** |
| `requestsPerPod` (LB-request guard) | 10 | **16** |
| `minReplicas` / `maxReplicas` | 40 / 60 | unchanged (the lead lowers
the floor separately) |

**Why 55% and not the plan's 70%.** The HPA takes the maximum across its
metrics and ignores ratios within 10% of target. A target T therefore
only scales out once mean CPU exceeds about 1.1×T. During the 2026-10-19
incident (15:10–17:25Z), mean listen CPU per pod peaked at 0.56–0.65 of
the 1-CPU request (10-minute means) while the hottest pods saturated. At
70%, and also at 60%, the HPA would never have acted. At 55% it acts
above about 0.60, which would have fired in the 16–17Z window. The
plan's figure of about 17 pods at p50 assumes about 90% utilization;
per-pod CPU is too uneven for that.

**Why both socket guards rise together.** Raising them is for the later
floor drop, not for this roll. Live HPA right now: 14.8 ws/pod (target
22) and 8.8 on `backend_listen_requests_per_pod` (target 10) at 40 pods.
That second metric is every LB response code over a 3-minute window
divided by replicas (prod adapter, no `101` filter), so 8.8 means about
117 LB requests a minute in total, not concurrent upgrades. At the old
targets the guards would hold about 36 and 27 pods. That is below the
floor of 40 today, but it would pin listen near 36 once the floor drops,
so CPU could never take over. At 16 and 35 they bind near 22 and 17 pods
at today's peak, so they act only on connection or request surges. With
the old guards, CPU would still have scaled out at the incident mean
(ceil(40 × 0.65 / 0.55) = 48), because the HPA takes the max. Neither
guard was dropped. The guards cap the per-pod average; they do not cap
the hot pod.

Evidence (ro-prod tier, Cloud Monitoring aggregates only:
`kubernetes_io:container_cpu_request_utilization` for the backend-listen
container, kube-state-metrics HPA status, and a `kubectl get hpa` status
read of the metric values only):
- Last 7 days: mean CPU 0.42 at p50 and 0.62 at p95. Across pods, the
p95 pod is at 0.66 at p50. The hottest pod sat at about 2.0 cores (the
limit) from 06Z to 18Z on 10-20.
- Pre-incident week (10-13 to 10-19, floor 12): 28.7 pods at p50.
- Last 24h (floor 40): mean CPU 0.34 to 0.63. The peak is 16–18Z, with
25 cores across 40 pods.

## Expected pod count by hour (UTC)
Computed from the last 24h as mean CPU × replicas ÷ 0.55, rounded up.
From N ready pods the HPA moves only when the recommendation leaves ±10%
of N. From 40, scale-up needs a recommendation of at least 45.
Scale-down then runs at 1 pod per 120s after a 600s window, so 46 → 40
takes about 20 minutes.

| hour | 00 | 01 | 02 | 03 | 04 | 05 | 06 | 07 | 08 | 09 | 10 | 11 | 12
| 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 |

|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| CPU recommendation | 33 | 35 | 32 | 27 | 27 | 25 | 25 | 29 | 30 | 28 |
30 | 30 | 30 | 35 | 38 | 41 | 43 | 45 | 46 | 36 | 33 | 34 | 33 | 32 |
| as shipped (floor 40) | 40 | 40 | 40 | 40 | 40 | 40 | 40 | 40 | 40 |
40 | 40 | 40 | 40 | 40 | 40 | 40 | 40 | 45 | 46 | 40→ | 40 | 40 | 40 |
40 |

- **As shipped (floor 40):** 15–16Z sit inside the deadband and stay at
40. 17–18Z go to 45–46, then decay back to 40 within about 20 minutes.
That is about 12 extra pod-hours a day, roughly +$1/day, as headroom in
the hours that degraded on 10-19. That is all this PR changes on its
own.
- **After the lead lowers the floor (for example to 25):** about 33 pods
mean versus 40 today, roughly −$16/day at today's per-pod CPU. Before
lowering, confirm the checked-in `prod_omi_backend_listen_cronjob.yaml`
(which patches the floor to 10 at 01Z and 30 at 11Z) is still not
applied. Today `kubectl get cronjob -A` under ro-prod returns none.
- **Path to the plan's −$25/day:** it needs the D0a CPU fix (per-flush
re-encode) to cut cores. Cores per hour at peak are about 25% above the
pre-incident week.

## Rollout and watch
Ship this in an off-peak listen roll that the lead schedules, **not**
together with the STT-routing fix roll, so the two listen changes stay
separately attributable. Watch for 24h:
- Event-loop lag: `histogram_quantile(0.99, sum by (le)
(rate(omi_listen_event_loop_lag_seconds_bucket[5m])))` < 50 ms. This is
the D0b gate in `backend/docs/listen_pusher_pipeline.mdx`. It lives in
the in-cluster Prometheus, not GMP.
- Session failures: listen session terminal-failure and close-code
rates, live STT exhausted/accepted (10-19 baseline 0.25–0.27), and
Soniox `connection_lost` per 10m.
- First-text latency per arm (#22230), plus terminal-after-text.
- HPA: `kube_horizontalpodautoscaler_status_desired_replicas` should
track the table above. Hottest-pod CPU should stay below the 2-core
limit, and liveness/readiness probe timeouts should not reappear.

Known limit: a mean-CPU target does not rebalance a single hot pod; the
long-lived sockets stay where they are. That hot pod existed before this
change. D0a, or the edge gateway, is the fix for it.

## Review
Grok: no blockers. Every should-fix is addressed in the second commit:
- the deadband-corrected table;
- the guard rationale and the corrected units for
`backend_listen_requests_per_pod`;
- the test now pins the reviewed values;
- the CronJob was checked (not in the cluster);
- the stale D0b docs are updated;
- the rollback timing is corrected.

## Lane / contract
Lane pusher-d0b (10-20 swarm P5 Part B); owner sign-offs for edits to
other lanes' files: none

## Product invariants affected
none

## Verification
- `backend/test.sh` on `test_backend_listen_helm_defaults.py`: 10
passed. Layer: unit plus a local `helm template` render.
- New test `test_prod_listen_hpa_scales_on_cpu_with_socket_guards`
renders the prod chart. It asserts a CPU Utilization metric below 60%
and pins the reviewed values: CPU 55, guards 16 and 35, floor and
ceiling 40 and 60. The `listen_pusher_pipeline.mdx` and `listen_loop.py`
text that called the D0b gate "CPU 70%, before the retune" now describes
55% and a 24h watch after the roll and before the floor drop.
- Not run: any deploy. HPA behavior under load is measured only after
the lead's off-peak roll.

## Rollback
Revert this PR (`targetCPUUtilizationPercentage` back to commented out,
guards back to 22 and 10) and roll listen. For an immediate effect
without a roll, an operator can patch the HPA metrics. The HPA
re-evaluates on its next 15s sync. Scale-down still honors the 600s
window plus 1 pod per 120s, so 46 → 40 takes about 20 minutes. A
chart-only listen upgrade that keeps the running image does not change
the pod template, so it updates the HPA without dropping websockets.

Failure-Class: none

🤖 Generated with [Claude Code](https://claude.com/claude-code)


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/22934?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/22934?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F22934&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. -->
Git-on-my-level added a commit that referenced this pull request Oct 22, 2026
…notes, boundaries and lifecycle (shadow by default) (#23335)

## Capture, speaker and notes refactor integration

Integrates L1 `efd6d97d1a5`, L2 `f01392bfc7b`, L3 `2475429ecc1`, L4
`8ec85289796`, and L5 `f4877478d10` in that order, plus current main.
This is a branch-only integration: no PR, main merge, deployment or
cohort change.

- L1: committed frame ledger, intake/dedupe/config hygiene,
authenticated coverage route and export, same-key open-live discovery
without a device. The generated plan alias reader now uses the gated
shared parser.
- L2: ranked evidence, receipt-constrained projection, caches and
pooling; explicit owner/retraction wire events; continuity and GPU
policy packaging; boundary roster candidates retain low,
non-label-eligible priors.
- L3: unified notes packet/output/language work; cache source closure
and effective packet/version identity; metric export;
account/conversation-aware episode rendering and language propagation.
- L4: mounted boundary endpoint, live committed events,
CAS/clocks/boundaries/executors, durable atomic merge admission and
epoch-fenced reconciliation in the existing finalization outbox.
Correction transfer seals the recovery phase atomically; recovery safely
rolls back preparation or replays sealed source cleanup without another
paid notes call. Empty-ready quiet obligations use content/lease-fenced
lifecycle deletion. Normal and recovered merge completion share the
typed notification dispatcher and retain the data-only background
transport.
- L5: mobile Home/owner/custody/continuations and desktop
identity/labels/boundary adapters consume the integrated authorities.
Tombstone-first deletion purges staged chunks even without a parent;
staging expires after seven days and expired parts cannot assemble.
- macOS meeting identity requires call-control chrome for Telegram,
Slack, Discord and WhatsApp. Dominant chat windows no longer supply
meeting participants.

## Flags and ramp

Backend `CAPTURE_COVERAGE_MODE`, `SPEAKER_EVIDENCE_MODE`,
`NOTES_PACKET_V2_MODE`, `STT_LANGUAGE_HINTS_MODE`,
`EPISODE_BOUNDARIES_MODE`, `LIFECYCLE_V2_MODE`, and
`CLIENTS_FROM_SEGMENTS_CHUNKS_MODE` remain shadow by default. Percent
selectors default zero; digest lists default empty. No manifest serves a
cohort. Shadow retains legacy output and adds no duplicate paid
model/transcription call. Coverage records may be written in shadow, but
new committed custody events are emitted only for the capture serving
cohort.

PostHog `clients_refactor`, `clients_from_segments_chunks`,
`clients_boundary_evidence` remain off/unknown.
`custody_capture_committed_release` is a deleting opt-in and requires
explicit boolean true through the identity-fenced reader. No PostHog
rows or cohorts are changed here.

Owner **dazheng**, expansion complete by **2026-10-26**: integrated
synthetic/test cohort → reviewed runtime digest cohort → 1% → 5% → 25% →
100%, with a full clean observation window before each expansion. For
notes/client arms whose lane ramp uses 10%, require the same clean gate
before that step. Before continuation serves, enable Firestore TTL for
`from_segments_chunks.expires_at`; the seven-day expiry field and
assembly checks are implemented, but physical database TTL is not
applied by this code-only task. The reviewed declaration is
`backend/deploy/from-segments-retention.json`;
`backend/scripts/batch_pipeline_ttl.py --policy` produces its plan
without credentials.

Require zero custody loss, false frame suppression, duplicate
per-session conversations, manual-receipt violations, cross-boundary
automatic merges, empty rows reaching paid processing, and pre-durable
committed events. Review dedupe/projection/notes disagreements and owner
attribution, language quality, failed/held work, queue age and merge
dead letters. Exported families include capture coverage/dedupe/retry,
speaker evidence/agreement/owner share, notes shadow/results, lifecycle
shadow, executor task gauges and client refactor comparisons. The
prerecorded-language gate and vendor allowlist entries are retained.

Rollback: set backend mode off and client flags false; already-admitted
durable merge obligations continue reconciling. Do not remove TTL or
rewrite historical data as rollback.

## Invariants and failure class

Invariants: **INV-AUTH-1**, **INV-MEM-4**, **INV-CAP-1**,
**INV-TASK-2**. Identity fences remain authoritative; retained/released
audio requires exact durable proof; merge retraction preserves
correction/Undo and memory ownership; task effects stay behind
successful processing and source retraction boundaries.

Failure-Class: FC-split-mutation-authority

## Validation

- Backend lane lists: **2,897 passed across 87 file-isolated suites**.
Expanded seam run: **334 passed across 15 files**. The full selector ran
once (2,223 isolated files); 34 files exposed
integration/import-isolation regressions, all repaired and rerun. A
132-file affected union was checked; two files caught the brief
in-progress merge conflict and were rerun afterward. The 16-file
post-main run is **624 passed**, including those two. These focused
counts overlap.
- Merge/notification recovery follow-up: **135 passed across 13 files**;
the notification direct-call ratchet decreases by one.
- Real local Firestore emulator: **15 passed**, covering concurrent
merge admission, epoch fencing, atomic correction-transfer sealing,
empty-row deletion races and capture-ledger contention.
- Swift: **49 passed** (43 meeting identity/storage plus six L5 client
tests). Flutter: **58 focused tests passed**, plus the bootstrap's
hermetic spine/shell checks; analyzer ratchet passed with baseline lint
debt retained.
- Backend Pyright after the main merge: **zero errors**, with existing
warning-level debt (47,794 warnings).
- All heavy commands use `omi-heavy` and `nice -n 10`. OpenAPI, Dart,
Swift, TypeScript, feature-registry and plan-catalog outputs were
regenerated from their sources. All seven backend modes were checked
with an empty environment: shadow and no serving without a cohort.
Client readers require explicit boolean true, and no serve cohort is
introduced in manifests.

**Body-aware preflight: all 67 selected checks passed, zero skipped**
(also repeated successfully on the final pushed tip), after repairing
the notification boundary. The required non-force push passed its
exact-tip pre-push gate: current preflight, backend Pyright (zero
errors), bounded backend tests, OpenAPI/wire contracts, Flutter
generated output, Dart formatting and Swift compile. No production
reads, production API calls, GCP credential tier, deployment or paid
evaluation is used.

Publication: non-force push succeeded at **2026-10-22 19:20Z**, before
the 21:30Z cutoff. Remote and local tip both verify as
**`8892f2b85e7d5790c8b9a40169cdeffd9f8bb573`**, including review fix
`ec90304a8ca` and current main
`312b4f734c22900547ff23e7260f69622b6aa36b`. All five lane tips remain
ancestors; worktree is clean. The exact-tip pre-push gate passed: 67
selected preflight checks, Pyright zero errors, bounded backend tests,
source closure, OpenAPI/client compatibility, Flutter code generation,
Dart/Python formatting and Swift compile. The separate all-gates
preflight passed 68 gates with no failure or time skip. No GitHub
Actions runs are listed for this branch at verification, so this is
local-gate evidence, not a terminal GitHub CI claim. No PR, deployment
or cohort change is part of this task.

## Review findings

GLM lane reviews plus the contact-name addition are reconciled below.
All required-before-merge and required-before-ramp fixes are
implemented. Defaults remain shadow/off; no cohort or deployment
changes.

| Finding | Status | Resolution |
| --- | --- | --- |
| L1 #1 route registration | Done | Already integrated: authenticated
route policy, app role via sync mount, OpenAPI prefix and regenerated
wire outputs; push gate passes. |
| L1 #2 shadow audio fetch | Done | Shadow uses only an
already-prefetched manifest; full provider audio fetch requires the
capture serve cohort. |
| L1 #3 derivative cleanup | Done | Trim returns ownership of generated
and retired paths through the coordinator cleanup set, including fully
suppressed input. |
| L1 #4 dark metadata | Done | Accepted internal-only delta; missing
envelopes/optional identity fields are guarded and tested. |
| L1 #5 empty uploads | Done | Synthetic covered response is serve-only;
shadow/off retain legacy empty admission. |
| L1 #6 open-live binding | Done | Already integrated: no-device
discovery gate plus full capture/session/clock projection and
transactional selection. |
| L2 #1 preserve established labels | Done | Abstaining clusters emit no
replacement decision; accepted voice candidates and scoped manual
decisions alone project labels. Reprocessing fixtures preserve
established owner/person labels and identity status with expired audio,
exhausted budget or a deleted print. |
| L2 #2 pinned operating points | Done | Independent literal and
comparison-strictness pins cover every legacy point, plus each env
override and the shared finalize/cross-epoch binding. |
| L2 #3 ownership | Done | Integrator ratifies the voiceprint-scoped
users.py and speaker_assignment_effects.py edits and the documented
conversation_speakers path correction. |
| L2 #4 second wire emitter | Done | Owner/retraction adapter already
integrated; the transcript introduction emitter now explicitly declares
is_user=false because it is contact-only. |
| L2 #5 malformed evidence | Done | Evidence reads fail open to existing
labels, with a bounded error log and fallback counter; malformed
content/identity is not logged. |
| L2 #6 policy consumers/markers/provenance | Done | Continuity and GPU
policy imports were integrated; missing superseded markers added and
original offline measurement provenance restored. OperatingPoint.accepts
remains a tested pure policy utility. |
| L2 #7 pooling edges | Done | Legacy multi-sample provenance is
retained as one aggregate base, replaceable/retractable as one
contribution. Sample deletion already preserves the materialized
remaining source; regression coverage pins it. |
| L4 F1 shadow read cadence | Done | Bounded owner/client-scoped
60-second caches cover shadow windows and unchanged context ingestion,
with write invalidation. Serve reads remain fresh. |
| L4 F2 candidate widening | Done | Numeric/ISO timestamp normalization
requires the lifecycle serve cohort; shadow/off retain raw datetime-only
eligibility. |
| L4 F3 rescheduling | Done | Calendar identities accept an updated
start/window; non-calendar starts remain immutable and same-start end
retries cannot reopen. Saved row contexts cannot rewind an authoritative
calendar reschedule. |
| L4 F4 post-commit hardening | Done | Malformed run grouping and
optional publication failures cannot fail an already-durable transcript
flush or trigger rollover. No custody event is emitted without ledger
success. |
| L4 F5 integration gaps | Done | Boundary mount/policy, durable merge
leases/reconciliation, empty-ready deletion and serve-only bounded
executor were completed in integration. Shadow/off deliberately retain
the legacy executor. |
| L4 F6 sanctioned deltas | Skipped | Informational: retain the
brief-authorized cap/CAS/UTC fixes and same-value activity/speech dual
writes; no additional behavior change. |
| L4 F7 missing producer | Done | L1 coverage is present in the composed
runtime and source-closure checks; no absent-module stub or bypass. |
| L4 F8 cold emulator contention | Skipped | Informational flake; no
weakened retry/fixture policy. The current 15-test emulator run includes
the concurrent-reconnect case and passed; this is not treated as a
production defect. |
| L5 #1 custody index failure | Done | Newly released copies revert to
repair on failed index persistence. Flush durably commits a release
before retention can act on it; no extra save in default mode without a
release. Failure fixtures preserve the audio file. |
| L5 #2 continuation flag withdrawal | Done | Prepared input is
terminalized once as continuation_disabled, with the prepared copy
dropped and the audio retained. Status/reason are durable; no repeated
recognition/upload, including without a model. |
| L5 #3 unfinished Home rows | Done | Serving hides in-progress,
processing and merging members until completed/failed. Flag-off behavior
remains identical. |
| L5 #4 missing desktop finish | Done | Chunked finalization derives an
absent finish from the latest finite positive segment end; explicit
finish and legacy single-shot behavior are preserved. |
| L5 #5 early chunk validation | Done | Finite, nonnegative,
positive-duration and nonblank segment checks run before any staged
write. |
| L5 #6 projection-digest response | Skipped | Optional protocol
expansion is beyond a cheap follow-up: it needs a versioned
response/decoder contract. Frozen clients already keep a stable
projection; retain first-staged display-only projection and list digest
negotiation as follow-up. |
| L5 #7 agreement log noise | Done | Mobile comparison helper and
desktop hot paths log disagreements/errors only; backend agreement
counters remain available without per-agreement log lines. |
| L5 ownership/registry notes | Done | Integrator ratifies extracted
developer intake/models/tests for the line-count boundary; the L1-owned
coverage registry declaration was reconciled at integration. |
| Ambiguous contact names | Done | Rule preserves transcript spelling
when contacts compete and forbids merging shared first names. Synthetic
packet fixture lists confusable and shared-first-name candidates without
choosing or projecting a label. |

Review-pass validation: **1,180 passed across 29 focused backend files**
after merging P71; **157 passed across six final seam files**
(overlapping the broader run), **33 Flutter tests**, **seven Swift
tests**, and **15 local Firestore emulator tests**. Pyright after the
main merge: **zero errors** (47,827 warnings under the repository's
warning-level checks). The only initial new-fixture failure was its
missing policy_version; corrected and rerun. No required finding is
deferred to the ramp. Review-pass body-aware preflight: **68 gates
passed, zero failures, zero time skips** (492 seconds). Exact-tip
pre-push passed; the remote SHA and gate receipt are recorded above.

## UI evidence

L5's real ConversationsPage hermetic renders are retained unchanged by
integration.

![Shadow
Home](https://raw.githubusercontent.com/BasedHardware/omi/5d66b99f2460e1a591d87df7323789244180f7ca/.agent-artifacts/ui-evidence/refactor-l5-clients/001-mobile-ios-home-shadow.png)
![Serve
Home](https://raw.githubusercontent.com/BasedHardware/omi/5d66b99f2460e1a591d87df7323789244180f7ca/.agent-artifacts/ui-evidence/refactor-l5-clients/002-mobile-ios-home-serve.png)

## Conflicts

Review-pass main merge: `312b4f734c2` brings the P71 as-captured archive
ruling. Resolve the `audio_archive.py` parser conflict by preserving
main's LIVE/READ default-on behavior through the shared default-on
helper; all seven refactor modes remain shadow and their cohorts empty.
The registry renderer synchronizes those inherited kill-switch metadata
fields and regenerates the doc. No refactor serving default is enabled.

Lane merge conflicts were flag declarations and dead-code metadata. The
final main merge also conflicted on the sync-router imports and the
metric-export regex: retain both route/playback imports and the union of
metric families, including main’s playback metric and the pinned
language/vendor entries. Preserve each authority's declarations, retain
consumed-contract removals, and regenerate the registry. OpenAPI and
client wire artifacts are regenerated after route composition. The
dead-code tool explicitly never generates/prunes allowlists; merge their
explicit declaration changes and validate them with the tool rather than
inventing missing exemptions. No product-code conflict was resolved by
taking an entire side.

## Risks and remaining rollout work

- No deployed/product acceptance claim: PostHog configuration, physical
Firestore TTL activation, runtime cohorts and semantic
attribution/language sampling still require the owner-led ramp.
- Source provenance absent from older/on-device results remains unknown;
partial segment overlap retains audio rather than guessing alignment.
Simultaneous read-only admissions can still duplicate provider spend
before transactional dedupe observes a committed winner.
- Speaker calibration starts at existing operating points and
process-local embedding caches do not imply cross-replica reuse.
Evidence can briefly lag transcript persistence.
- Persistent sealed merge cleanup failure stops after five attempts,
retaining its survivor and durable failure record for reconciliation. No
speculative restoration after correction anchors move.
- L3 filtering only drops explicit `out_of_profile` metadata. The
independent live language observer remains telemetry-only; expanding
stored classification and the topic request's optional classified-input
support is follow-up work, not a new heuristic in this integration.
- GPU policy source closure and local tests do not prove a deployed GPU
image. Client screenshots remain the L5 hermetic page evidence; no
named-bundle live E2E or physical-device custody test is claimed.

## Deletion follow-up after bake

1. Retire legacy capture text/clock dedupe, open-target selection and
config parsers only after missing-speech and held-work gates are clean;
add the same-audio-twice synthetic soak case to private staging tooling.
2. Retire competing speaker hard-label writers and legacy voiceprint
replacement after evidence/receipt and Undo acceptance; keep
released-client sentinel reads until supported versions adopt explicit
owner events.
3. Retire the legacy notes packet/output/prompt branches after quality
sampling; move remaining offline-only episode selection/tier helpers
alongside evaluation code.
4. Retire legacy merge admission and redundant speech-clock readers
after outbox recovery bake; stop `finished_at` compatibility dual-writes
only when all consumers migrate.
5. Retire old Home, local-label and 500-segment/refusal/compaction paths
after client adoption. Verify physical staging TTL and account-erasure
coverage before deleting migration adapters.
6. Append-only segment storage and the pusher session-state restructure
remain separate follow-ups.

🤖 Generated with [Claude Code](https://claude.com/claude-code)


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/23335?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/23335?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F23335&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. -->
Git-on-my-level added a commit that referenced this pull request Oct 24, 2026
## What changed and why

Monthly allowance refreshes repeatedly scan `hourly_usage` (caller #6,
about 42M reads/day in the sprint's latest-hour snapshot). Maintain five
monthly counters and daily subtotals in the same transaction as hourly
usage and its existing once/partial receipt. Warm full-month and
since-day lookups read one document. Absolute history overwrite, admin
reset and historical deletion atomically invalidate the total; first use
rebuilds from hourly source rows. Legacy anomalies retain the existing
query.

Every new aggregate creator binds erasure authority to publication:
ordinary, once-key, absolute, admin and migration writers use the
existing `external_write_fence` and require a user root inside their
transaction. Authority reads precede all receipt/source/total writes.
Rejected publication leaves receipts untouched. Existing batch
projection completion/partial transactions reuse their
deletion/root/privacy checks. Lead approved this strengthening in ANX
`event:ev_5e7c48e900024551f307ab9c3e254fd7`.

Usage publication refusals are non-fatal to user-facing pipelines. The
shared `utils.analytics.record_usage` composition boundary catches the
refusal outside the transaction: conversation/transcript/audio
processing completes while hourly/monthly counters and the once receipt
remain uncommitted. A typed missing-root refusal is distinct from a
deletion/destructive-operation refusal in `omi_fallback_total` and
matching fixed-field logs (`component=usage_publication`,
`from_mode=publish`, `to_mode=skip`, `outcome=degraded`, reason
`usage_root_missing` or `usage_fence_blocked`); no UID, content or
exception text enters labels/logs. All user-facing source writes use
this helper. Direct admin/migration operations keep their refusal
semantics. Cold reader rebuild already returns to the hourly query on
root absence; no other production user path gains a root dependency in
this PR.

Hermetic regressions cover a root absent before sync admission, root
removal immediately before publication, pending/completed deletion and
ordinary live-account once replay. They require completed sync, the
persisted conversation/transcript, no aggregate/usage receipt on refusal
and an incremented bounded counter. Deletion still returns 403 for HTTP
polling. The Firestore fake now preserves subcollections during root
deletion, matching Firestore; a harness self-test checks repeated
deletion without recreating the root.

## Rollout and rollback

Writer maintenance ships ON. Reader `usage_month_total` remains 0
because mixed-version writers can undercount paid/Free allowance. Lead
owns merge, deploy and ramp. Target writer train: **2026-10-24 08:00Z**,
cutoff **07:30Z**. Deploy every writer (listen → pusher → Cloud Run →
desktop-backend, plus operator/migration tooling); verify actual serving
identities/traffic and drain old jobs. Choose a common
`FSR_USAGE_MONTH_TOTAL_EPOCH`, then 5% for two hours with zero synthetic
parity mismatches, no p95/5xx regression and no contention errors.
Lead/reads loop expands to 100%.

The original 08:00Z full-ramp deadline conflicts with an 08:00Z writer
train plus the required hold. **Proposed replacement: 2026-10-24 12:00Z,
pending lead acceptance.** Report any writer/parity blocker. Details:
`backend/docs/monthly-usage-totals.md`.

Kill switch: `usage_month_total:0`, preserving other levers. Writers
continue maintenance. After rollback to any old writer, change the epoch
on all readers before re-enabling. Epoch wiring uses existing
manifests/renderers; no new workflow.

## Attribution and net economics

Origins: `job:usage_month_total_read`, `job:usage_month_total_rebuild`,
`job:usage_month_total_fallback`. Grade all three alongside original
monthly and writer caller origins. **Up to 40M/day gross reader
reduction is modeled, not measured.** Previously unfenced writer/replay
attempts now add **three point reads** (deletion marker, destructive
gate, root) per commit attempt. If their daily count is W, subtract 3W
plus cold-seed scans/point reads and fallbacks from gross reduction;
account separately for one added total write per accounting commit.
Retries and existing outer fences may add further reads. Example:
W=1M/day implies at most 37M/day before those other costs. W and
realized net saving remain unmeasured. Funded `read_month` and
plan/shadow readers retain their existing paths.

## Product invariants affected

INV-MEM-4: `backend/deploy/runtime_env.yaml` wires the epoch; canonical
memory intake/promotion keeps its authority. Existing deletion fences
are strengthened by transaction-bound reuse under the lead's explicit
ruling. Free-plan allowance policy, authorization, transcripts and
speaker labels retain their behavior.

## Validation

- Latest integration head **`9efacbc5723b866a598c061986d8718d960071d6`**
includes main **`0d302a99fe`** (#23402) and **`251892e223`** (#23393).
Only adjacent feature declarations conflicted. All
monthly/snapshot/released-memory declarations and query proof registry
entries are preserved; the feature registry keeps its existing
2026-10-22 date. The reviewed safety code and regressions are unchanged
from safety commit `162181c8d8`.
- Normal integrated-head commit/push hooks passed; evidence
`nonfatal-main2-push.log`. No workflow, timing budget, test selection,
skip hatch or force-push change. [Live exact-head
checks](https://github.com/BasedHardware/omi/pull/23397/checks) are
authoritative: require every expected backend check, all six unit shards
and aggregate gate, full Hermetic E2E and merge gate, emulator proofs,
guardrails, source closure, static contracts, metadata, hygiene and
formatting to be present and successful before merge. The final gate
certificate belongs to the lane handoff; no stale-head or
check-presence-only certification.
- Safety delta local evidence: **165 focused unit passes** (47
sync-two-lane, 24 monthly total, 60 usage units, 34 user usage), **24
targeted hermetic passes**, and **56 loopback monthly Firestore emulator
passes**. Eight ordinary/once refusal cases prove zero writes/committed
usage receipt, exact bounded reason counter/log, and unrelated errors
still propagate. Real finalize cases include a root absent before
admission, root removed immediately before accounting, pending/completed
deletion and live once replay; the job and persisted decoded
conversation/transcript complete. Evidence: `nonfatal-unit2.log`,
`nonfatal-unit3.log`, `nonfatal-hermetic2.log`,
`nonfatal-emulator2.log`.
- Full Hermetic E2E on predecessor `f05a38addd`: **135 passed, 3
skipped, 2 xfailed**, 110.56s
([job](https://github.com/BasedHardware/omi/actions/runs/40028805287/job/120671936148));
emulator, other five shards and stack checks also passed. That head was
not green: its first shard-3 attempt passed all 66 runtime-image
assertions but failed a **1.17s / 1.00s CPU guard**; one bounded
same-head retry passed all test files and the CPU guard but failed the
unchanged **723s / 720s wall gate**. Earlier safety head `162181c8d8`
failed wall **733s / 720s**. No further identical reruns are queued.
Main #23402 then advanced and caused a real merge conflict; the latest
head integrates that changed source/test input. Timing evidence:
`nonfatal-final-unit3-failure.log`,
`nonfatal-final-unit3-retry-failure.log`,
`card:fs-p3-ci-unit-wall-budget`.
- One requested safety delta Luna review: **SHIP, no P0/P1**, execution
`exec-express-mask-gap-tennis-atom-bundle`; static production/caller
review, `nonfatal-luna-review.md`. Later changes only corrected test
setup/fake deletion semantics and integrated already-reviewed main. No
review loop.
- Earlier writer proof remains: fake **744 source reads to 1 warm
read**, identical five-field/day-cutoff results, three writer authority
reads and one added total write. Monthly emulator proofs include all
original creator erasure cases, receipt rollback/retry/replay and racing
root/deletion inventories. Four historical broader projection failures
also reproduced on then-main `4d236fd94e`, tracked on
`card:fs-p3-projection-emulator-baseline`; the broader suite was not
rerun after the latest upstream integration.

All local checks use `omi-heavy` at nice 19 with targeted FILE_LIST or
hermetic `-k`. No full local backend unit suite, production data, GCP or
deploy action. Reader remains off until lead-owned writer/epoch gates;
realized net savings are unmeasured.

## UI evidence

UI-Evidence: none -- backend accounting/read-path change.

## Failure class (fixes)

Failure-Class: none

The erasure defect was found within this unmerged feature; no shipped
incident is classified. ANX owner/evidence: `card:fs-p3`,
`card:p88-monthly-usage-cold-seed-erasure`.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
Git-on-my-level added a commit that referenced this pull request Nov 27, 2026
…s 503 (SCA-2225) (#26458)

## What

Every handler-level designed 503 refusal on `POST /v2/sync-local-files`
now writes exactly one INFO record:

`sync_upload_refused uid=%s status=503 reason=%s trace=<32-hex
X-Cloud-Trace-Context id>`

The mechanism lives in `utils/sync/designed_refusal.py`:
- The handler calls `mark_designed_refusal(...)` right before the
designed 503.
- `designed_refusal_outcome`, the innermost decorator, captures the
handler's own response or exception.
- `records_designed_refusals`, outside `custody_upload`, writes the
record only if the final outcome is that same object and is a 503. A 503
that the custody finalizer substitutes is left unrecorded.
- The fence cutover is marked only when `SYNC_LEDGER_FENCE_MODE` is
explicitly `standby`, so an invalid setting that fails closed is not
marked.

The existing `backfill_day_cap` line moves onto this mechanism. Failure
503s write no record. Those include `sync_dispatch_unavailable` (staging
or sequencer), `sync_batch_unavailable` from batch-admission errors,
custody, config and platform 503s.

## Why

SCA-2225. The Cloud Run rollout guard used to exclude every
sync-local-files 503 (`refusal_statuses: [503]`), which hid real
failures. Removing that exclusion outright flips the labelled trip
backtest, because designed backpressure then counts as errors. Luna
approved a design on SCA-2225 (2026-11-27T00:09Z): exclude a 503 only
when the same revision logged a designed-refusal record for the same
request, and hold on anything that cannot be reconciled. The `trace=`
field lets the guard match each record to its own request log
one-to-one, so window edges do not skew the counts. The guard side of
the change is a separate PR stacked on #26438 (linked below).

Production shape check (ro-prod `read-only-bot-account`, 2026-11-27,
projections only, no payloads or uids read): backend-sync 503 request
logs for this route carry `trace=projects/based-hardware/traces/<id>`.
The existing `sync_upload_refused … status=503` records land in
`run.googleapis.com%2Fstdout` with `resource.labels.revision_name`.

### 503 inventory: `POST /v2/sync-local-files` (BasedHardware/omi
`origin/main` f628eab)

Line numbers are at f628eab. "Record" means one `sync_upload_refused
uid=… status=503 reason=… trace=…` line. The handler marks the refusal
right before its 503, and the outermost wrapper writes the line only if
that same 503 is the final response. Before this change, only #8 wrote a
record, and that record had no trace. `sync_upload_refused` is written
only inside `sync_local_files_v2`; no other route or file writes that
string.

| # | file:line | code | trigger | designed? | record before | record
after |
|---|---|---|---|---|---|---|
| 1 | utils/sync/stage.py:50 (router dependency) | stage unavailable |
`OMI_ENV_STAGE` missing or invalid | failure (config) | no | no (counts
as error) |
| 2 | utils/other/endpoints.py:65 | `directory_routing_unavailable` |
directory resolution fails | failure | no | no |
| 3 | utils/other/endpoints.py:112 |
`account_deletion_state_unavailable` | deletion-fence read raises |
failure | no | no |
| 4 | utils/account_cutover/access.py:260/262 |
`account_cutover_state_unavailable` | cutover state unreadable | failure
| no | no |
| 5 | live_upload.py:118 via `memoized_record_wait` (sync.py:852) |
`record_capture_pending` | cached conversation-level wait | designed |
no | **no (gap, see below)** |
| 6 | sync.py:873 | `sync_ledger_fence_cutover` | fence mode STANDBY |
designed pause only when explicitly configured* | no | **yes, explicit
standby only** `sync_ledger_fence_cutover` |
| 7 | sync.py:973 | `backfill_capacity` | backfill lane,
`SYNC_BACKFILL_ENABLED` off | designed (kill switch) | no | **yes**
`backfill_disabled` |
| 8 | sync.py:1040 (log at 1038) | `backfill_capacity` | unlimited_v2
backfill day cap | designed | yes, no trace | **yes**
`backfill_day_cap`, now with trace |
| 9 | utils/sync/record_token_lease.py:120 | custody admission |
`record_custody_append.begin` raises | failure (custody) | no | no |
| 10 | utils/sync/receipt_clock.py:197 / :204 |
`capture_clock_anchor_unavailable` | :197 too many scopes (bounded
refusal); :204 read fails | :197 designed, :204 failure | no | no (gap
for :197) |
| 11 | sync.py:1118 | "Historical recovery is paused" | retained
recovery while backfill is off | designed | no | **yes**
`retained_recovery_disabled` |
| 12 | sync.py:1169 | `capture_clock_identity_required` | future-clock
files with no device id | designed | no | **yes**
`capture_clock_identity_required` |
| 13 | live_upload.py:118 via record router (sync.py:1265,
intake.py:750) | `record_capture_pending` | 9 wait reasons are designed;
4 `*_failed` reasons are failures | mixed | no | no (gap for the waits)
|
| 14 | intake.py:749 | `record_capture_pending` | `record_router` is
None | wiring fault, unreachable | no | no |
| 15 | utils/batch_pipeline/upload_coalescing.py:242 |
`sync_batch_unavailable`, Retry-After 1 | coalescing wait | designed |
no | no (gap) |
| 16 | intake.py:987 | `sync_batch_unavailable` | decode-failure memo
hit | designed repeat | no | no (gap) |
| 17 | intake.py:1271 (`FutureCaptureRetry`) |
`capture_clock_anchor_pending` / `identity_required` /
`anchor_unavailable` | clock anchoring in batch decode | pending and
identity designed; unavailable failure | no | no (gap) |
| 18 | intake.py:1298 | `sync_batch_unavailable` | any batch-admission
exception | failure | no | no |
| 19 | sync.py:1421 | `sync_batch_unavailable` | batch declined an
estimated or retained-clock upload | designed decline | no | **yes**
`repaired_clock_batch_declined` |
| 20 | sync.py:1608 | `backfill_capacity` | backfill lane but not Cloud
Tasks eligible | failure (config, fail closed) | no | no |
| 21 | sync.py:1664 | `dispatch_hold` | staging hit
`DestructiveOperationInProgress` | designed pause | no | **yes**
`dispatch_hold` |
| 22 | sync.py:1675 | `sync_dispatch_unavailable` | GCS staging failed |
failure | no | no (counts) |
| 23 | sync.py:1758 | `sync_dispatch_unavailable` | sequencer
registration failed | failure | no | no (counts) |
| 24 | record_token_lease.py:93 (`@custody_upload` finally) | custody |
`record_custody_append.finish` raises; can replace any response |
failure | no | no |
| — | Cloud Run platform | — | no instance, queue full, crash | infra |
no app log | no (counts) |

\* #6: an invalid fence setting also fails closed to STANDBY
(`database/sync_jobs.py:154`) and returns the same 503. Since 61972e1,
only `SYNC_LEDGER_FENCE_MODE=standby` is marked; an invalid setting
stays unrecorded and counts as an error (regression test included).

**Records gap (designed, but still counted as errors):** #5, #10:197,
the wait reasons in #13, #15, #16, and #17 pending/identity. These 503s
come from below the handler: `live_upload`, batch intake,
`receipt_clock`. There the request's trace is not in scope, and the same
response code is shared with failure paths. Batch intake's outer `try`
also rewrites exceptions into the generic `sync_batch_unavailable`.
Recording them needs the trace passed down (for example a contextvar)
and its own review. Until then they count as errors on both revisions,
which is the conservative direction: a candidate that changes their rate
is scored as a 5xx change.

**Custody finalizer (#24), fixed in 61972e1:** the record used to be
written before `@custody_upload` finished, so a finalizer 503 could
replace a designed response after its record existed. Now
`designed_refusal_outcome`, the innermost layer, captures the handler's
own response or exception, and `records_designed_refusals`, outside
`custody_upload`, writes the record only if the final outcome is that
same object and is a 503. A finalizer-replaced 503 stays unrecorded and
counts (regression test included).

**Logging path:** the `utils/sync/designed_refusal.py` logger propagates
to the root handler that `main.py:27` installs through
`configure_logging(K_SERVICE, default_format='text', …)`. That handler
writes INFO to stdout as `INFO utils.sync.designed_refusal:
sync_upload_refused uid=… status=503 reason=… trace=<32 hex>`. Cloud Run
ingests stdout as `textPayload` in `run.googleapis.com%2Fstdout` and
labels it with `resource.labels.revision_name`. The trace comes from the
`X-Cloud-Trace-Context` header the handler already declares. It is the
trace id Cloud Run writes into the request log's `trace` field. No PII
is added beyond the existing `uid=` pattern.

## Composition and order

- This PR touches no guard files, so it has no conflict with #26438
(`lane/holdback-wiring`). The guard change is a separate PR stacked on
#26438: #26459. The workspace copy is Git-on-my-level/omi-workspace
#586.
- **Order:** this PR should be serving on backend-sync before either
guard change scores Sync. Before that, a revision's old
`backfill_day_cap` record carries no `trace=`, and the guard holds
(`INSUFFICIENT_DATA refusal_records_unparseable_record`) on any window
where that revision logged one. The first comparison against a pre-trace
inverse can therefore hold once.
- Rollback: revert this PR. The records are log-only; responses and
behavior are unchanged.

## Verification

Run with `omi-heavy run -- timeout 1800 bash test.sh …` (local,
hermetic):
- `test_sync_designed_refusal_record.py`: 19 passed.
- `test_sync_backfill_day_cap_upload.py` 11,
`test_logging_entrypoint_guard.py` 51,
`test_sync_ledger_fence_cutover.py` 14, `test_sync_capture_time_skew.py`
160: all passed.
- The other suites that touch `sync_local_files_v2` (future-early
parity, schema inventory, legacy dark, fair use, mobile standard batch,
batch language router, cloud tasks, assignment recovery, `test_sync_v2`,
batch intake outcome, custody admission privacy): 14, 15, 48, 30, 27,
31, 40, 210, 13, 51 and 193 passed.

The new tests cover:
- the record format and trace parsing, and the guard parser reading the
shared text format;
- a raised designed 503, which is recorded once and still raised;
- a mark made without the outer recorder, which writes nothing;
- **custody finish failing after a designed refusal**, which gives the
finalizer's 503 and no record; a clean finish records once;
- a wrapper replacing the response, which writes no record;
- the decorator order: recorder, then custody, then observe, then
capture, then handler;
- **an explicit `standby` fence, which is recorded; an invalid setting
(`stanby`, `on`) gives the same 503 with no record and logs
`invalid_config`**;
- a real over-cap upload, which writes exactly one traced record;
- an AST check that the seven marks each sit directly before a designed
503.

Not proven here: that production records carry the trace id. That needs
this PR serving, then a READBACK that `sync_upload_refused … trace=`
lines match request-log traces on the same revision.

Line-Count-Exception: backend/routers/sync.py | 4393 -> 4405 | seven
designed-refusal marks, the explicit-standby guard and two decorator
lines; the mechanism lives in utils/sync/designed_refusal.py

## Product invariants affected

none

🤖 Generated with [Claude Code](https://claude.com/claude-code)
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.

3 participants