Skip to content

perf: add default-off episode member read memo (episode_members_cache lever) - #24929

Merged
Git-on-my-level merged 1 commit into
mainfrom
lane/fsr-wq51-members-cache
Nov 8, 2026
Merged

Git-on-my-level merged 1 commit into
mainfrom
lane/fsr-wq51-members-cache

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

Default-off reads lever: episode_members_cache — 60s-TTL memo on episode member conversation batch reads in utils/episodes/home_read.py, registered in KNOWN_LEVERS at 0. No FIRESTORE_READ_LEVERS literal change (absent key = off everywhere), no deploy-file change, no query/read-path change on the off path.

Mechanics (review-verified): lever-off short-circuits before any lock or cache access, so off is main's exact code (off-path test pins exact get_all call-list and prepare order). Bounded memo: TTL exactly 60s with the deadline captured before the reads (late populations dropped), LRU 128 oldest-eviction, bypass above 1000 ids, key (uid, sorted-id-tuple), hits re-insert the original deadline (no renewal), deep copies in/out, errors propagate uncached with no stale serve. Concurrency locks cover only cache ops, never Firestore calls. Memo also covers the per-episode lookup caller at home_read.py:310 (in scope; attribution noted for rollout dashboards).

Review: full-diff zcode glm-5.3 r1 verdict SAFE, zero P1/P2 (exec-pet-flag-safe-observe-rude-blue); sol implementation exec-purpose-crucial-service-ancient-victory-fringe (477 tests, 36 preflight checks on the lane venv).

Product invariants affected

none

Verification

  • Focused: 147 passed on rebased head 4ae74f4 (test_episode_members_cache 15 + test_firestore_read_levers 41 + test_render_backend_runtime_env 91), lane venv.
  • Sol-side: 477 tests + 36 preflight checks (exec-purpose-crucial-service-ancient-victory-fringe); zcode r1 re-ran the three test files before verdict.
  • Rollout: code rides the Cloud Run backend train via the rollout lead (handoff posted on merge; this lane never dispatches deploys). The lever is dark until a separate config PR ramps it 0 -> 5 after serve + verify PASS (WQ51 remains open through ramp5 -> graded).

View guided diff Turn on auto-fix

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-08T14:45:47.509896Z 4ae74f4 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

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

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

3 issues found across 5 files

Confidence score: 3/5

  • In home_read.py, deep copies run under _members_cache_lock, so concurrent Home reads across users serialize on cache hits. Keep the lock limited to cache operations.
  • The home_read.py cache can retain and duplicate large inline photo payloads, but its limits count entries and IDs rather than memory. Keep bulky photo data out of the cache.
  • home_read.py reimplements BoundedTTLCache from database/privacy_ttl_cache.py, creating a second cache implementation to maintain. Reuse the existing cache.

You’re at about 98% of the monthly reviewed-line limit. You may want to disable incremental reviews to conserve quota. Reviews will continue until that limit is exceeded. If you need help avoiding interruptions, please contact [email protected].

Prompt for AI agents (unresolved issues)

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


<file name="backend/utils/episodes/home_read.py">

<violation number="1" location="backend/utils/episodes/home_read.py:129">
P3: This reimplements the existing `BoundedTTLCache` in `database/privacy_ttl_cache.py`, which already provides the TTL, LRU, lock, and start-time guard. Reuse it, e.g. `BoundedTTLCache(max_entries=MEMBERS_CACHE_MAX_ENTRIES)`, with `put(key, value, started=start)`. Otherwise the two copies can drift, for example in how errors or late fetches are handled.</violation>

<violation number="2" location="backend/utils/episodes/home_read.py:157">
P2: The deep copies run under `_members_cache_lock`, which contradicts the PR's claim that the lock covers only cache operations. Every concurrent Home read, across all users, serializes behind that copy. On a hit, copy `cached[1]` after releasing the lock. On a store, build the `deepcopy(result)` before acquiring the lock. The stored values are never mutated, so copying outside the lock is safe.</violation>

<violation number="3" location="backend/utils/episodes/home_read.py:174">
P2: The LRU can pin and duplicate inline photo payloads: `MEMBER_FIELDS` includes `photos`, whose entries can contain base64 data, while the cache is bounded only by 128 entries and 1,000 IDs per entry. Keep bulky photo data out of cached rows or enforce a byte budget to prevent worker memory pressure.</violation>
</file>

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

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

