Repository navigation
perf(batch): cut serving and ramp Firestore reads - #24577
Conversation
There was a problem hiding this comment.
6 issues found across 9 files
Confidence score: 3/5
- The exclusion memo described in
backend/docs/listen_pusher_pipeline/changes/2026-11-04-batch-firestore-reads.mdcan skip reevaluating a previously excluded owner’s new upload for 60 seconds. Bypass the memo for incoming audio, or document the intended behavior. - In
backend/utils/batch_pipeline/serving.py, the attempt closes beforereconcile_async’s fire-and-forget owner drains finish, so their transactions repeatedly do full privacy authority walks. Keep the attempt open until those drains complete. - In
backend/database/batch_ramp.py, read failures exclude the upload but aren’t memoized, so each partial-ramp admission during an outage repeats all three metadata reads. Memoize the failure outcome after the durable-owner check. - The handoff in
backend/docs/listen_pusher_pipeline/changes/2026-11-04-batch-firestore-reads.mdisn’t reproducible as written: its caller labels don’t match the exactmodule:functionnames, it references a metric or caller that isn’t emitted, andavo/firestore-reads/measure.pyis absent. Update it to use the actual callers and metrics and a tracked measurement tool.
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/docs/listen_pusher_pipeline/changes/2026-11-04-batch-firestore-reads.md">
<violation number="1" location="backend/docs/listen_pusher_pipeline/changes/2026-11-04-batch-firestore-reads.md:14">
P2: A memo hit bypasses `incoming_audio_seconds`, so a previously excluded owner’s new upload is not evaluated afresh during the 60-second TTL. Bypass the exclusion memo for incoming audio, or change this note to document the unavailable result.</violation>
<violation number="2" location="backend/docs/listen_pusher_pipeline/changes/2026-11-04-batch-firestore-reads.md:25">
P2: Use the exact `module:function` caller labels in the handoff: `database.batch_pipeline_privacy:read`, `database.batch_pipeline_store:oldest`, and `database.batch_ramp:read_owner_load`; otherwise the suggested rows will not match the emitted attribution data.</violation>
<violation number="3" location="backend/docs/listen_pusher_pipeline/changes/2026-11-04-batch-firestore-reads.md:27">
P2: This post-deploy command points to an untracked or absent `avo/firestore-reads/measure.py`, so the handoff cannot be reproduced from the repository. Reference a tracked measurement tool or document and provision the external tool path explicitly.</violation>
<violation number="4" location="backend/docs/listen_pusher_pipeline/changes/2026-11-04-batch-firestore-reads.md:29">
P2: No `batch_ramp:read_owner_load` metric or caller is emitted. Check `omi_batch_ramp_heavy_owner_excluded_total{reason}` during the partial ramp, or document the actual fully qualified billed-read caller.</violation>
</file>
<file name="backend/utils/batch_pipeline/serving.py">
<violation number="1" location="backend/utils/batch_pipeline/serving.py:113">
P2: This decorator closes the attempt before the fire-and-forget owner drains launched by `reconcile_async` run, so their transactions inherit a closed attempt and repeatedly perform full privacy authority walks instead of token-only reads. Give `OwnerDrains.run` its own privacy-attempt scope, or clear the inherited context when scheduling the drain.</violation>
</file>
<file name="backend/database/batch_ramp.py">
<violation number="1" location="backend/database/batch_ramp.py:83">
P2: Firestore read failures exclude the upload but never populate `_exclusions`, so an outage makes every partial-ramp admission repeat all three metadata reads. Memoize this read-failure outcome after durable-owner checks, or otherwise add an outage-specific read budget.</violation>
</file>
Reply with feedback, questions, or to request a fix.
View guided diff | Turn on auto-fix | Re-trigger cubic
| composed from the production overlay. | ||
|
|
||
| Handoff estimate: about 30–45M reads/day saved at current volume, mostly integration | ||
| `batch_pipeline_privacy:read` and `batch_pipeline_store:oldest`; excluded-owner memo |
There was a problem hiding this comment.
P2: Use the exact module:function caller labels in the handoff: database.batch_pipeline_privacy:read, database.batch_pipeline_store:oldest, and database.batch_ramp:read_owner_load; otherwise the suggested rows will not match the emitted attribution data.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/docs/listen_pusher_pipeline/changes/2026-11-04-batch-firestore-reads.md, line 25:
<comment>Use the exact `module:function` caller labels in the handoff: `database.batch_pipeline_privacy:read`, `database.batch_pipeline_store:oldest`, and `database.batch_ramp:read_owner_load`; otherwise the suggested rows will not match the emitted attribution data.</comment>
<file context>
@@ -0,0 +1,29 @@
+composed from the production overlay.
+
+Handoff estimate: about 30–45M reads/day saved at current volume, mostly integration
+`batch_pipeline_privacy:read` and `batch_pipeline_store:oldest`; excluded-owner memo
+savings apply only during partial ramps. After deployment, use
+`FSR_CALLER_WINDOW=1h python3 avo/firestore-reads/measure.py --hours 1` from the workspace with `ro-prod`, compare
</file context>
| savings apply only during partial ramps. After deployment, use | ||
| `FSR_CALLER_WINDOW=1h python3 avo/firestore-reads/measure.py --hours 1` from the workspace with `ro-prod`, compare | ||
| those service/caller rows over complete pre/post hours at similar batch throughput, | ||
| and check `batch_ramp:read_owner_load` on backend-sync during a partial ramp. |
There was a problem hiding this comment.
P2: No batch_ramp:read_owner_load metric or caller is emitted. Check omi_batch_ramp_heavy_owner_excluded_total{reason} during the partial ramp, or document the actual fully qualified billed-read caller.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/docs/listen_pusher_pipeline/changes/2026-11-04-batch-firestore-reads.md, line 29:
<comment>No `batch_ramp:read_owner_load` metric or caller is emitted. Check `omi_batch_ramp_heavy_owner_excluded_total{reason}` during the partial ramp, or document the actual fully qualified billed-read caller.</comment>
<file context>
@@ -0,0 +1,29 @@
+savings apply only during partial ramps. After deployment, use
+`FSR_CALLER_WINDOW=1h python3 avo/firestore-reads/measure.py --hours 1` from the workspace with `ro-prod`, compare
+those service/caller rows over complete pre/post hours at similar batch throughput,
+and check `batch_ramp:read_owner_load` on backend-sync during a partial ramp.
</file context>
| Handoff estimate: about 30–45M reads/day saved at current volume, mostly integration | ||
| `batch_pipeline_privacy:read` and `batch_pipeline_store:oldest`; excluded-owner memo | ||
| savings apply only during partial ramps. After deployment, use | ||
| `FSR_CALLER_WINDOW=1h python3 avo/firestore-reads/measure.py --hours 1` from the workspace with `ro-prod`, compare |
There was a problem hiding this comment.
P2: This post-deploy command points to an untracked or absent avo/firestore-reads/measure.py, so the handoff cannot be reproduced from the repository. Reference a tracked measurement tool or document and provision the external tool path explicitly.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/docs/listen_pusher_pipeline/changes/2026-11-04-batch-firestore-reads.md, line 27:
<comment>This post-deploy command points to an untracked or absent `avo/firestore-reads/measure.py`, so the handoff cannot be reproduced from the repository. Reference a tracked measurement tool or document and provision the external tool path explicitly.</comment>
<file context>
@@ -0,0 +1,29 @@
+Handoff estimate: about 30–45M reads/day saved at current volume, mostly integration
+`batch_pipeline_privacy:read` and `batch_pipeline_store:oldest`; excluded-owner memo
+savings apply only during partial ramps. After deployment, use
+`FSR_CALLER_WINDOW=1h python3 avo/firestore-reads/measure.py --hours 1` from the workspace with `ro-prod`, compare
+those service/caller rows over complete pre/post hours at similar batch throughput,
+and check `batch_ramp:read_owner_load` on backend-sync during a partial ramp.
</file context>
| Partial-ramp admission memoizes only owners already excluded by intrinsic load | ||
| or an uncertifiable/saturated snapshot, for 60 seconds (maximum 1,024 entries, | ||
| scoped by client, stage and owner). Hits return unavailable, never stale counts; | ||
| light owners and incoming audio always require fresh evaluation. A drained owner |
There was a problem hiding this comment.
P2: A memo hit bypasses incoming_audio_seconds, so a previously excluded owner’s new upload is not evaluated afresh during the 60-second TTL. Bypass the exclusion memo for incoming audio, or change this note to document the unavailable result.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/docs/listen_pusher_pipeline/changes/2026-11-04-batch-firestore-reads.md, line 14:
<comment>A memo hit bypasses `incoming_audio_seconds`, so a previously excluded owner’s new upload is not evaluated afresh during the 60-second TTL. Bypass the exclusion memo for incoming audio, or change this note to document the unavailable result.</comment>
<file context>
@@ -0,0 +1,29 @@
+Partial-ramp admission memoizes only owners already excluded by intrinsic load
+or an uncertifiable/saturated snapshot, for 60 seconds (maximum 1,024 entries,
+scoped by client, stage and owner). Hits return unavailable, never stale counts;
+light owners and incoming audio always require fresh evaluation. A drained owner
+can remain on legacy admission for at most 60 seconds. Existing durable ownership
+checks still precede load evaluation. This memo does nothing outside partial ramps
</file context>
| if self.merge.commit_next(owner_id, time.time(), release=release) is None: | ||
| break | ||
|
|
||
| @with_batch_privacy_attempt |
There was a problem hiding this comment.
P2: This decorator closes the attempt before the fire-and-forget owner drains launched by reconcile_async run, so their transactions inherit a closed attempt and repeatedly perform full privacy authority walks instead of token-only reads. Give OwnerDrains.run its own privacy-attempt scope, or clear the inherited context when scheduling the drain.
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/batch_pipeline/serving.py, line 113:
<comment>This decorator closes the attempt before the fire-and-forget owner drains launched by `reconcile_async` run, so their transactions inherit a closed attempt and repeatedly perform full privacy authority walks instead of token-only reads. Give `OwnerDrains.run` its own privacy-attempt scope, or clear the inherited context when scheduling the drain.</comment>
<file context>
@@ -109,6 +110,7 @@ def drain_owner(self, owner_id: str, *, recovered: str | None = None):
if self.merge.commit_next(owner_id, time.time(), release=release) is None:
break
+ @with_batch_privacy_attempt
async def reconcile_async(
self, *, recover_quarantine=False, periodic=False, owner_id=None, recovered=None, owner_only=False
</file context>
| job_rows = [row.to_dict() or {} for row in jobs] | ||
| # Incoming audio belongs to this request, not the owner. A single oversized | ||
| # upload must not suppress certification for subsequent small uploads. | ||
| if exclusion_reason(owner_load(job_rows, pending_rows, now)) is not None: |
There was a problem hiding this comment.
P2: Firestore read failures exclude the upload but never populate _exclusions, so an outage makes every partial-ramp admission repeat all three metadata reads. Memoize this read-failure outcome after durable-owner checks, or otherwise add an outage-specific read budget.
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/database/batch_ramp.py, line 83:
<comment>Firestore read failures exclude the upload but never populate `_exclusions`, so an outage makes every partial-ramp admission repeat all three metadata reads. Memoize this read-failure outcome after durable-owner checks, or otherwise add an outage-specific read budget.</comment>
<file context>
@@ -54,8 +77,17 @@ def read_owner_load(uid, *, firestore_client=None, now=None, incoming_audio_seco
+ job_rows = [row.to_dict() or {} for row in jobs]
+ # Incoming audio belongs to this request, not the owner. A single oversized
+ # upload must not suppress certification for subsequent small uploads.
+ if exclusion_reason(owner_load(job_rows, pending_rows, now)) is not None:
+ with _exclusions_lock:
+ _exclusions[key] = time.monotonic() + EXCLUSION_MEMO_SECONDS
</file context>
Failure-Class: none
Failure-Class: none
…atch # Conflicts: # backend/scripts/enrichment_recovery_emulator_test.py
|
episodes batch 1: ships together as one train, CI red |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
) <!-- claude-projects-attribution: {"github_login":"Git-on-my-level"} --> _Requested by **David**_ Batch captures previously stayed outside episodes until transcription finished. Audio close now attaches retained captures by committed audio bounds before queueing finalization, through the shared fenced recorded-time membership transaction. Arrival and processing clocks never select the episode or change its live pointer. The membership transaction stamps a fixed pending-transcription entry time and two-hour deadline. Replays preserve the deadline. Home shows “Transcribing…” while awaiting the durable batch projection; a dead letter, failed upload/status or elapsed deadline shows “Couldn't transcribe” with the committed audio finish time. A later successful projection restores ordinary member metadata. Audio and retry work remain retained. `EPISODE_BATCH_CLOSE_ATTACH_ENABLED` defaults on. Setting it to false/off/0/no restores attach-after-transcription. Episode/cohort, privacy, custom-STT, retention, lock, deletion and donor guards remain authoritative. Attachment adds no model calls and does not require a client-seen marker. Failure emits shared degraded-fallback telemetry and leaves finalization as the repair path. The overdue metric is an unlabeled read-observation counter; the info alert remains in the pending catalog, with no monitoring provisioning in this PR. Refreshed with merge commits through main `563e6c240944` (#24577, #24579, #24582/#24604 and subsequent main changes, including #24509). The resolution keeps batch 1's shared transaction/fence, attempt-local candidate reuse, current canonical partition proof, visibility validation, deduplicated memberships and recovery memo. Pending close writes its deadline inside that transaction without claiming/resetting completed transcript recovery. Close replay validates current committed archive bounds, normalized through the same datetime conversion used at admission, and is a true no-op with attach optimizations on or off. Changed bounds still update the episode without renewing the deadline. Composer settling, foreground promotion, Home read cuts and recording-speaker carry remain intact. The five original conflicts were in `episode_recorded_components.py`, `episode_timeline.py`, `service.py`, the Firestore query-driver registry and the generated feature-flag catalog. The sync callback and affected tests now use the public `attach_recorded` helper. The final speaker-tip merge was clean; the core episode resolution is unchanged. Validation at `817784dced26`: **858 passed across 21 focused backend files** through `backend/test.sh` with an explicit file list and four workers; **4 real Firestore emulator replay cases passed**, covering integer/fractional archive epochs and attach optimizations on/off. All tests/build gates run through `omi-heavy` at low priority, with no production credentials. Emulator limitation: the full 28-case episode suite alternated SDK transaction-lock timeouts between two old concurrency cases. Its last full run was **27 passed / 1 failed**, not all green. Both concurrency cases then passed together in a targeted run on exact main `cf601889c67b` and exact candidate `b8633977345c`. All 28 cases have passing candidate executions across full plus targeted runs; this does not establish a cause for the intermittent timeout. Core episode/emulator source is byte-identical after the final main merge, and the four new replay cases were rerun on the final head. Firestore clients now close at fixture teardown; test concurrency and transaction retry budgets are unchanged. Final hermetic e2e at `817784dced26`: **205 passed, 3 skipped, 2 xfailed in 101.14s**, within the unchanged **120s** limit. Native-library threads were capped at one; `--disable-warnings` suppressed only the console warning summary, without filtering warnings or changing warning assertions. Two earlier final-head attempts reached the wall limit (one at 100% test progress while rendering warnings). The lead authorized a documented 300s diagnostic if necessary, but it was **not used**. Committed and remote-CI budgets remain 120s. `make preflight` passed **43/43** before the final clean main merge; the normal push hook runs the final required gates again. Failure-Class: FC-finalize-hook-allowlist-omits-ingestion-path Product invariants: INV-MEM-4 and INV-TASK-2. Canonical episode ownership and task/enrichment authority remain unchanged. No PR merge, deploy, production account access or GCP calls. GCP tier: none. No rebase, force-push, workflow additions or firmware edits. The lead owns merge and the backend/listen release train. UI-Evidence: none -- backend response projection; related mobile fixture evidence belongs to #24541.
Requested by David
Serving commits repeat a full Firestore privacy walk even within one reconciliation pass. Give reconciliation, each recording-drain tick, and each projection follow-up the existing bounded privacy attempt: the first authorization per client/owner/source-ID set walks authority, and subsequent transactions read only the token. Every transaction still enrolls that read in its conflict set; token changes and server revisions force live revalidation.
Partial-ramp admission now memoizes only already-excluded or uncertifiable owners for 60 seconds, capped at 1,024 entries and isolated by client/stage/uid. Hits decline certification without returning stale counts and use the existing
load_unavailableexclusion reason. Light owners are always reread, incoming audio is evaluated afresh, and saturated reads still cannot certify a light owner. A drained owner may remain on legacy admission for up to 60 seconds; prior durable ownership still wins.Set prod backend-integration and the batch-pipeline worker's serving metrics minimum refresh to 60 seconds (previously the 30-second code default), below the guard's 120-second blind window. Bind the worker chart explicitly in both contract environments: prod 60 seconds and dev 30 seconds, matching their serving hosts. Regenerate the runtime manifest and feature-flag registry; both remain unchanged after the main merge.
Failure-Class: none
Product invariants affected
Validation
Follow-up validation through
omi-heavyafter merging main1ee787ba63c4:python -m pytest tests/unit/test_cross_service_deploy_contract.py -q: 23 passed, 3 skipped (optional historical replays); dev/prod worker Helm rendering is exercised.bash backend/scripts/pre-deploy-check.sh: 357 passed, plus 36 source-admission tests; dev/prod runtime env validation passed.make preflight: 43 checks passed; the final normal pre-push gate also passed all 43 selected checks.scripts/pr-preflight --metadata-only --pr-body-file ...: 4 checks passed.lane/fsbatchpassed every pre-push gate on24e740e574ebd3323d8f10fda9e25bcbac3695cd, including backend typecheck (0 errors), all 43 preflight checks, the two changed unit-test files (65 passed), runtime-env checks, and pinned formatting.Prior implementation validation recorded before this follow-up: five targeted backend suites 185 passed (
test_batch_ramp,test_bpp_generation_memo,test_batch_pipeline_serving,test_batch_pipeline_projection_followup,test_batch_pipeline_metrics); loopback Firestore privacy-fence emulator 49 passed, then shut down cleanly. The follow-up changes only the worker chart and merges current main. The upstream enrichment proof clock-stub repair is retained exactly from main.Expected saving and post-deploy verification
The 2026-11-04 cost handoff estimates about 30–45M fewer reads/day, roughly $20–25/day at current volume. The privacy attempt is the main saving; doubling the serving metrics interval halves those refresh walks. Owner-load savings apply during partial ramps (no additional saving at the current 100% ramp). These are estimates, not deployed measurements.
After deployment, from the Omi workspace:
Sum all collection/kind rows per service and caller in
origins.top_1h, comparing similar batch completion volume:batch_pipeline_privacy:readandbatch_pipeline_store:oldeston backend-integration; alsobatch_ramp:read_owner_loadon backend-sync during a partial ramp. Checkorigins.windowis1h(the script otherwise defaults caller rows to 3h despite thereads_1hfield name), service coverage remains complete, and privacy denials/serving freshness remain healthy. Multiply the comparable hourly read reduction by 24 for reads/day. Observe after the new release fully serves and has a full measurement window; do not count a missing service/caller series as a saving.No production reads or writes were needed for this PR. No PR merge or deployment performed.
🤖 Generated with Claude Code