Repository navigation
feat(firestore): batch-2 read levers — historical_scan_memo, ledger_purge_coalesce, people_scan_dedupe (default off) - #22019
Conversation
…ger_purge_coalesce, people_scan_dedupe)
…urge_coalesce, people_scan_dedupe (default off)
…st_people memoize as shape-neutral
…memo, public defer contextmanager
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. |
There was a problem hiding this comment.
💡 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".
| @contextmanager | ||
| def historical_scan_memo_scope(uid: str) -> Iterator[None]: |
There was a problem hiding this comment.
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 👍 / 👎.
| include_dismissed: bool = False, | ||
| limit: Optional[int] = None, | ||
| memoize: bool = False, |
There was a problem hiding this comment.
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 👍 / 👎.
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_LEVERSruntime_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 indatabase/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 indatabase/person_aliases.py::list_people,strictly opt-in (
memoize=True) for audited read-only callers — none are wired in this PR (inert until an integratorlands), 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 noproduction 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
existing
memories/canonical reads within one task attempt and every write path fences it. Default off.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).
promotion, authority or mutation semantics change.
ledger_purge_coalescekeeps the final fresh verificationper user, legal-hold takeover, provider-absence proofs and retry receipts (review-confirmed).
KNOWN_LEVERS).Test plan
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-countproofs (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.
BACKEND_UNIT_TEST_FILE_LIST(test.sh runner), plus 72 behavior-preservation tests acrossthe touched modules' existing suites (baseline memories, chat memory adapter, atomicity lifecycle, cascade
retraction fence, person confidence/deserialize).
(lazy
to_dictlet 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).
entities.py:159writes 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 thatmake no external people writes; deepcopy/pickle truncate
DatetimeWithNanosecondssub-µs precision (symmetric withthe 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
FIRESTORE_READ_LEVERSuntouched).verify.pyguards on backend-sync/backend-sync-backfill.readout.pyabsolute caller reads vs baseline; then 100% for SUPPORTED levers.