Repository navigation
fix(memory): add default-off privacy reference index - #24857
Git-on-my-level wants to merge 9 commits into
Conversation
Maintain owner-scoped keyed reference tokens alongside ledger history writes. Gate token candidate queries behind MEMORY_PRIVACY_REFERENCE_INDEX=on while keeping the default exhaustive purge and its payload/authority checks. Historical backfill and cutover proof are a separate later PR. Failure-Class: FC-deadline-bounded-query-without-covering-index
Codex Review Summary: ✅ CompletedThis 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.
1 issue found across 19 files
Confidence score: 4/5
- In
memory_privacy_reference_index.py,privacy_reference_patchonly adds tokens, so changed values leave stale tokens behind and fresh lease/ack timestamps can make the array grow over time. Remove obsolete tokens or otherwise bound the array.
You’re at about 90% 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/database/memory_privacy_reference_index.py">
<violation number="1" location="backend/database/memory_privacy_reference_index.py:85">
P2: `privacy_reference_patch` uses `ArrayUnion` on every call, so tokens for changed string values are never removed. Vector-repair outbox patches carry fresh ISO timestamps on every lease and ack, so this array grows with each attempt. Consider bounding it, for example by recomputing the exact set in a full-document write where the document is already read.</violation>
</file>
Reply with feedback, questions, or to request a fix.
View guided diff | Turn on auto-fix | Re-trigger cubic
| Full replacements recompute the exact set. No extra document read is needed. | ||
| """ | ||
| tokens = with_privacy_reference_tokens(uid, patch)[PRIVACY_REFERENCE_TOKENS] | ||
| return {**patch, PRIVACY_REFERENCE_TOKENS: ArrayUnion(tokens)} if tokens else dict(patch) |
There was a problem hiding this comment.
P2: privacy_reference_patch uses ArrayUnion on every call, so tokens for changed string values are never removed. Vector-repair outbox patches carry fresh ISO timestamps on every lease and ack, so this array grows with each attempt. Consider bounding it, for example by recomputing the exact set in a full-document write where the document is already read.
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/memory_privacy_reference_index.py, line 85:
<comment>`privacy_reference_patch` uses `ArrayUnion` on every call, so tokens for changed string values are never removed. Vector-repair outbox patches carry fresh ISO timestamps on every lease and ack, so this array grows with each attempt. Consider bounding it, for example by recomputing the exact set in a full-document write where the document is already read.</comment>
<file context>
@@ -0,0 +1,85 @@
+ Full replacements recompute the exact set. No extra document read is needed.
+ """
+ tokens = with_privacy_reference_tokens(uid, patch)[PRIVACY_REFERENCE_TOKENS]
+ return {**patch, PRIVACY_REFERENCE_TOKENS: ArrayUnion(tokens)} if tokens else dict(patch)
</file context>
Brings the branch onto current main (fc68c80) without rewriting the reviewed commits. Resolves the driver-registry fingerprint conflicts and drops a duplicate privacy-query fingerprint key introduced by the rebase. Co-Authored-By: Claude Haiku 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_017CeWy3EF6Zh8RJRNEiFQEP
|
Cost check: extra token writes with Measured on: branch
Verdict: under the $5/day threshold by a wide margin. Since the bound is far below the threshold, the flag-off token writes do not need a gate. A measured row count from the counts-only read would turn this bound into a number. Generated by Claude Code |
Use the supported Firestore ArrayUnion re-export, distinguish terminal operation resources from memory_operations field URLs, and exercise the real retryable_failure outbox status in the token transition test. Failure-Class: none Co-Authored-By: Claude Opus 5.5 <[email protected]>
Carry the ACTION_ITEM_REFRESH_PRESERVE_ENABLED review-date ruling from upstream 9ac8cf0 into this older lane. David approved extending the review to December 8; retain the recorded ruling and regenerate the registry documentation. This clears the overdue review gate without changing runtime behavior. Failure-Class: none Co-Authored-By: Claude Opus 5.5 <[email protected]>
Skip lease/ack token unions while the reference index is off. Retain full-write tokens and require fenced backfill plus bounded enabled-mode patch history before cutover. Prove repeated off-mode leases and acks preserve token arrays, and wire SDK pagination and concurrent ArrayUnion proofs into the emulator harness. Failure-Class: none Co-Authored-By: Claude Opus 5.5 <[email protected]>
Summary repair currently walks the oldest debt in its bounded window
before recent user-visible debt. Apply David's 2026-11-10 03:19Z ruling
(`relay-cl1 6db8f2`): serve rows at risk of expiry first, then newest to
oldest.
## Behavior
- Scan the first 600 seconds above the age-gate cutoff oldest-first,
then the remaining window by pending time DESC, with due/path
tie-breaks. The margin spans five 120-second ticks: up to 40 attempts at
the default eight-attempt cap. This provides headroom, not an overload
guarantee.
- Share the scan/admission budgets across both phases, with independent
versioned cursors. Owner fairness allows at most three attempts per
owner per tick across both phases, including failed/blocked attempts.
Each durable phase cursor continues after every examined row, including
owner-quota deferrals, so later owners remain discoverable across ticks
even when one owner fills multiple scan budgets. Deferred rows are
retained separately as unchanged conversation debt (`summary_due_at`);
later passes/wraps select them again. Admission/time interruptions
preserve the unexamined fetched tail. Exhausted phases wrap as before,
with no additional retry queue or cursor schema. Legacy phase cursors
reset safely.
- With the age gate disabled, preserve the legacy `summary_due_at <=
now` query ordered by `(summary_due_at, __name__)` and its flat due/path
cursor. Rows with missing or explicitly null pending time remain
admissible, using their due time to bound admission pending time.
Gate-enabled cursors advance on finite numeric due values, including
zero/negative values; datetime handling is preserved.
- Fetch chunks of at most 500 rows. Stop starting work at the admission
cap, total scan budget, or a 90-second cooperative scan-work deadline
checked between rows/chunks; an in-flight RPC can finish later.
`scanned` includes the fetched-but-unexamined tail: it counts returned
document rows, not examined rows or admissions.
- If the newest query raises `FailedPrecondition` (including an
unavailable DESC index), emit
`event=summary_debt_repair_newest_index_unavailable outcome=error` once,
count one error, skip that phase and still finish the near-expiry cursor
and counters. No alternate query is used; other exceptions propagate. An
empty near-expiry page followed by a newest-phase precondition failure
still finishes the cursor lease and publishes all five counters with one
error. Pagination uses the last examined row directly and never indexes
an earlier phase’s page tail. Both sweep callers accept an older
tick-result shape without `near_expiry_admitted`.
No extra per-user ranking reads are added. Eligible rows have no
reliable denormalized Home-today or active-user rank, so that preference
is deferred. Existing lifecycle/local-only exclusions remain.
## Settings and capacity
Three startup settings are registered in the flag catalog and
deployment-setting classification:
| Setting | Default | Bounds |
|---|---:|---:|
| `SUMMARY_DEBT_REPAIR_ADMISSION_LIMIT` | 8 | 1..60 |
| `SUMMARY_DEBT_REPAIR_PER_OWNER_LIMIT` | 3 | 1..10 |
| `SUMMARY_DEBT_REPAIR_SCAN_LIMIT` | 100 | 1..5000 |
Invalid values restore defaults. At 120 seconds/tick there are 30
ticks/hour, so the admission-attempt ceiling is the per-tick limit x 30:
default 240/hour, maximum 1800/hour. Lead2 `8b9c8f` sets
prod/backend-integration to eight attempts/tick in the runtime overlay
and ops inputs; the runtime manifest is regenerated. No other service
receives an override. Lead2 `d233ac` also sets the code default/fallback
to eight. The owning capacity record
`/Users/dazheng/workspace/omi/data/run-2026-11-08-retro-fixnow/out-sd-capacity.md`
uses a $0.0054/repair mean: 8/tick = 5760/day = $31.104/day (~$31.1),
within David's $36 planning budget. This is the ruling's worst-case
full-admission estimate using a mean, not a hard dollar bound or a
billing measurement by this task. Production cap rollback is explicit 10
in both inputs followed by regeneration and an authorized deploy; unset
now restores default 8.
Owner `215fdc` raises the scan maximum to 5000 without changing default
100 or adding an overlay value. Full-utilization row-read arithmetic:
720 ticks/day x 100 rows = 72000 document reads/day per 100 rows/tick.
At 2800 rows: **2800 document reads/tick and 2016000/day**; at 5000:
3600000/day. These figures exclude retries, empty-query minimums,
index-entry charges, cursor transactions and admission/fence/outbox
reads. The supplied ~84k-row window (`refactor-lead a7dc6f`, original
measurement timestamp not supplied) implies an ideal ~28h pass at
100/tick and ~1h at 2800/tick. Strictly under one hour needs more than
2800 if 84k is exact, before admission/time stops and cursor rewinds. A
debt-only index/filter that skips refusals is the structural fix and is
out of scope.
## Index readiness and telemetry
Keep the ASC composite and add `(summary_first_pending_at DESC,
summary_due_at ASC, __name__ ASC)` for the conversations collection
group, with index/query-shape/driver registries and generated manifest
updated. **The new DESC index must be READY in the target project before
deploy**, through the existing provisioning/readiness lane. The
selective phase error handling preserves urgent progress but does not
remove this deployment prerequisite. No deploy, index apply, flag flip
or production access is performed here.
Keep expired_seen/overdue/oldest/sample gauges and add
`near_expiry_admitted` to tick/sweep counts plus its gauge.
`omi_summary_debt_repair_total{outcome}` accumulates exactly the
returned tick values for `scanned`, `admitted`, `error` (returned
`errors`), `expired_seen` and `near_expiry_admitted`. It increments once
after cursor completion, outside transactional callbacks; unclaimed
ticks and transaction retries do not duplicate increments. All metric
names/outcomes are declared and pinned in tests.
Post-deploy admissions readback:
`sum(rate(omi_summary_debt_repair_total{outcome="admitted"}[10m]))`,
alongside `near_expiry_admitted`, `error`, the serving release identity,
sample freshness and summary receipts. Admissions are redrives, not
completed summaries. No live backlog, throughput, index readiness or
vendor spend was measured by this task.
## Validation
Current fix verification runs on m1 through
`/Users/david/workspace/omi-workspace/bin/omi-heavy`, with file-isolated
unit processes and `BACKEND_UNIT_FILE_BUDGET_SECONDS=900`. Local
results: **2675 passed** across 12 targeted files (104 summary/age-gate,
1729 lifecycle inventory, 842 index/query guards; one test deselected by
the standard marker filter) at 2026-11-10T17:03:08+00:00; **225 passed**
across the repair-cap, production-policy and sweep-caller files at
2026-11-10T16:59:25+00:00; **49 passed** against the real loopback
Firestore emulator at 2026-11-10T17:02:41+00:00. `make preflight`: **51
checks passed** before the final hardening at 2026-11-10T17:00:13+00:00,
including the complete query-shape guard (560 passed). Final PR-body
preflight: **51 checks passed** against `1112536b8397` at
2026-11-10T17:05:26+00:00. Normal pre-push hooks remain enabled.
Detailed evidence is recorded in
`/Volumes/scratch/cl2-fixnow-push25019/out-25019-fix4.md` with
timestamps. CI after this push is the authority for the complete backend
suite.
Regressions cover three persistent failing urgent rows for A and more
than two scan budgets of A's newest rows before B; B must be discovered
within a bounded number of ticks. After the obstruction is removed,
every retained deferred row must be admitted across wrap. Both enabled
and disabled age-gate modes are covered. The index-failure regression is
parameterized over empty urgent and owner-deferred urgent pages. The
emitted version-2 phase cursors remain usable by existing phase readers;
cleared flat fields cause older enabled-gate readers to rewind, while
disabled-gate readers retain the compatible flat due/path continuation.
No lifecycle field, query shape, or cursor field is added, so the
existing inventory and query-driver declarations remain applicable.
Existing tests retain near-expiry priority, the shared owner cap of
three and admission cap of eight, scan/time limits, preservation of
fetched tails, lease fencing, `FailedPrecondition` completion and
counter publication.
## Merge order
**#25019 merges first. #25020 and #25021 rebase and regenerate after
it**, then rerun their summary/enrichment/sync suites. For overlapping
generated artifacts (also touched by #25018/#25012/#24731/#24857),
regenerate from the combined sources rather than hand-resolving output
ordering: runtime-env compose, Firestore index manifest and flag
registry, followed by exact-match guards. This PR performs no merge or
review request.
Rollback: revert this PR, leaving the additive index. Unset restores
admission 8 / owner 3 / scan 100; prior admission rollback is explicit
10. The cursor schema remains version 2. Existing phase readers continue
correctly; cleared flat fields make older code rewind safely with the
gate enabled; disabled-gate mode keeps its compatible flat due/path
cursor. Deferred conversation debt remains queryable after rollback.
## Product invariants affected
- INV-MEM-4 — the generated runtime-manifest diff adds only the summary
repair cap on prod/backend-integration. Canonical memory intake,
consolidation, promotion receipts and projection authority remain
unchanged.
Failure-Class: FC-bounded-discovery-pinned-by-blocked-page
Failure mechanism: repair order: oldest-first starves user-visible debt.
Line-Count-Exception: backend/database/firestore_index_registry.py |
2336 -> 2342 | Declare the additive newest-first repair composite beside
the existing ASC requirement.
Line-Count-Exception: backend/routers/sync.py | 3820 -> 3821 | Expose
near-expiry admission counts through the existing scheduled sweep
response.
Resolve the base conflicts the review flagged: keep main's flag-registry state (dropping the unrelated ACTION_ITEM_REFRESH_PRESERVE_ENABLED backport), keep both the new record-custody index requirement and the eight privacy reference-field requirements, and regenerate firestore.indexes.json from the registry. Declare MEMORY_PRIVACY_REFERENCE_INDEX in config/feature-flags.yaml (config_switch, default off, owner memory-ledger) and regenerate backend/docs/feature-flag-registry.md, so the kill switch is visible to the registry checker. Failure-Class: none
|
Closing under the approved stale PR disposition. There is no current owner or demonstrated need for this privacy reference index. Reopen with a privacy owner and evidence that current main needs the index. |
|
Hey @Git-on-my-level 👋 Thank you so much for taking the time to contribute to Omi! We truly appreciate you putting in the effort to submit this pull request. After careful review, we've decided not to merge this particular PR. Please don't take this personally — we genuinely try to merge as many contributions as possible, but sometimes we have to make tough calls based on:
Before your next PR, please skim:
If this was declined for direction or taste, maintainers should cite an invariant ID or open a proposed one — ask if that citation is missing. Your contribution is still valuable to us, and we'd love to see you contribute again in the future! If you'd like feedback on how to improve this PR or want to discuss alternative approaches, please don't hesitate to reach out. Thank you for being part of the Omi community! |
Requested by David · project thread
What changed and why
Privacy-history purges currently scan eight complete history collections within
users/{uid}. Persist storage-onlyprivacy_reference_tokens[]with active ledger writers and provide owner-local, paginatedarray_contains_anycandidate lookup. Tokens use HMAC-SHA256 with the existing serverENCRYPTION_SECRET, a versioned privacy-reference domain, and an unambiguous owner/string encoding. They cover every matching string leaf, plus daily-budget map keys. Commit identity, model payloads, and returned logical legacy commits stay unchanged.MEMORY_PRIVACY_REFERENCE_INDEXdefaults OFF. Only the explicit valueonselects indexed retrieval. Off retains the existing exhaustive name-ordered scans, page size, payload predicates, whole-document deletion, legal-hold checks, operation cascades, receipt ordering, provider-absence proof, and finalization. Creates/full replacements maintain tokens while the switch is off; incremental lease/ack patches skip token unions while off to prevent timestamp-driven array growth. Consequently these rows are incomplete for cutover and require the later fenced backfill. Missing/short keys preserve off-path writes with an empty token array and fail closed before indexed deletion when on; these rows are incomplete for cutover purposes.Creates/full replacements compute tokens alongside the payload in the same write. With the flag on, outbox lease/ack updates atomically union tokens for new string leaves without another read; stale tokens can only create extra candidates, since the existing logical-payload predicate still authorizes every deletion. The P2 follow-up takes the smallest approved option: skip these unions while off, preserving the original logical patch and preventing merge-time hot-row growth. Bounding enabled-mode patch history is a prerequisite to enabling in the backfill/cutover PR; this follow-up does not claim enabled-mode growth is bounded. Budget updates recompute tokens for remaining entries. No active backend writers exist for the three retired JIT collections; their retained rows require historical coverage.
The registry and generated
firestore.indexes.jsondeclare eight additive field overrides using the repository's existingFieldIndexRequirementreadiness primitive: each retains COLLECTION ASC/DESC/CONTAINS defaults and enables COLLECTION_GROUP CONTAINS. Runtime queries stay strictly underusers/{uid}; no collection-group queries are introduced. Query drivers exercise off/on shapes and operation-only cascades.The follow-up fix imports
document_id_from_seeddirectly from its definingdatabase.document_idsmodule inmodels/memories.py, removing the model dependency on the Firestore client/re-export. The frozen field-inventory fake now distinguishes the exact operation-resource path from thememory_operationsfield path. The reviewed-body fingerprint for_iter_privacy_history_candidatesis refreshed.Historical backfill is excluded and must be a separate PR. Do not enable this switch until that later work proves all retained rows complete under a writer-generation fence, retires old writers, verifies a consistent token key and index readiness, and establishes indexed/full-scan parity per owner. No coverage fence, backfill, runtime flip, GCP tier change, merge, or deploy is performed here. Lead2 ruling 6a2119 requires the flag to remain off at merge; cutover belongs to the backfill PR. Cost ruling b2f9a2 is closed by the accepted cost bound (no live row-count measurement is claimed). Query planning/READY state, retained coverage, writer/key consistency, concurrent writer/purge behavior, and size/headroom checks against the real service are deferred to that backfill PR; rollback is
MEMORY_PRIVACY_REFERENCE_INDEX=off.Product invariants affected
INV-MEM-1, INV-MEM-2, INV-MEM-4, INV-MEM-5 are preserved: storage metadata and gated candidate retrieval do not change memory authority, tiers, hydration, or ledger intent.
Follow-up verification (2026-11-09)
Commit
94a61f93e3cc9e8e25963f987f2224bf16c57054implements ruling 6a2119. Focused unit command (from backend):Result:
78 passed, 1 warning in 26.55s(audioop deprecation). The four new default/off × transactional/nontransactional cases each exercise 50 lease/ack cycles with advancing timestamps, worker IDs and errors while asserting the token array never grows.Focused proof through the existing Firebase emulator harness (from repository root):
env -u GOOGLE_APPLICATION_CREDENTIALS -u CLOUDSDK_CONFIG -u CLOUDSDK_CORE_ACCOUNT /Users/dazheng/workspace/omi/bin/omi-heavy run --wait 7200 -- firebase emulators:exec --only firestore --project demo-omi-isolated-tests 'backend/.venv/bin/python -m pytest -q -p no:cacheprovider backend/tests/integration/test_memory_privacy_reference_index_emulator.py'The test is wired into
backend/scripts/run-emulator-proofs.shso the existing emulator CI lane reruns it. These are SDK/emulator proofs only. No GCP tier or production account data was accessed. Real-service planning/READY, concurrency, coverage and headroom checks remain in the backfill PR. The flag remains default off; bounding enabled-mode patch history is also a cutover prerequisite.Follow-up CI (2026-11-09)
The single foreground push succeeded. All local pre-push gates passed: 42 shared preflight checks, the seven-file Firestore guard, backend type-checking (0 errors), the 14-file unit selection (one support module had no tests), OpenAPI compatibility/generation, and pinned formatting.
All nine reported checks are CodeQL checks for the exact head. GitHub still reports
CONFLICTING/DIRTY; backend unit shards/suite, emulator proofs and the other pull-request workflows have no checks on this head. Their CI acceptance remains unverified until the base conflicts are resolved and those workflows run. The local unit and emulator results above remain separate evidence. No merge or deployment was performed.How it was verified
Earlier verification (on
69f973916, before the rebase): the import-fix suite went from3 passed, 8 errorsto11 passed;test_memory_ledger.py31 passed;test_firestore_field_indexes.py42 passed; the full seven-file Firestore index guard842 passed. Live Firestore remains unverified: actual query planning and index READY state, retained-history coverage, cross-service writer/key consistency, concurrent writer/purge behavior, and document/index size headroom. No production account data or GCP tier was accessed.Tests
test_memory_privacy_reference_index.pyproves default/off full-scan behavior on unindexed history, on/off purge parity across all eight collections, operation cascades, owner isolation, payload rechecks for false-positive tokens, retained receipt ordering, bounded pagination, multi-chunk deduplication, domain/owner separation, budget-map keys, and unavailable-key handling. Existing ledger/apply/vector writer tests are retained unchanged; no skips or weakened assertions are added.UI evidence
UI-Evidence: none -- backend storage and query change.
Failure class (fixes)
Failure-Class: FC-deadline-bounded-query-without-covering-index
The owner-history lookup grows with unrelated retained rows in the request path. This instance adds a covering reference index and a gated lookup, with candidate parity tests; no new failure class is introduced.
Scoped file growth
Line-Count-Exception: backend/database/memory_apply_store.py | 2869 -> 2873 | Keep atomic token wrapping at the existing operation, commit, outbox and receipt write seams; the shared token implementation lives in memory_privacy_reference_index.py.
Line-Count-Exception: backend/database/firestore_index_registry.py | 2330 -> 2348 | Add the eight reference-field declarations in the required registry while keeping its generator unchanged.
🤖 Generated with Claude Code