Skip to content

perf(backend): memoize batch privacy authorities within one transaction behind default-off lever (fsr WQ12) - #23072

Merged
Git-on-my-level merged 1 commit into
mainfrom
lane/firestore-reads-wq12-privacy
Oct 21, 2026
Merged

Git-on-my-level merged 1 commit into
mainfrom
lane/firestore-reads-wq12-privacy

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Oct 21, 2026 •

Copy link
Copy Markdown
Member

Summary

WQ12 of the firestore-reads loop: assert_batch_write_allowed costs 3 + 2D document reads per assertion and callers repeat the same authorities within one transaction (explicit body checks, flush dedupe, projection prepare/validate). Fleet origin cluster ~125-135M reads/day measured 1hx24 (snapshot 2026-10-21T05:01:28Z, origins.top_1h, backend-sync + backend-sync-backfill) - the largest origin cluster not yet owned by a lever.

New default-off lever batch_privacy_memoize (registered in KNOWN_LEVERS, backend/config/firestore_read_levers.py; absent key = 0):

  • BatchPrivacyMemo (backend/database/batch_pipeline_privacy.py) reuses successful document snapshots - including absence - by full path, bound to one client + transaction; mismatches are rejected, read errors never cached.
  • FirestoreTransaction.check_privacy creates the memo per enabled uid; flush shares it within the same transaction view; projection session shares prepare/plan snapshots and resets on every prepare attempt.
  • Scope is one transaction callback attempt: the first real get of every distinct authority still occurs in the mutating Firestore transaction, so there is no TTL, no cross-transaction staleness window, and no way for a later transaction to inherit an earlier allow decision. Deletion/generation fences, redirect walks, cycle detection and the 256-document budget are unchanged.
  • Lever off = byte-identical reads in original order; no memo allocated, no middleware/ContextVar/FastAPI-teardown changes (2026-10-16 desktop-backend bug class avoided).

Measured hermetic caller counts (WQ12-sol-privacy-report.md, not fleet telemetry): real admit() 20 segments 100 -> 43 privacy reads (-57%); transaction-view body+flush 200 -> 43; single-source flush 105 -> 5. Production mix share unknown until served - daily saving recorded as unknown in the work queue until the readout.

This PR does NOT change any FIRESTORE_READ_LEVERS value; enablement is a follow-up config PR after serve + ramp per the loop runbook.

Product invariants affected

  • INV-DATA-1 - no routing, ownership or retention change; memo reuses snapshots within the same transaction that mutates the same documents, and fence evaluation order/reasons are preserved.
  • INV-MEM-4-equivalent for batch pipeline: off-path behavior is byte-identical to main (asserted by read-count and parity tests).

Test plan

  • New backend/tests/unit/test_fsr_wq12_batch_privacy.py: 43 tests (read counts on real admission fixture, stored-payload parity, denial parity, memo isolation, Aborted-retry reread/deny, walk budget, failure paths).
  • Regression suites re-run green in separate pytest processes: batch_privacy_conversation_fence 15, firestore_read_levers 9, batch_pipeline_scheduler 42, projection 45, intake 44, shadow 26 (224 focused total); test_firestore_query_shapes.py 495 passed.
  • Staged formatting + git diff --check clean.

Rollout

  1. Default-off; no prod env change in this PR.
  2. Enablement config PR later via set_levers.py (complete literal), train order listen -> pusher -> Cloud Run, coordinated with the two-lane lead via bus handoff.
  3. Review chain: zcode glm-5.3 full-diff review before merge; verdict + exec id recorded in the loop work queue.

View guided diff Turn on auto-fix

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 21, 2026 •

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-21T21:10:53.102134Z 574fee3 New commits
ℹ️ 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.

@Git-on-my-level

Copy link
Copy Markdown
Member Author

Review (zcode glm-5.3, direct run, 2026-10-21T17:10Z): VERDICT: SAFE

All five verification items confirmed with file:line evidence; 67 focused + 157 regression tests re-run green by the reviewer; Aborted-retry reread/deny spot-check holds. Two minors (unreachable cross-client reference robustness nit; report preflight-promise doc nit) — no code change required. Reviewer output: loop state rev-wq12-r1.json; sessionId sess_7026de51. Note: agentctl zcode delegations for this loop failed twice today with native_execution_failed (exec-inherit-head-area-captain-raise-jacket, exec-split-match-run-oval-usual-close), so the review ran zcode directly in the lane worktree.

…on behind default-off lever

WQ12 lever `batch_privacy_memoize` (KNOWN_LEVERS, absent key = 0): a successful
assert_batch_write_allowed performs 3 + 2D document reads and callers repeat the
same authorities within one transaction (body checks, flush dedupe, projection
prepare/validate). BatchPrivacyMemo reuses successful snapshots per transaction
callback attempt only - the first real get of every distinct authority still
occurs in the mutating transaction, so no cross-transaction staleness window and
no TTL. Lever off = byte-identical reads. Measured hermetic admission fixture:
100 -> 43 privacy reads for a 20-segment admit (report: WQ12-sol-privacy-report.md;
224 focused + 495 query-shape tests pass).

