Repository navigation
harden: sample fresh reads on usage and episode-member cache hits - #25061
Conversation
Failure-Class: none
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f1dee8bcaa
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| from .llm_usage import nest_usage_fields, resolve_usage_plan_id | ||
| from .usage_units import hourly_shadow, normalize_plan_usage | ||
| from models.user_usage import UsageStats | ||
| from utils.read_cache_shadow import compare_hit |
There was a problem hiding this comment.
Keep cache observation below the database import boundary
Importing utils.read_cache_shadow from database.user_usage reverses the repository's explicitly required dependency hierarchy. It also makes the persistence module depend transitively on episode-specific telemetry through utils.episodes.metrics, even for consumers that only need usage accounting. Move the shared cache-observation primitive into the database layer (including a lower-layer metric registration dependency) so both usage and episode readers can consume it without reversing that boundary.
AGENTS.md reference: backend/AGENTS.md:L168-L174
Useful? React with 👍 / 👎.
| except Exception: | ||
| _record(cache, 'error') | ||
|
|
||
| from utils.executors import read_cache_shadow_executor, submit_with_context |
There was a problem hiding this comment.
Move the shadow helper's imports to module scope
The new helper imports fresh_reads inside compare() and the executor dependencies inside compare_hit(), contrary to the backend guide's explicit requirement that all imports be at module scope. These dependencies are therefore resolved only when a sampled hit executes rather than being exposed in the module's dependency declarations. Move both imports to the top level, restructuring the shared helper's location if necessary to preserve the required layering; the newly added function-local imports in the cache tests should follow the same rule.
AGENTS.md reference: backend/AGENTS.md:L168-L168
Useful? React with 👍 / 👎.
| return { | ||
| cid: row | ||
| for cid, raw in members.items() | ||
| if (row := conversations.prepare_conversation_for_read(raw, uid)) is not None |
There was a problem hiding this comment.
Bound preparation reads within the shadow deadline
When a sampled member needs a neutral minimum title and its timezone cache entry has expired or been evicted, this preparation call performs another Firestore RPC: prepare_conversation_for_read calls home_titles.project_home, which resolves the timezone through notifications.get_cached_user_time_zone. That helper calls .get(field_paths=['time_zone']) without a timeout or retry override, so the five-second deadline applied to get_all does not bound the complete shadow operation. During Firestore degradation, two such reads can occupy both shadow workers beyond the intended budget and cause subsequent comparisons, including usage checks, to be rejected. Avoid title presentation work for the ID-only comparison, or propagate the remaining deadline and no-retry policy through all preparation reads; the backend guide also prohibits submit_with_context pipelines that hold a slot for more than ten seconds.
AGENTS.md reference: backend/AGENTS.md:L274-L275
Useful? React with 👍 / 👎.
Failure-Class: none
Keep key canonicalization in the background worker, match registry metadata to the enabled default, and attribute member shadow reads to the shadow job. Failure-Class: none
## Behavior — enrollment closes before the owner fetch Only identical episode list/detail/lookup calls that enroll **before the owner starts `_fetch_members`** may share that owner's read. The owner closes `accepting` under the same map lock used for enrollment, then immediately fetches inline. Any caller arriving after enrollment closes bypasses directly to its own fresh read, even while the owner is still fetching or preparing its earlier snapshot. There is no grace sleep or batching delay. This corrects a concrete freshness defect in the earlier implementation: its unfinished Future could already contain a snapshot captured before a deletion/edit that completed before the next request began. The new request incorrectly inherited that snapshot. The old green tests did not establish freshness because their enrollment barrier was inside `get_all`, too late to be a valid sharing boundary. That earlier implementation is superseded. The bounded flight record carries a private Future plus `accepting`. Closed records remain in the map until owner completion for capacity accounting. Late bypasses neither replace nor remove them; cleanup checks record identity. The map still admits at most 128 flights with at most 1,000 unique member IDs each, keyed by Firestore plane, uid and sorted unique IDs. Capacity/oversized/reentrant calls use the independent read without truncation. Owners fetch inline with no child executor job; nested reads bypass flights. Exceptions/cancellation release early waiters and permit retry. Cancelling a waiter cannot cancel the owner. Every participant receives an independent deep copy. Completed flights/results are not retained; no writes, visibility/entitlement rules, plan filters or client shapes change. The existing `episode_members_singleflight` read lever remains default 100. Explicit 0 in the existing `FIRESTORE_READ_LEVERS` object restores independent reads at the new flight layer; the separate pre-existing cache behavior remains unchanged. No serving config is changed. The separate `episode_members_cache` remains default 0; its 60-second TTL is neither activated nor repurposed by this PR. Source default0 is not a live off-state claim: firestore-lead ec5e02 reports that cache100 on the serving backend, so this feature only sees cache misses there. Actual eligible overlap must be measured. Existing fixed-cardinality `firestore_cache_requests_total` namespace `fsr_episode_members_flight`, results `owner|coalesced|bypass|error`, remains unchanged and contains no uid/member identifiers. No production threads, tasks, executors, grace periods or TTLs are added. Original base: `BasedHardware/omi@aa3df45`. Prior-art review found merged #24929 (dark TTL memo), #25061 (shadow observation), and the audio rebuild Future pattern; no duplicate open episode-member coalescing PR was found. This corrective commit changes only `home_read.py` and its focused single-flight test file. Failure-Class: FC-read-in-flight-across-delete-resurrects-row The same stale-adoption mechanism applies here: a later request must not inherit an underlying read issued before its completed deletion. The guard is now the pre-fetch enrollment boundary, tested through the real member helper; no registry definition is changed. ## Restricted validation Serial, isolated file processes through workspace `bin/omi-heavy`, using this worktree's own Python 3.11 `backend/.venv`, with host load checked below 60 before heavy admission: - `.venv/bin/python -m pytest tests/unit/test_episode_members_singleflight.py -q`: **22 passed**. - Episode member cache/home/router siblings: **25 / 33 / 11 passed** respectively; **91 focused tests total**. - The new real `_read_members` regression first failed all **3** deletion/edit/soft-deletion cases against the old implementation. With the fix, it captures an independent fake-SDK snapshot, pauses owner preparation, completes the mutation, then proves the late caller makes its own second RPC and sees missing/current state before releasing the owner. It also proves that bypass keeps the original closed record. - Early-sharing tests now pause the owner metric callback before enrollment closes and assert no SDK call has started when waiters enroll. Isolation, independent deep copies, shared errors then retry, capacity/ID bypass, reentrancy, owner/waiter cancellation, rollback and metric failures remain covered. A closed-capacity case checks that neither same-key nor new-key bypass replaces/removes the owner. - From backend, `.venv/bin/pyright --pythonpath .venv/bin/python utils/episodes/home_read.py`: **0 errors, 45 warnings**. Pinned formatting passes. The corrective commit is `a88ccda60f11c0937d55fdd4c8def55955184b04`. The normal push hook passed all 36 selected preflight checks (including the seven-file Firestore guard: 847 passed), standard backend type checking with 0 errors, and the changed single-flight file: 22 passed. The unchanged 40-file cap restricted the broad selector to that changed test file. Final command/log results are in the appended implementation receipt. No full backend suite, skip hatch, force push or workflow edit. Existing route tests exercise local ASGI/fake dependencies; no live Firestore, installed backend, deployment, image build or production canary is claimed. Independent review and new-head GitHub CI are parent-owned, with no duplicate waiter/heartbeat started. ## Dated economic basis — ceiling only This is rank 2 / source 4 in the 2026-11-11 margin proposal, the largest additional eligible backend-invisible proposal after #25080's sync allowance repair lane. Conversation pagination needs client adoption; memory-history work needs its privacy failure gate. No overlapping credit is claimed. Recorded sampled caller pool: **20.278400M reads/day** for `utils.episodes.home_read:_read_members`, trailing 24h nominally ending **2026-11-10T22:33Z** (snapshot generated **22:35:59Z**). Recorded GMP query family: `topk(120, sum by (service_name, caller, collection, kind)(increase(omi_firestore_billed_reads_by_caller_total[24h])))`; select/sum this caller's rows. Source: workspace `data/run-2026-11-11-goals/margin-round4/firestore-measure-snapshot.json`, `deep-read-gmp.json` query strings and `deep-code-kimi-result.md`, source analysis pinned at `85de1985f0fb4fddd05e0de4b36c1ac68108d81e`; published KB `projects/admin-omi-tv-dashboard/evidence/2026-11-11-margin-unmeasured-programs.md`. Settled price basis is **2026-11-02..08**, Cloud Firestore Read Ops net **$4,054.076894 / 8,167.507724 read-M = $0.496366459757/read-M**, from recorded `firestore-read-cost-daily.json` billing-export aggregates. This gives only a **$0–$10.065518/day gross caller ceiling**. Corresponding closed Nov09 caller volume **17.134M / $8.505** is a different window and is not substituted into this estimate. These historical records were read locally; this task used no GCP tier and made no new cloud/vendor measurement. The eligible overlap is only the narrow **pre-fetch enrollment interval**, not broad concurrent misses or the duration of an in-flight RPC/preparation. Its share is even narrower and **UNMEASURED**, as is realized paid/free impact; **no expected saving and $0 booked**. Prometheus sampling, top-k omissions, retry/reset/scrape coverage, caller-vs-route attribution and mismatched native/billing windows limit the ceiling; the caller pool is not all avoidable. This does not include episode-window query reads, enable or alter the separate existing cache, imply a per-plan attribution join, or forecast savings. ## Dated readback PROPOSAL, not a serving ACK - **Baseline Nov11:** margin-lead / firestore-lead capture all-series member caller reads, `owner/coalesced/bypass/error` outcomes, episode-route 5xx and p95, and reads per successful episode completion (plus route-success denominators). Use matched windows and preserve coverage/overflow evidence. - **Target first full serving day Nov14:** only if ordinary lead2 review/release gates allow serving before Nov14 begins (by Nov13 23:59Z); otherwise use the next actual full serving day. No merge, deployment or activation is authorized by this PR or this date. - **Conditional D+2 Nov16:** margin-lead / firestore-lead reconcile the first full serving day's settled read-SKU export only after export completeness is established; shift the readback with the real serving day if later. Compare matched baseline per successful episode completion and route health, and distinguish fleet-wide SKU movement from this caller's measured reduction. Paid/free remains unmeasured until valid attribution exists. Keep $0 booked until correctness, serving identity/traffic and settled measurement prove a net impact. Implementation stops after the corrective normal push and metadata verification. Independent new-code review, new-head CI and ordinary lead2 release gates are parent-owned; no merge, deploy, activation or runtime acceptance is claimed. <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/BasedHardware/omi/pull/25086?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/25086?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F25086&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. --> Measurement ownership ACK (2026-11-11T01:47:56Z, coordkit bus `29da15`): firestore-lead owns the sync/episode readbacks, first full serving day Nov 14 / settled Nov 16 only if ordinary lead2 approval and serving allow it; otherwise D is the next full UTC serving day and readback D+2 after export completeness. This ACK does not authorize activation or deployment. Final source reviews on the earlier head `fb3bb9b83f5c9e3d5bc12302369e8e316a732074`: lead2-approved Sol privacy substitute PRE:CLEAN, then independent Luna privacy/erasure SHIP. Independent DeepSeek FINAL:CLEAN covers the earlier corrected source and its real-helper mutation regressions. These reviews cover the unchanged episode topic patch, not a claim of runtime acceptance or savings. Current PR head: `d4fab30d6726818c511346443f8cb052652aebb5`. Main was integrated after #25093 merged as `643c991a5544b6c0387f3dddd6f9b36cb9b51b54` and #25080 merged as `ad8fd1278eabb4eb1c0e4ee0aff31a150cb4ead1`, under lead2's local branch-refresh allowance. The normal push preserved the reviewed helper/test blobs and the normalized three-file topic patch. Focused tests: 22 passed through `omi-heavy`; normal hooks passed. Fresh exact-head CI is terminal green: **36 SUCCESS, 23 SKIPPED, zero pending/failed/cancelled** (backend run 42967827128); the formerly failing backfill file now has 101 passed / 1 skipped, with no guard or assertion change. Lead2 issued MERGE-OK at this head (bus d91753). Latest main #25065 also touches the helper outside the flight layer; that drift is disclosed for merge-desk's fresh-main and combined-tree checks. No merge, deploy, activation or settled saving is claimed here. Cost-change acceptance also requires accepted-result/output parity under the published quality guard (`omi-knowledge` commit `e450f118493bdc990c224ca018435a550c132ede`, `projects/omi-100m-plan/evidence/2026-11-11-quality-standing-guard.md`). Missing/stale/incomplete quality evidence is HOLD; transport success alone does not establish useful output. This proposal contributes $0 additional admitted savings to the ruling15 meter-basis path.
Cache-hit correctness is currently unobserved for monthly usage and episode members. Sample 1% of hits by default, reread durable state in a bounded background worker, and preserve the cached response and cache contents.
omi_read_cache_shadow_total{cache="usage_month"|"episode_members",result="match"|"mismatch"|"error"|"skipped"}distinguishes failed reads from incomplete/capacity-limited samples. Two workers, zero queue, and default rate0.01remain unchanged. Saturated submissions skip immediately without rejection warnings.monthly_usage_totals.FIELDSwithmath.isclose(rel_tol=1e-9, abs_tol=1e-6), tolerating accumulation-order rounding while detecting meaningful differences. The authoritative hourly query has an explicitlimit(744), a five-second RPC timeout, and no retries. Returning 744 documents conservatively countsskipped, even if that happened to be the complete month; a partial sum never becomes a mismatch.MEMBER_FIELDSpreparation retains extant rows, including deleted/discarded rows; display visibility is applied later. The shadow applies that same existence filter withfield_paths=[], returns IDs only, and never runs preparation, decryption, title projection, or transcript loads. Each batch uses the remaining five-second monotonic deadline and retries disabled; an expired deadline aborts rather than returning a partial key set. The normal serving preparation is unchanged.OMI_READ_CACHE_SHADOW_RATEis the only new control: missing means0.01, positive finite values clamp to1, and invalid strings, nonfinite values, and values <=0 silently skip with no metric. Rollback:OMI_READ_CACHE_SHADOW_RATE=0.mismatch; cheap write-timestamp attribution is unavailable, sostale_within_ttlis not guessed.Verified the original cache/TTL/phase metric implementations before coding at earlier head
35e63b5d701f94396cd166ef22db8df37aa947d4. Review baselineorigin/mainwas inspected at9fc3d64dc2e62c14acbfe4e77d33344cb13fdda0; its changes do not conflict with these paths. Published ancestry is preserved for a single normal fast-forward fix push.Added reads and attribution
The refreshed read-only
ro-prodGMP aggregate at 2026-11-10T19:03:16Z returned no 1-hour hit series for either requested cache. The earlier 24-hour aggregate at 17:15:06Z was also empty. Missing series are not zero hits, so no numeric estimate is claimed. This PR adds the missing episode-members hit counter. The application namespace is exposed asexported_namespacein GMP:Nominal fresh-read operations/hour =
r × (H_usage + H_members), or0.01 × (H_usage + H_members)by default; saturation reduces admissions. Billable document reads/hour =r × (H_usage × D_usage + H_members × D_members), where D includes empty/missing-document charges. Usage reads at most 744 documents per sampled hit, members at most 1000 unique requested IDs per eligible cache hit. The conservative document-read upper bound at default sampling is0.01 × (744 × H_usage + 1000 × H_members). A usage sample that reaches the cap still incurs its reads even though its comparison isskipped; a saturated sample incurs none.Both usage and member shadow reads run under
read_origin('job:read_cache_shadow')and the existing boundedrecord_firestore_readfamily. The SDK document probe records their billed reads under callersdatabase.user_usage:_fresh_month_statsandutils.episodes.home_read:_fetch_members, with distinct originjob:read_cache_shadow. The member origin is scoped to shadow RPC creation and iteration; the serving origin is preserved, including after failures. Tests exercise the real probe counters. Cost readback:Verification and review follow-up
Touched suites run through
/Users/david/workspace/omi-workspace/bin/omi-heavy:The full backend type check passed with 0 errors before the fix push.
Coverage includes the malformed rates
abc, empty string, and1%; real projection-cache values compared with hourly sums in a different floating-point summation order; 743/744/745-document bounds and skipped verdicts; actual per-caller/origin billed-read attribution; ID-only member reads matching real preparation for ordinary, deleted, discarded, and enhanced rows; no preparation on the shadow path; and silent skipped saturation. Existing match/mismatch/error/disabled and cached-response preservation tests remain.Conflict coordination: #24607 edits the same
home_read.pylines, including the member-reader rename/source-version changes. Whichever PR lands second rebases and reconciles that semantic overlap.Head SHA:
665b969d681e449ef4218c757d6c6dc1dee2d165. Review addressed against earlier head896b6950c6f76a8d5829f321b5f1619b73f97f4a.The final review fixes move all canonicalization, including member-key sorting, into the background worker. The worker retains the raw private cache snapshot: serving callers receive deep copies, so response mutation cannot alter it. Tests assert canonicalization has not run at submission, and verify response isolation plus shadow-only read-origin scoping on success and failure. Registry
fail: opennow matches the unset default (0.01, sampling on); the default and two-worker pool are unchanged.Local touched tests: 161 passed, 9 warnings in 4.18s; full preflight through
omi-heavy: 41 checks passed in 74.09s. Full backend type check: 0 errors. Current-head source CI completed without failures; every check is recorded below. No deployment is included. After deploy, verifysum by (cache,result) (increase(omi_read_cache_shadow_total[1h]))after eligible cache hits.CI readback
As of 2026-11-10T20:02:53.217295+00:00, for head
665b969d681e449ef4218c757d6c6dc1dee2d165: 37 passed, 22 skipped, 0 failed or pending. This body update triggers metadata-only validation, which is watched separately.Every reported CI check
Product invariants affected
none
Failure-Class: none
🤖 Generated with Claude Code