Skip to content

feat(firestore): batch-2 read levers — historical_scan_memo, ledger_purge_coalesce, people_scan_dedupe (default off) - #22019

Merged
Git-on-my-level merged 5 commits into
mainfrom
lane/firestore-reads-b2
Oct 17, 2026
Merged

Git-on-my-level merged 5 commits into
mainfrom
lane/firestore-reads-b2

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

Summary

Firestore reads loop, batch 2 (L4 amplifiers). Prod reads are ~900M/day, inflated by the #21883 backfill drain;
steady-state after the drain is expected near the pre-drain level. This PR adds three default-off levers
targeting the sync/backfill scan amplifiers identified in data/run-2026-10-16-firestore-reads/L4-batch2-triage.md,
all gated by the existing FIRESTORE_READ_LEVERS runtime_env key (no new config surface):

  • historical_scan_memo (≤32M reads/day predicted): task-attempt memo of identical
    (uid, order_field, query_spec, start_after, limit) historical memory scan pages in
    database/memories.py::_historical_scan_page — same task re-scanning the same bounded page pays the read cost once.
    FIFO + byte-bounded, per-attempt lifetime, every memory write in the module fences (clears before and after commit,
    including failures), budget accounting stays truthful (hits still charge check()).
  • ledger_purge_coalesce (≤22M/day): at the privacy-purge orchestrators
    (canonical_memory_adapter::purge_canonical_memory_projections, memory_service::retract_conversation_memories)
    defer redundant intermediate history walks for one task's memory-ID set and run ONE final fresh purge over the union.
    No scan caching: provider-absence proofs, legal-hold takeover checks, destructive-gate revalidation and retry receipts
    are preserved (review-verified with file:line evidence); the final fresh history walk always executes.
  • people_scan_dedupe (≤15M/day): task-attempt-scoped raw-projection memo in database/person_aliases.py::list_people,
    strictly opt-in (memoize=True) for audited read-only callers — none are wired in this PR (inert until an integrator
    lands), per the S6 constraint (no TTL/Redis/cross-task cache; authority/privacy/mutation-adjacent callers stay live;
    alias writes fence + invalidate; nested attempts isolate and invalidate ancestors).

Both memo scopes (historical_scan_memo_scope, people_scan_attempt) are context-manager constructs with no
production opener in this PR
— enabling the flag without opening a scope is a no-op, so this ships safe at any pct.

Product invariants affected

  • INV-MEM-1 — no new tier invented and no new collection created; the historical-scan memo caches pages of the
    existing memories/canonical reads within one task attempt and every write path fences it. Default off.
  • INV-MEM-3 — the universal memory authority path is unchanged; memoization only removes identical re-reads inside
    one task attempt (same uid, cursor, limit), never returns a historical row when the canonical check cannot run
    (budget-exhausted scans still raise; the final fresh purge always executes).
  • INV-MEM-4 — memory/sync read and purge paths change only how many reads run, behind default-off levers; no
    promotion, authority or mutation semantics change. ledger_purge_coalesce keeps the final fresh verification
    per user, legal-hold takeover, provider-absence proofs and retry receipts (review-confirmed).
  • INV-TASK-2 — no task creation/write behavior touched.
  • INV-DATA-1 — no data-plane or ownership change; no new runtime_env keys (levers already in KNOWN_LEVERS).

Test plan

  • New suites: test_fsr_historical_scan_memo.py (35 tests), test_fsr_ledger_purge_coalesce.py (26),
    test_fsr_people_scan_dedupe.py (26) — off-path identity (byte-for-byte query/purge/steam behavior), read-count
    proofs (e.g. 10 identical scans → 1; 4 history walks → 1 final walk; 2 identical list_people → 1 stream),
    mutation/uncertain-commit fences, legal-hold + takeover + receipts + final-fresh-purge safety.
  • All 87 pass locally via BACKEND_UNIT_TEST_FILE_LIST (test.sh runner), plus 72 behavior-preservation tests across
    the touched modules' existing suites (baseline memories, chat memory adapter, atomicity lifecycle, cascade
    retraction fence, person confidence/deserialize).
  • Independent review: zcode glm-5.3 — verdict SAFE on all three levers; the one failing test was a test-fake bug
    (lazy to_dict let a mid-stream write mutate an already-delivered snapshot; real Firestore snapshots are immutable),
    fixed by copying eagerly. Review-confirmed: final fresh purge, legal-hold takeover, provider-absence proofs, retry
    receipts preserved; purge ordering change is failure-safer (tombstones + receipts stay durable for retry).
  • Known residuals documented for the future scope integrator (review findings, unreachable today): entities.py:159
    writes memories outside database/memories.py (a historical-scan scope must never wrap KG subject reassignment);
    people writers outside person_aliases (speaker learning, users.py) mean a people scope may only wrap tasks that
    make no external people writes; deepcopy/pickle truncate DatetimeWithNanoseconds sub-µs precision (symmetric with
    the existing pipeline deepcopy; backend writers use µs precision).

Line-count exceptions

Line-Count-Exception: backend/database/memories.py | 1646 -> 1860 | task-attempt memo + write fences for historical scan pages (lever historical_scan_memo)
Line-Count-Exception: backend/database/person_aliases.py | 140 -> 285 | opt-in task-attempt memo with write fencing (lever people_scan_dedupe)
Line-Count-Exception: backend/utils/memory/canonical_memory_adapter.py | 4255 -> 4303 | purge deferral + single final fresh purge (lever ledger_purge_coalesce)
Line-Count-Exception: backend/utils/memory/memory_service.py | 4718 -> 4747 | retract purge sequencing coalesce (lever ledger_purge_coalesce)

Failure-Class: none

(fix-suffixed commit is a pre-merge typecheck hygiene fix, not a validated production failure.)

Rollout

  1. This PR deploys with all three levers at 0 (config unchanged; FIRESTORE_READ_LEVERS untouched).
  2. Separate config PR: 5% each, 3 h soak with verify.py guards on backend-sync/backend-sync-backfill.
  3. Readout via readout.py absolute caller reads vs baseline; then 100% for SUPPORTED levers.

View guided diff Turn on auto-fix

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 17, 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-17T11:56:42.541328Z f3b6986 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.

@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: f3b69866c4

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

Comment on lines +112 to +113
@contextmanager
def historical_scan_memo_scope(uid: str) -> Iterator[None]:

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 Badge Enter the historical memo scope in production tasks

Enabling historical_scan_memo cannot reduce any production reads because _active_historical_scan_memo() only returns a memo created by this context manager, but a repo-wide search shows historical_scan_memo_scope is used only by the new unit tests. The sync/backfill paths that call scan_memories_updated_at_page and scan_memories_created_at_page never enter the scope, so every scan still reaches Firestore; wire this scope around each task attempt.

Useful? React with 👍 / 👎.

Comment on lines +210 to +212
include_dismissed: bool = False,
limit: Optional[int] = None,
memoize: bool = False,

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 Badge Opt production People scans into the task memo

The people_scan_dedupe lever is inert in production: memo reuse requires both an active people_scan_attempt() and memoize=True, but neither appears outside the new tests, while the existing list_people callers retain the new False default. Consequently enabling the lever still streams the complete People collection on every call; the audited read-only task path must establish the scope and opt its duplicate calls into memoization.

Useful? React with 👍 / 👎.

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.

2 participants