No FIRESTORE_READ_LEVERS value changed; enablement is a later config PR per the
firestore-reads loop runbook.
@Git-on-my-level
Git-on-my-level force-pushed the lane/firestore-reads-wq12-privacy branch from 00c1574 to 574fee3 Compare October 21, 2026 21:02

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 574fee30b6

ℹ️ 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".

db.rows[change] = {'generation': 1} if change[0] == 'batch_pipeline_privacy' else {}
raise Aborted('concurrent privacy mutation')

monkeypatch.setattr(transaction, '_commit', commit)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Add emulator coverage for retry-scoped privacy memos

When memoization is enabled and a concurrent privacy mutation aborts the transaction, correctness depends on every retried callback discarding its previous snapshots. This test instead mutates the fake's in-memory rows and monkeypatches _commit to raise Aborted; StrictFirestore deliberately does not model server contention or retry semantics, so it cannot validate the production safety guarantee. Cover this case with the Firestore emulator as required for retry/contention behavior.

AGENTS.md reference: backend/AGENTS.md:L225-L225

Useful? React with 👍 / 👎.

@Git-on-my-level
Git-on-my-level merged commit d90643d into main Oct 21, 2026
63 of 67 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/firestore-reads-wq12-privacy branch October 21, 2026 21:40
Git-on-my-level added a commit that referenced this pull request Oct 25, 2026
#23554)

## Summary

Config-only: enable `batch_privacy_memoize` at 5% in the prod
`FIRESTORE_READ_LEVERS` literal. All 16 existing keys are byte-identical
to the served literal on backend-02109-qzv; the only delta is the added
`"batch_privacy_memoize":5`.

Behavior code already merged and served via #23072 (merge d90643d,
ancestor of the serving release; memoized per-job privacy assertion).
The lever key is in main `KNOWN_LEVERS` (firestore_read_levers.py:46).
The lever has been dark at 0 since then; this PR makes it addressable at
the cautious first ramp step.

Caller pool being addressed (loop snapshot
baseline-2026-10-24T09-45Z-pre-bpm.json, 1h caller window, window_end
2026-10-24T08Z): `database.batch_pipeline_privacy:read` ~3.36M reads/h
across backend-sync + backend-sync-backfill (not_found storms on `other`
+ lookups on users/conversations) ≈ 81M/day at 1hx24 — the top measured
origin. Expected saving is unknown until the ramp readout; predicted
50M/day is the caller-pool hypothesis registered in the loop ledger, not
a measurement.

## Product invariants affected

- INV-FSR-LEVERS — lever percentage changes only via this literal;
absent keys remain 0/off; REPLACE-mode literal kept complete (17 keys)
at all sites.
- INV-READ-BUDGET — at 5% cohort the memoized path serves most per-write
privacy reads from the per-job memo; off-cohort behavior is
byte-identical to today.
- INV-MEM-4 — required citation: this PR touches the locked
runtime_env/charts path family this invariant guards. It changes only a
Firestore read-lever percentage (read-path memoization of an existing
per-write privacy assertion); it adds no promotion route, fast-track
pass, or canonical-lineage change.

## Verification

- Literal consistency: all 54 literal occurrences under backend/ parsed
and compared; every deployed-literal site (runtime_env/_base.yaml x12,
rendered runtime_env.yaml x24, 4 listen/pusher chart values, flag
registry, both pinned contract tests) equals the exact 17-key target;
the 10 partial literals in test_fsr_s5_action_items.py are intentional
single-lever fixtures, unchanged.
- Contract tests: `backend/.venv/bin/python -m pytest
backend/tests/unit/test_render_backend_runtime_env.py
backend/tests/unit/test_verify_pusher_config_references.py -q` → 121
passed.
- Loop-side pre-enable baseline pinned (post-code-serve, pre-enable):
baseline-2026-10-24T09-45Z-pre-bpm.json, coverage 0.685,
missing_services [].
- No GCP write tier used; measurement used the read-only prod tier.

UI-Evidence: none — backend config only, no UI change.

Failure-Class: none

## Rollout and rollback

Rollout: loop-owned lever config at 5%, then per the loop runbook ramp
rule (verify PASS x2 ticks after 3h → 100% candidate; grades on absolute
caller reads vs the pinned baseline). Deploy train order remains listen
→ pusher → Cloud Run (rollout lead owns the train). Rollback: revert
this commit (or a follow-up config PR setting the key to 0), then the
same train.
tivince82 pushed a commit to tivince82/omi that referenced this pull request Oct 25, 2026
…>17 keys)

Top measured origin database.batch_pipeline_privacy:read ~3.36M reads/h
(~81M/day 1hx24, loop baseline-2026-10-24T09-45Z-pre-bpm.json, window_end
2026-10-24T08Z) storms per-write privacy reads on backend-sync/backfill.
Memoize code served since d90643d (BasedHardware#23072); key already in KNOWN_LEVERS.
All other 16 keys byte-identical to the served literal. Contract tests 121
pass; literal consistency checked at all 54 backend sites.
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