cached = _members_cache.pop(cache_key, None)
if cached is not None and time.monotonic() < cached[0]:
_members_cache[cache_key] = cached
return deepcopy(cached[1])

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2: The deep copies run under _members_cache_lock, which contradicts the PR's claim that the lock covers only cache operations. Every concurrent Home read, across all users, serializes behind that copy. On a hit, copy cached[1] after releasing the lock. On a store, build the deepcopy(result) before acquiring the lock. The stored values are never mutated, so copying outside the lock is safe.

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

<comment>The deep copies run under `_members_cache_lock`, which contradicts the PR's claim that the lock covers only cache operations. Every concurrent Home read, across all users, serializes behind that copy. On a hit, copy `cached[1]` after releasing the lock. On a store, build the `deepcopy(result)` before acquiring the lock. The stored values are never mutated, so copying outside the lock is safe.</comment>

<file context>
@@ -120,25 +123,59 @@ def wire_episode(episode: dict[str, Any] | None) -> dict[str, Any] | None:
+            cached = _members_cache.pop(cache_key, None)
+            if cached is not None and time.monotonic() < cached[0]:
+                _members_cache[cache_key] = cached
+                return deepcopy(cached[1])
     members: dict[str, dict[str, Any]] = {}
     for offset in range(0, len(ids), episodes.MEMBERSHIP_BATCH_LIMIT):
</file context>

# Count read/prepare latency against the TTL, so a slow fetch never
# publishes a snapshot older than the promised staleness window.
if time.monotonic() < cache_deadline:
_members_cache[cache_key] = (cache_deadline, deepcopy(result))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2: The LRU can pin and duplicate inline photo payloads: MEMBER_FIELDS includes photos, whose entries can contain base64 data, while the cache is bounded only by 128 entries and 1,000 IDs per entry. Keep bulky photo data out of cached rows or enforce a byte budget to prevent worker memory pressure.

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

<comment>The LRU can pin and duplicate inline photo payloads: `MEMBER_FIELDS` includes `photos`, whose entries can contain base64 data, while the cache is bounded only by 128 entries and 1,000 IDs per entry. Keep bulky photo data out of cached rows or enforce a byte budget to prevent worker memory pressure.</comment>

<file context>
@@ -120,25 +123,59 @@ def wire_episode(episode: dict[str, Any] | None) -> dict[str, Any] | None:
+            # Count read/prepare latency against the TTL, so a slow fetch never
+            # publishes a snapshot older than the promised staleness window.
+            if time.monotonic() < cache_deadline:
+                _members_cache[cache_key] = (cache_deadline, deepcopy(result))
+                _members_cache.move_to_end(cache_key)
+                while len(_members_cache) > MEMBERS_CACHE_MAX_ENTRIES:
</file context>

MEMBERS_CACHE_TTL_SECONDS = 60
MEMBERS_CACHE_MAX_ENTRIES = 128
MEMBERS_CACHE_MAX_IDS = 1000
_members_cache: OrderedDict[tuple[str, tuple[str, ...]], tuple[float, dict[str, dict[str, Any]]]] = OrderedDict()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3: This reimplements the existing BoundedTTLCache in database/privacy_ttl_cache.py, which already provides the TTL, LRU, lock, and start-time guard. Reuse it, e.g. BoundedTTLCache(max_entries=MEMBERS_CACHE_MAX_ENTRIES), with put(key, value, started=start). Otherwise the two copies can drift, for example in how errors or late fetches are handled.

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

<comment>This reimplements the existing `BoundedTTLCache` in `database/privacy_ttl_cache.py`, which already provides the TTL, LRU, lock, and start-time guard. Reuse it, e.g. `BoundedTTLCache(max_entries=MEMBERS_CACHE_MAX_ENTRIES)`, with `put(key, value, started=start)`. Otherwise the two copies can drift, for example in how errors or late fetches are handled.</comment>

<file context>
@@ -120,25 +123,59 @@ def wire_episode(episode: dict[str, Any] | None) -> dict[str, Any] | None:
+MEMBERS_CACHE_TTL_SECONDS = 60
+MEMBERS_CACHE_MAX_ENTRIES = 128
+MEMBERS_CACHE_MAX_IDS = 1000
+_members_cache: OrderedDict[tuple[str, tuple[str, ...]], tuple[float, dict[str, dict[str, Any]]]] = OrderedDict()
+_members_cache_lock = threading.Lock()
+
</file context>

@Git-on-my-level
Git-on-my-level merged commit feac121 into main Nov 8, 2026
62 of 64 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/fsr-wq51-members-cache branch November 8, 2026 14:58
Git-on-my-level added a commit that referenced this pull request Nov 11, 2026
## 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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant