Skip to content

feat(privacy): measure session checks and shadow token-validated reuse - #24402

Merged
Git-on-my-level merged 15 commits into
mainfrom
lane/ic-privacy
Nov 2, 2026
Merged

Git-on-my-level merged 15 commits into
mainfrom
lane/ic-privacy

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Nov 2, 2026 •

Copy link
Copy Markdown
Member

What changed and why

Add measurement and after-live shadow comparisons for repeated privacy checks,
plus default-off token-validated batch/session/negative reuse. Count checks,
allow/block reasons, point reads, conversation walks and completed 60-second
listen/pusher intervals. Labels and sampled mismatch logs contain no identifiers.

Build on the writer-generation fence now merged in #23894: cover speaker-only
consent changes and flattened BatchWrite arguments, reject implicit authority
state loss before any RPC, and validate tokens against server revisions. Keep
its shared authority-field export, unchanged-field suppression, write-budget
reservation and regression coverage. Cache hints re-read durable authority on
every decision; Redis invalidation alone never authorizes a negative.

Transactional external fences and full-row snapshot consumers remain live.
Nontransactional provider-STT retains the admission-write deferral from
1219b0e. No query/list or memory tombstone changes, deletion TTL increase,
workflow change, deployment or flag flip.

Product invariants affected

No locked catalog paths are intentionally changed. Preserve account/data-plane
authority, absent-cloud-consent-means-enabled, and transactional conflict sets.

Line-Count-Exception: backend/routers/listen/runtime.py | 1505 -> 1509 | Attach census to the existing runtime and offload its two bounded lifecycle operations; implementation stays in its own module.
Line-Count-Exception: backend/routers/pusher.py | 1891 -> 1893 | Import and apply session scope at the existing websocket entry; implementation stays in its own module.
Line-Count-Exception: backend/utils/sync/pipeline.py | 3965 -> 3967 | Scope the shared coordinator entry so inline and Cloud Tasks jobs both participate in shadow; the attempt implementation stays in its own module.

Verification and review status

Tree: lane/ic-privacy, head de85db4 (integration 32b42d0 plus follow-ups). All tests use omi-heavy and
nice -n 19. backend/test.sh with targeted file list: 571 passed across writer,
memo, privacy-contract, legal hold, tombstone, cache and listen regressions.
Real loopback Firestore matrix: 49 passed, including all writer families,
mixed atomic/bulk state-loss refusal, stale purge finish and subtree erasure.
Full hermetic listen/sync harness at the default 120s budget: 185 passed,
3 skipped, 2 expected failures
. Emulator listener cleanup verified.

Earlier local runs hit 120s, and one diagnostic 300s run had a CancelledError at
the unchanged reconnect test's context exit before timeout. Its isolated default
rerun and subsequent full runs passed. All failed receipts are retained; no
checked-in timeout or skip changed. Integration also preserved every main-only
test added by #23894. At integration 32b42d0, function/class ASTs across 10 privacy
modules matched reviewed e962; two only added the shared constant/alias from main.
The later follow-up changes counters and attempt entry scope, not live authority
decisions or token validation.

Luna rounds 1/2 found authority loss and a missing pusher census; corrected.
Lead approval ee01ec authorized one final delta review of e962. Round 3 returned
FIX-FIRST for a hypothetical raw purging=false update outside the canonical
generation-checked finish API. Rebuttal: the only production purging=false write
is inside transactional finish_privacy_purge, which compares generations; the
real-emulator stale-finish test confirms an older finish cannot reopen a newer
purge. An explicit raw authority change rotates the token and affects live policy
identically with caching off; no stale memo survives it. The token hook does not
decide whether a caller completed cleanup. Lead ruling 3c079e accepted that
scope rebuttal and authorized marking ready after exact-head CI is green. The
formal Luna round-three verdict remains FIX-FIRST; it is not relabeled SHIP.
Boundary for future changes: writes to generation/blocked/purging must stay
inside the canonical generation-checked transactional authority APIs; any new
raw-SDK state writer requires a fresh privacy review and ownership regression.
Final-head backend CI is required after conflict repair; security-only checks on
the conflicted e962 head are not that evidence.

Cubic follow-up closes inline sync attempt coverage and counts cached deletion
calls/decisions plus the artifact protection read. Targeted 198 tests and full
default-budget hermetic harness (185 passed, 3 skipped, 2 expected failures) pass.
Live decision/token validation logic is unchanged. The runbook now names the
exact mismatch metric, the combined session lever's two-family baseline and
rollback, transactional read boundaries and reproducible verification commands.
Its fixed managed 30-second ceiling needs no runtime TTL knob. P3 lazy import
cleanup and the pre-existing serial bulk Commit performance risk are tracked for
infracost by 2026-11-03T12:00Z; measure bulk latency/contention before all-plane
writer qualification, preserving per-item source/token atomicity and partial
failure semantics. Pusher census was already fixed and tested in round 1.
The pusher ticker now uses the WS-scoped task helper, interruptible stop event,
bounded drain and fixed-message failure reporting. Its first complete interval
includes setup; listen resets after bootstrap, so each has its own baseline.
The backwards-clock regression is valid: subtracting two seconds from now changes
age from threshold+1 to threshold-1. Shadow's extra live artifact protection read
is deliberate and metered; infracost must include it in shadow economics.

No GCP access, production account data or live vector/backfill operations.

Default-off ramp and deployment order

Owner: infracost; the rollout lead merges/deploys. Deploy listen → pusher →
Cloud Run serving writers
(backend, sync, backfill, desktop and other writers)
→ jobs/operator producers. Qualify this final writer implementation everywhere,
including speaker-only consent and flattened bulk coverage; #23894 alone is not
the complete writer qualification. No new reader lever is enabled by this PR.

Record each slice's own pre-ramp baseline. Enable privacy_checks_shadow across
all planes for at least 14 days, with zero unexplained privacy_decision_mismatch_total,
actual eligible hits, no unresolved shadow errors and the scope's 30% repeat-key
hit-rate bar. Infracost owns expansion and the first enforcement decision is due
14 days after shadow reaches all planes.

After qualification, remove shadow before ramping bpp_generation_memo,
legal_hold_fence_cache, and tombstone_negative_cache separately to
5% → PASS on two ticks → 100%, against that slice's own baseline.
privacy_session_token enables both external-fence and tombstone candidates in a
session, even with the family levers off; grade it against both baselines and
coverage, and roll it back on either family's regression.
Shadow wins if both modes are present. Any unexplained mismatch
blocks expansion. Rollback: new shadow/enforcement levers off restores the original
live read sequence; mandatory writer tokens remain.

The scope's $45–58/day is an estimate, not measured savings. Warm external
fences may replace two authority reads with one token read; tombstones still pay
a token read and cold candidates add reads. Do not book the original slice 3
savings. Include token writes/contention and vendor spend in the net readout.
Redis-only zero-read reuse is excluded; strict writer fencing is a separate
proposal requiring fault-injection evidence and measured/explicitly estimated
savings. Details: backend/docs/runbooks/privacy-check-shadow.md.

Tracking: https://anx.scalingforever.com/o/david-zhang/w/omi/r/card:session-privacy-counters-writer-tokens

UI evidence

UI-Evidence: none -- backend privacy checks only.

Failure class

Failure-Class: none

Install atomic writer invalidation independently of the privacy epoch, measure
live checks and listen intervals, and compare candidate decisions after live
authority without changing the result. All enforcement levers default off.

Keep transaction and full-snapshot authority reads live. Validate the durable
token on every new cached decision, including session reuse, per infracost
ruling 93d4a1; do not authorize from Redis invalidation alone.
Normalize flattened BatchWrite request fields before classification so those
writers cannot bypass token preparation. Cover sync and async surfaces and
clarify shadow qualification requires eligible cache hits and no unresolved
candidate errors.
Use closed caller labels around measured privacy reads so counters do not
move the existing Firestore baseline into an instrumentation helper bucket.
Retain the legacy transaction snapshot-memo caller separately and verify
the labels through actual authority and tombstone paths.
Keep the SDK callback-retry regression explicit and also exercise the current
fresh-transaction contention budget. Verify each retry re-reads the changed
privacy token and rejects concurrent deletion before a second commit.
Do not memoize an allow from a stale running deletion gate: wall time can move
backwards and change that verdict without a writer-token movement. Cache only
timeless clears and test both Redis and session reuse across a clock reversal.
Assert email, UID-shaped token and conversation-id components individually,
including the sampled-log state, so a partial disclosure fails the test too.
Allow decision-only artifact callbacks to compare the candidate with only the
shadow lever enabled. Keep exported full-row snapshots live and continue
reading the protection context from durable authority in both cases.
…undary

Reset and publish the session census through the existing context-propagating
database executor rather than taking its cross-thread lock on the event loop.

@cubic-dev-ai cubic-dev-ai 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.

4 issues found across 25 files

Confidence score: 3/5

  • backend/database/batch_privacy_write_fence.py makes each authority write in a bulk request a separate serial Commit RPC, which can add hundreds of round trips and cause timeouts on large writes. Batch compatible writes into bounded groups.
  • backend/docs/runbooks/privacy-check-shadow.md makes a blanket claim that doesn’t hold for transactional legal-hold fences: external_write_fence authorizes from live-account and gate reads without reading batch_pipeline_privacy into the transaction. Clarify the runbook’s scope.
  • backend/database/fsr_read_cache.py adds TTL controls that managed deployments can’t configure because they’re missing from the runtime-env allowlist and generated manifests; those deployments stay at the 30-second fallback. Add both names to the allowlist and manifests.
  • backend/database/privacy_negative_cache.py defers internal imports inside _candidate, causing import lookups on every candidate call and diverging from the backend import convention. Move them to module scope.
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/fsr_read_cache.py">

<violation number="1" location="backend/database/fsr_read_cache.py:169">
P2: These new TTL controls are not part of the runtime-env allowlist or generated manifests, so managed deployments cannot configure them and silently remain at the 30-second fallback. Add both names to the runtime-env source/allowlist and regenerate the manifests, or remove the environment lookup if 30 seconds is intentionally fixed.</violation>
</file>

<file name="backend/database/privacy_negative_cache.py">

<violation number="1" location="backend/database/privacy_negative_cache.py:16">
P3: Move these internal imports to module scope. Keeping them inside `_candidate` makes every candidate call perform deferred import lookups and violates the backend import convention.</violation>
</file>

<file name="backend/docs/runbooks/privacy-check-shadow.md">

<violation number="1" location="backend/docs/runbooks/privacy-check-shadow.md:38">
P2: This blanket claim is false for transactional legal-hold fences: `external_write_fence` intentionally authorizes from the live account and gate reads without reading `batch_pipeline_privacy` into the transaction conflict set. Qualify the statement to cached-decision transactions so the runbook does not promise a concurrency guarantee this path does not provide.</violation>
</file>

<file name="backend/database/batch_privacy_write_fence.py">

<violation number="1" location="backend/database/batch_privacy_write_fence.py:207">
P2: This turns each authority write in a bulk request into a separate serial Commit RPC. Large BatchWrite/BulkWriter calls can therefore incur hundreds of round trips and timeouts; group compatible writes into bounded atomic commits or use bounded concurrent dispatch while preserving each source/token pairing.</violation>
</file>

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

# These are correctness limits, not merely tunable defaults.
_CACHE_TTLS = {
'deletion_marker_cache': ('FSR_DELETION_NEGATIVE_TTL_SECONDS', 30),
'legal_hold_fence_cache': ('FSR_LEGAL_HOLD_NEGATIVE_TTL_SECONDS', 30),

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: These new TTL controls are not part of the runtime-env allowlist or generated manifests, so managed deployments cannot configure them and silently remain at the 30-second fallback. Add both names to the runtime-env source/allowlist and regenerate the manifests, or remove the environment lookup if 30 seconds is intentionally fixed.

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/fsr_read_cache.py, line 169:

<comment>These new TTL controls are not part of the runtime-env allowlist or generated manifests, so managed deployments cannot configure them and silently remain at the 30-second fallback. Add both names to the runtime-env source/allowlist and regenerate the manifests, or remove the environment lookup if 30 seconds is intentionally fixed.</comment>

<file context>
@@ -166,6 +166,8 @@ def forget_request_reads(uid):
 # These are correctness limits, not merely tunable defaults.
 _CACHE_TTLS = {
     'deletion_marker_cache': ('FSR_DELETION_NEGATIVE_TTL_SECONDS', 30),
+    'legal_hold_fence_cache': ('FSR_LEGAL_HOLD_NEGATIVE_TTL_SECONDS', 30),
+    'tombstone_negative_cache': ('FSR_TOMBSTONE_NEGATIVE_TTL_SECONDS', 30),
     'subscription_cache': ('FSR_SUBSCRIPTION_TTL_SECONDS', 60),
</file context>

Comment thread backend/routers/sync.py Resolved
leave the original live result/exception intact.

Batch memo entries belong to one sync/pump attempt and close on every exit.
Every authorizing transaction reads the token in its conflict set. Existing

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: This blanket claim is false for transactional legal-hold fences: external_write_fence intentionally authorizes from the live account and gate reads without reading batch_pipeline_privacy into the transaction conflict set. Qualify the statement to cached-decision transactions so the runbook does not promise a concurrency guarantee this path does not provide.

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/runbooks/privacy-check-shadow.md, line 38:

<comment>This blanket claim is false for transactional legal-hold fences: `external_write_fence` intentionally authorizes from the live account and gate reads without reading `batch_pipeline_privacy` into the transaction conflict set. Qualify the statement to cached-decision transactions so the runbook does not promise a concurrency guarantee this path does not provide.</comment>

<file context>
@@ -0,0 +1,137 @@
+leave the original live result/exception intact.
+
+Batch memo entries belong to one sync/pump attempt and close on every exit.
+Every authorizing transaction reads the token in its conflict set. Existing
+transactional legal-hold fences retain both live authority reads. Nontransactional
+provider-STT checks remain live (the deferred admission-write fix in
</file context>
Suggested change
Every authorizing transaction reads the token in its conflict set. Existing
Every cached-decision authorizing transaction reads the token in its conflict set.

# than silently lose a caller's billing attribution.
raise ValueError('labeled batch privacy bulk writes require atomic Commit migration')
individual = {}
for i in indices:

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: This turns each authority write in a bulk request into a separate serial Commit RPC. Large BatchWrite/BulkWriter calls can therefore incur hundreds of round trips and timeouts; group compatible writes into bounded atomic commits or use bounded concurrent dispatch while preserving each source/token pairing.

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_privacy_write_fence.py, line 207:

<comment>This turns each authority write in a bulk request into a separate serial Commit RPC. Large BatchWrite/BulkWriter calls can therefore incur hundreds of round trips and timeouts; group compatible writes into bounded atomic commits or use bounded concurrent dispatch while preserving each source/token pairing.</comment>

<file context>
@@ -0,0 +1,252 @@
+                # than silently lose a caller's billing attribution.
+                raise ValueError('labeled batch privacy bulk writes require atomic Commit migration')
+            individual = {}
+            for i in indices:
+                try:
+                    response = await client.commit(
</file context>



def _candidate(family, uid, client, variant, live, cache_family, *, shadow, reuse_allowed):
from database.batch_pipeline_privacy import PRIVACY_COLLECTION, privacy_owner_key

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3: Move these internal imports to module scope. Keeping them inside _candidate makes every candidate call perform deferred import lookups and violates the backend import convention.

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/privacy_negative_cache.py, line 16:

<comment>Move these internal imports to module scope. Keeping them inside `_candidate` makes every candidate call perform deferred import lookups and violates the backend import convention.</comment>

<file context>
@@ -0,0 +1,114 @@
+
+
+def _candidate(family, uid, client, variant, live, cache_family, *, shadow, reuse_allowed):
+    from database.batch_pipeline_privacy import PRIVACY_COLLECTION, privacy_owner_key
+    from database.fsr_read_cache import cached_read, plane_id
+
</file context>

@Git-on-my-level
Git-on-my-level marked this pull request as draft November 2, 2026 16:28
@Git-on-my-level
Git-on-my-level marked this pull request as ready for review November 2, 2026 19:12
@Git-on-my-level
Git-on-my-level marked this pull request as draft November 2, 2026 19:16

@cubic-dev-ai cubic-dev-ai 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.

5 issues found across 20 files

Confidence score: 3/5

  • test_privacy_shadow_and_session.py cannot reach the expected exception because moving the clock backward makes the gate even staler. Start just inside the stale threshold and observe the transition.
  • The session-cycle metric in privacy-check-shadow.md can include setup checks because the pusher census does not reset after bootstrap. Reset the census at the end of bootstrap.
  • retention.py duplicates the live users/{uid} read for no-snapshot authorization when shadow checks are enabled. Reuse the live snapshot for the shadow candidate.
  • test_bpp_generation_memo.py duplicates the focused retry tests, adding test time and maintenance without new coverage. Keep one set of retry tests.
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/runbooks/privacy-check-shadow.md">

<violation number="1" location="backend/docs/runbooks/privacy-check-shadow.md:83">
P2: The session-cycle metric is not consistently measured after bootstrap: pusher census starts at decorator entry and never resets after bootstrap, so its first interval can include setup checks. Either reset the pusher census at the completed bootstrap boundary or document that the metric has different lifecycle semantics for pusher and listen.</violation>
</file>

<file name="backend/tests/unit/test_bpp_generation_memo.py">

<violation number="1" location="backend/tests/unit/test_bpp_generation_memo.py:488">
P3: This newly added parametrized test duplicates both focused retry tests above, increasing test time and leaving three copies to maintain when retry behavior changes. Remove the redundant parametrized test or keep only the focused cases.</violation>
</file>

<file name="backend/tests/unit/test_privacy_shadow_and_session.py">

<violation number="1" location="backend/tests/unit/test_privacy_shadow_and_session.py:187">
P2: This test cannot reach the expected exception: moving the clock backward makes the already-stale gate even older, so `_gate_blocks` continues allowing it. Initialize the gate just inside the stale threshold and observe it from just after the threshold before moving the clock backward across that boundary.</violation>
</file>

<file name="backend/utils/batch_pipeline/retention.py">

<violation number="1" location="backend/utils/batch_pipeline/retention.py:464">
P2: Enabling `privacy_checks_shadow` now duplicates the live `users/{uid}` read on every no-snapshot artifact authorization. Preserve the live user snapshot while still running the shadow candidate, so shadow adds only its intended reads and the point-read baseline remains accurate.</violation>
</file>

<file name="backend/database/privacy_check_metrics.py">

<violation number="1" location="backend/database/privacy_check_metrics.py:224">
P3: Move this executor import to module scope; deferring it until the first pusher session violates the backend import contract and delays import failures until live traffic reaches the ticker.</violation>
</file>

Requires human review: Auto-approval blocked because this review re-detected 1 unresolved issue already reported by Cubic.

View guided diff | Turn on auto-fix | Re-trigger cubic

| `privacy_checks_total{family,mode,reason}` | Allow/block/error decisions |
| `privacy_check_reads_total{family,mode,result}` | Issued point reads, hit/miss/error |
| `privacy_conversations_walked_total{mode}` | Distinct conversation nodes walked per check |
| `privacy_session_cycle_operations{plane,family,mode,kind}` | Listen census over each completed 60-second interval after bootstrap |

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: The session-cycle metric is not consistently measured after bootstrap: pusher census starts at decorator entry and never resets after bootstrap, so its first interval can include setup checks. Either reset the pusher census at the completed bootstrap boundary or document that the metric has different lifecycle semantics for pusher and listen.

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/runbooks/privacy-check-shadow.md, line 83:

<comment>The session-cycle metric is not consistently measured after bootstrap: pusher census starts at decorator entry and never resets after bootstrap, so its first interval can include setup checks. Either reset the pusher census at the completed bootstrap boundary or document that the metric has different lifecycle semantics for pusher and listen.</comment>

<file context>
@@ -0,0 +1,144 @@
+| `privacy_checks_total{family,mode,reason}` | Allow/block/error decisions |
+| `privacy_check_reads_total{family,mode,result}` | Issued point reads, hit/miss/error |
+| `privacy_conversations_walked_total{mode}` | Distinct conversation nodes walked per check |
+| `privacy_session_cycle_operations{plane,family,mode,kind}` | Listen census over each completed 60-second interval after bootstrap |
+| `privacy_shadow_checks_total{family,result}` | Match/mismatch/error denominator |
+| `privacy_memo_requests_total{family,result}` | Hit/miss/ineligible repeat-key denominator |
</file context>
Suggested change
| `privacy_session_cycle_operations{plane,family,mode,kind}` | Listen census over each completed 60-second interval after bootstrap |
| `privacy_session_cycle_operations{plane,family,mode,kind}` | Session census over each completed 60-second interval; listen resets after bootstrap, while pusher starts at handler entry |

@metrics.with_session_census('listen')
async def exercise():
assert await run_blocking(db_executor, external, db)
clock[0] -= timedelta(seconds=2)

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: This test cannot reach the expected exception: moving the clock backward makes the already-stale gate even older, so _gate_blocks continues allowing it. Initialize the gate just inside the stale threshold and observe it from just after the threshold before moving the clock backward across that boundary.

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/tests/unit/test_privacy_shadow_and_session.py, line 187:

<comment>This test cannot reach the expected exception: moving the clock backward makes the already-stale gate even older, so `_gate_blocks` continues allowing it. Initialize the gate just inside the stale threshold and observe it from just after the threshold before moving the clock backward across that boundary.</comment>

<file context>
@@ -0,0 +1,319 @@
+    @metrics.with_session_census('listen')
+    async def exercise():
+        assert await run_blocking(db_executor, external, db)
+        clock[0] -= timedelta(seconds=2)
+        with pytest.raises(legal_holds.DestructiveOperationInProgress):
+            await run_blocking(db_executor, external, db)
</file context>

and current_attempt() is not None
and (
lever_enabled('bpp_generation_memo', item.owner_id)
or lever_enabled('privacy_checks_shadow', item.owner_id)

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: Enabling privacy_checks_shadow now duplicates the live users/{uid} read on every no-snapshot artifact authorization. Preserve the live user snapshot while still running the shadow candidate, so shadow adds only its intended reads and the point-read baseline remains accurate.

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/retention.py, line 464:

<comment>Enabling `privacy_checks_shadow` now duplicates the live `users/{uid}` read on every no-snapshot artifact authorization. Preserve the live user snapshot while still running the shadow candidate, so shadow adds only its intended reads and the point-read baseline remains accurate.</comment>

<file context>
@@ -457,7 +457,12 @@ def authorize(transaction):
+            and current_attempt() is not None
+            and (
+                lever_enabled('bpp_generation_memo', item.owner_id)
+                or lever_enabled('privacy_checks_shadow', item.owner_id)
+            )
         )
</file context>

check(db)


@pytest.mark.parametrize('outer_retry', [False, True])

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3: This newly added parametrized test duplicates both focused retry tests above, increasing test time and leaving three copies to maintain when retry behavior changes. Remove the redundant parametrized test or keep only the focused cases.

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/tests/unit/test_bpp_generation_memo.py, line 488:

<comment>This newly added parametrized test duplicates both focused retry tests above, increasing test time and leaving three copies to maintain when retry behavior changes. Remove the redundant parametrized test or keep only the focused cases.</comment>

<file context>
@@ -424,3 +440,75 @@ def test_actual_artifact_authorize_path_read_counts_and_exact_off_order(monkeypa
+            check(db)
+
+
[email protected]('outer_retry', [False, True])
+def test_real_store_transaction_retries_revalidate_token_and_deny(monkeypatch, reads, outer_retry):
+    enabled(monkeypatch)
</file context>



async def _pusher_census_ticks(holder):
from utils.executors import db_executor, run_blocking

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3: Move this executor import to module scope; deferring it until the first pusher session violates the backend import contract and delays import failures until live traffic reaches the ticker.

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/privacy_check_metrics.py, line 224:

<comment>Move this executor import to module scope; deferring it until the first pusher session violates the backend import contract and delays import failures until live traffic reaches the ticker.</comment>

<file context>
@@ -0,0 +1,261 @@
+
+
+async def _pusher_census_ticks(holder):
+    from utils.executors import db_executor, run_blocking
+
+    while True:
</file context>

Scope inline sync attempts before the first await and count cached deletion
decisions separately from issued reads. Include the artifact protection read
in batch telemetry and clarify the session lever's combined rollout criteria.

Failure-Class: none
Use the scoped task helpers and an interruptible stop event. Report ticker
failures without exception text and retain bounded cleanup on socket exit.
Clarify the different listen and pusher census bootstrap boundaries.

Failure-Class: none
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Addressed the two automatic reviews (5739452348 at f00ac24 and 5742048964 at 32b42d0) in the follow-up through de85db4:

  • Inline sync now enters the privacy-attempt scope at the shared coordinator, before its first await. Real-coordinator tests cover both inline and Cloud Tasks cancellation and restore the parent scope.
  • Deletion calls/decisions are counted outside Redis/request dedupe; issued reads stay in the fetch callback. Six cached/deduplicated calls correctly produce six decisions and one read. Artifact authorization's extra live protection read also uses the telemetry wrapper, with counted-versus-issued-read assertions.
  • The runbook distinguishes unchanged live legal-hold transaction reads from batch memo token reads, documents the session lever's combined external/tombstone scope and rollback, uses privacy_decision_mismatch_total, and supplies concrete test/emulator commands.
  • Pusher census flushing was fixed earlier. It now also uses the scoped task helper, interruptible event wait, bounded drain and fixed-message failure reporting. Tests cover normal ticks, socket cancellation and ticker failure without ending a healthy socket. The runbook states pusher starts at websocket entry (including setup), while listen resets after bootstrap; each plane has its own baseline.

Rebuttals/boundaries:

  • Managed negative-cache TTL is intentionally capped at 30 seconds. These are not promised deployment tuning controls; local overrides can only shorten the cap. Rollouts use the declared levers. No runtime TTL allowlist entry is needed to use the approved ceiling.
  • The clock regression is valid: _gate_blocks compares now - started_at < threshold. Initial age is threshold+1; moving now back 2 seconds makes it threshold-1, which blocks. Both real-helper variants pass; the review's age direction is reversed.
  • Shadow's additional live artifact protection read is deliberate. The decision-only check exports no snapshots; the caller still needs live protection metadata. Reusing candidate snapshots for live metadata would break the after-live shadow boundary. This read is now fully metered and must be included in shadow economics; it is not booked as a saving.

Tracked follow-ups, owner infracost, next 2026-11-03T12:00Z on the lane card:

  • Measure serial bulk authority Commit latency and per-owner contention before all-plane writer qualification. The serial loop already exists on main via feat(batch): writer-generation fence + attempt-authorization memo for batch_pipeline_privacy (firestore-reads WQ26) #23894. Any bounded concurrency/batching optimization needs to preserve per-item source/token atomicity, CAS and BatchWrite partial-failure/status semantics; naive grouping would change that contract.
  • P3 lazy import cleanup (including avoiding eager executor initialization for all privacy readers) and consolidation of duplicate retry tests, retaining both SDK-inner and store-outer retry coverage.

Latest follow-up verification: 198 targeted unit tests and the full default-budget hermetic harness (185 passed, 3 skipped, 2 expected failures). Authority/token/cache logic remains unchanged from the 49-case emulator-tested integration. Formal Luna R3 remains FIX-FIRST with the source-supported scope rebuttal accepted by lead ruling 3c079e, as recorded in the PR body; no fourth Luna review was launched. Final exact-head CI remains the readiness gate. No merge, deploy, runtime flag flip or production data access in this lane.

@Git-on-my-level
Git-on-my-level marked this pull request as ready for review November 2, 2026 19:54

@cubic-dev-ai cubic-dev-ai 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.

3 issues found across 23 files

Confidence score: 4/5

  • In privacy-check-shadow.md, a fresh worktree won’t have the Firebase CLI after make setup, so the writer-matrix command can’t run as documented. Add the pinned CLI installation step.
  • The commands in privacy-check-shadow.md use bare omi-heavy, but the runbook only identifies bin/omi-heavy and doesn’t set PATH. Use the workspace-qualified executable consistently.
  • test_privacy_shadow_and_session.py keeps imports inside a function, which conflicts with the repository’s top-level import convention. Move them to module scope.
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/tests/unit/test_privacy_shadow_and_session.py">

<violation number="1" location="backend/tests/unit/test_privacy_shadow_and_session.py:72">
P3: Move the function-local imports to the module scope. This repository requires top-level imports, and keeping them local makes the test’s dependencies harder to audit and maintain.</violation>
</file>

<file name="backend/docs/runbooks/privacy-check-shadow.md">

<violation number="1" location="backend/docs/runbooks/privacy-check-shadow.md:163">
P2: These verification commands use bare `omi-heavy`, but the runbook identifies the workspace executable as `bin/omi-heavy` and does not establish a PATH entry. Use the workspace-qualified executable consistently in all three commands so the documented checks can actually run.</violation>

<violation number="2" location="backend/docs/runbooks/privacy-check-shadow.md:168">
P2: `make setup` does not install the Firebase CLI, so this prerequisite statement leaves the writer-matrix command unavailable on a fresh worktree. Document the actual pinned CLI installation/setup step, or state that it must be installed separately.</violation>
</file>

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

`omi-heavy run -- nice -n 19 bash backend/testing/e2e/run.sh`; retain its default
timeout and do not supply cloud credentials.

For the writer matrix, `make setup` supplies the pinned Firebase CLI. Start its

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: make setup does not install the Firebase CLI, so this prerequisite statement leaves the writer-matrix command unavailable on a fresh worktree. Document the actual pinned CLI installation/setup step, or state that it must be installed separately.

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/runbooks/privacy-check-shadow.md, line 168:

<comment>`make setup` does not install the Firebase CLI, so this prerequisite statement leaves the writer-matrix command unavailable on a fresh worktree. Document the actual pinned CLI installation/setup step, or state that it must be installed separately.</comment>

<file context>
@@ -0,0 +1,176 @@
+`omi-heavy run -- nice -n 19 bash backend/testing/e2e/run.sh`; retain its default
+timeout and do not supply cloud credentials.
+
+For the writer matrix, `make setup` supplies the pinned Firebase CLI. Start its
+Firestore emulator with a scratch Firebase config on loopback and a `demo-`
+project, then invoke the same `backend/test.sh` contract with
</file context>

`tests/unit/test_batch_pipeline_privacy.py`, `tests/unit/test_fsr_wq12_batch_privacy.py`,
`tests/unit/test_legal_holds.py`, `tests/unit/test_conversation_tombstones.py`,
and `tests/unit/test_fsr_s4_caches.py`. Run
`omi-heavy run -- nice -n 19 env BACKEND_UNIT_TEST_FILE_LIST=<scratch-list> BACKEND_PYTEST_WORKERS=1 bash backend/test.sh`.

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: These verification commands use bare omi-heavy, but the runbook identifies the workspace executable as bin/omi-heavy and does not establish a PATH entry. Use the workspace-qualified executable consistently in all three commands so the documented checks can actually run.

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/runbooks/privacy-check-shadow.md, line 163:

<comment>These verification commands use bare `omi-heavy`, but the runbook identifies the workspace executable as `bin/omi-heavy` and does not establish a PATH entry. Use the workspace-qualified executable consistently in all three commands so the documented checks can actually run.</comment>

<file context>
@@ -0,0 +1,176 @@
+`tests/unit/test_batch_pipeline_privacy.py`, `tests/unit/test_fsr_wq12_batch_privacy.py`,
+`tests/unit/test_legal_holds.py`, `tests/unit/test_conversation_tombstones.py`,
+and `tests/unit/test_fsr_s4_caches.py`. Run
+`omi-heavy run -- nice -n 19 env BACKEND_UNIT_TEST_FILE_LIST=<scratch-list> BACKEND_PYTEST_WORKERS=1 bash backend/test.sh`.
+Run the full hermetic harness with
+`omi-heavy run -- nice -n 19 bash backend/testing/e2e/run.sh`; retain its default
</file context>



def test_instrumentation_preserves_closed_historical_sdk_caller_labels(world, monkeypatch):
from database import firestore_document_probe as probe

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3: Move the function-local imports to the module scope. This repository requires top-level imports, and keeping them local makes the test’s dependencies harder to audit and maintain.

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/tests/unit/test_privacy_shadow_and_session.py, line 72:

<comment>Move the function-local imports to the module scope. This repository requires top-level imports, and keeping them local makes the test’s dependencies harder to audit and maintain.</comment>

<file context>
@@ -0,0 +1,342 @@
+
+
+def test_instrumentation_preserves_closed_historical_sdk_caller_labels(world, monkeypatch):
+    from database import firestore_document_probe as probe
+
+    db, _, _, _ = world
</file context>

@Git-on-my-level
Git-on-my-level merged commit 17a8b46 into main Nov 2, 2026
68 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/ic-privacy branch November 2, 2026 20:00
Git-on-my-level added a commit that referenced this pull request Nov 2, 2026
…4412)

## What changed and why

Marks newly registered, active-fenced backfill cohort jobs
worker-eligible and runs them in a dedicated child process. The original
named Cloud Task is still enqueued, scheduled five minutes after the
head reservation; no worker claim means it runs the existing handler.
Redrive and normal worker failure return directly to that fallback. S1
and S2 have merged; this PR targets main. Main was merged locally
without rewriting branch history; its new privacy decorator is
preserved.

Workers run the existing async pipeline without the Cloud Run handler
budget or replacement-enqueue machinery. Sequencer heartbeat remains
120s; Redis renewal remains 300s with the unchanged 1800s TTL. After
acquiring Redis, a child revalidates the sequencer token before download
or provider work. Lease loss kills the owned process group, including
detached executor leaves. Cancellation retains the Redis fence and
staged custody. SIGTERM stops intake and drains up to the existing 1500s
pod grace.

A separate parent-enforced 1380s work deadline bounds bootstrap,
pipeline work and normal flushing even when the child's
provider/executor never returns. Deadline expiry stops sequencer renewal
and kills the job process group before `/fail`; Redis remains held until
its unchanged silence TTL and the existing sweep redrives Cloud Tasks. A
regression proves child/descendant death, no early fallback acquisition,
next-epoch fallback acquisition after simulated 1800s expiry, and
rejection of both stale tokens. Minimal redrives refuse before
Redis/download when `SYNC_MINIMAL_REDRIVE_ENABLED` is off; enabled mode
reaches the pipeline unchanged, with regressions for both cases.

The shared pipeline entry, staged download and async custody cleanup now
have public names; router callers and existing test/harness seams
migrate together. This preserves a single execution implementation
without private-API type suppressions or compatibility wrappers. A
token-fenced `execution_drive=pull` job marker lets the staging kit
distinguish installed-worker execution from Cloud Tasks fallback alone.

Normal child exit flushes active holds (30s) and drains tracked
background tasks (10s) before process termination. Tests exercise actual
hold closure and owned-task cancellation for completion/retry, and
verify lease-loss cancellation bypasses flushing after its fence.

Successful worker completion immediately kicks the next queued UID head,
matching Cloud Tasks and avoiding an added two-minute sweep wait per
job. An integrated sequencer test proves one next-head enqueue and an
inert duplicate completion; RPC/sequencer focused tests pass 146 cases.

Available-owner scans stop before owner queries in global legacy dark.
Otherwise each poll reads at most 100 candidates and attempts one claim
transaction; a per-API-process document-ID cursor reaches filtered later
pages on subsequent polls and wraps at EOF. Empty/error claims back off
10/20/40/60s, resetting to 5s on work; health remains fresh during
backoff. Tests cover cohort and scoped-dark filtering, cursor
continuation/wrap and transactional-attempt bounds. Conservative
owner-read ceiling at the 5s floor: 105/poll including five transaction
attempts, 1,814,400/day per worker (3,628,800 for two). Sustained empty
polling at 60s is 151,200/day per worker plus the initial transition.
These bounds exclude existing shared rollout-cache refreshes and
transport retries; they are not live billing measurements.

## Session privacy integration repair

The public S3 coordinator retains #24402's privacy decorator; its
cancellation test now calls the public name with every original
assertion unchanged. The pull worker also scopes its entire attempt
before the first await, covering ledger convergence, preflight and
cleanup outside the nested coordinator. Both Cloud Tasks and pull
entrypoints, and the actual pull-to-coordinator call, have cancellation
regressions.

The isolated child previously lost process-local privacy metrics on
exit. The supervisor now scrapes the child's live Prometheus mmap
counters, retains their final values after normal exit or SIGKILL, and
removes each owned child directory after reaping the process group.
`/metrics` exports the seven existing counter families; the worker chart
enables PodMonitoring. This is code/chart preparation only, with no
deployment, credentials or admission changes. Worker installed-target
coverage and successful scrapes are prerequisites for the all-plane
14-day shadow window.

Regressions exercise live authority, candidate memo hits, and a
deliberately missing writer-token bump that must produce a stale-allow
mismatch while retaining the live block. Removing the worker scope makes
four regressions fail; removing child counter transport makes two fail.
Actual child-process tests verify live and shadow reads/checks, walks,
mismatches and memo/denominator counters survive normal exit and SIGKILL
without double counting or retained per-job files. An ASGI check
exercises the supervisor endpoint with a real child.

The main integration also corrects a stale derived flag-inventory count
(225 → 226); declarations and the 169 seeded/replacement budget are
unchanged. All 22 flag-budget tests pass. At the preceding privacy
repair head, GitHub shard 6 passed; shard 5 exposed this inventory
inconsistency, also present unchanged on main.

## Product invariants affected

Customer data authority, account-deletion/cutover and content/run fences
are retained (INV-DATA-1 / INV-AUTH-1). New worker jobs require active
ledger fencing, the sequencer, backfill lane and legacy mode on at
registration. Existing accepted workers drain under their tokens. No
batch admission, workflow, prod.yaml, IAM or deployment changes.

## How it was verified

Hermetic tests through `omi-heavy run -- nice -n 19` in
BasedHardware/omi task tree: RPC and strict Firestore fence tests; real
Redis Lua execution exclusion; admission mode matrix; named-task
five-minute fallback; actual subprocess/descendant death on lease
rejection and child crash; real pipeline composition with synthetic
provider/storage leaves; stale-claim rejection after Redis acquisition;
cancelled-job custody/TTL retention. Full local `make preflight` and
push hook are required before publication.

Round-1 repair verification: 177 focused worker/sequencer tests and 815
selected Firestore contract tests passed, each file in its own pytest
process. Every review finding has a regression observed failing before
its fix. Local preflight passed; normal pre-push gates and exact-head
GitHub checks are reported in the handoff, including cancellations.

Live OIDC, real Firestore contention, installed worker image, staging
outcomes and cost savings are NOT measured here. The separate staging
kit and infracost's authorized window remain gates. No GCP credentials
loaded or cloud writes performed.

## Ramp and rollback

Percent remains 0. Infracost with lead approval owns synthetic staging
qualification, then stable SHA-256 cohorts 5% → 25% → 50% → 100%, at
least 24h at 5% and 25%. Gates: zero lost speech/nonterminal ACK;
partial_failure no worse than baseline (~5%); no oldest-wait/depth
regression at equal admission; cost comparison includes actual
node-hours and displaced Cloud Run container-hours. Review activation or
report continued darkness blocked by 2026-11-09. Rollback: percent 0
closes new eligibility and claims, accepted workers drain,
already-enqueued Cloud Tasks and sweep retain recovery. Full backfill
net $40–60/day remains a scope estimate, not measured savings.

## Tests

`test_sync_worker_execution.py`, `test_sync_worker_runtime.py`,
`test_sync_worker_rpc.py`, and `test_sync_backfill_uid_sequencer.py`
exercise core, duplicate/expired ownership, fallback, death and refusal
paths. Synthetic process fixtures are bounded and every owned group is
reaped.

UI-Evidence: none -- backend worker execution only.

Failure-Class: none
Git-on-my-level added a commit that referenced this pull request Nov 3, 2026
…ver manifest (#24455)

## What changed and why

Sets `bpp_generation_memo:100` in `FIRESTORE_READ_LEVERS` everywhere the
lever map is declared: listen and pusher chart values (dev and prod),
the desktop backend, and every Cloud Run service and job in
`runtime_env/_base.yaml` and `prod.overlay.yaml`. All other lever values
are unchanged, including prod backend-sync's
`usage_month_cache`/`usage_month_total` override.

The rollout lead is setting the same value live on the serving services
after train cost2-1103 (listen and pusher at fa73bb8). This PR makes the
manifest match so the next deploy does not drop it.

The memo stops `batch_pipeline_privacy` from re-reading privacy inputs
on every task attempt. That caller is the largest Firestore reader at
about 6.1M reads/h on backend-integration and backend-sync. Its writer
fence (#23894) and follow-up (#24402) are on main and in the serving
images. Expected saving (estimate): **-$28 to -$43/day**. It will be
read back from the Firestore reads loop caller counter after the live
set.

Rollback: set `bpp_generation_memo` to 0 in the lever map (live env
edit, no image change), or revert this PR.

## Product invariants affected

- INV-MEM-4: not affected. The changed deploy manifest is a locked path,
but only the Firestore read lever map changes; memory intake and
promotion routes are untouched.
- Privacy enforcement for batch units. The memo only reuses a decision
for the same task-attempt generation, and the writer fence invalidates
it when privacy inputs change
(`backend/database/batch_pipeline_privacy.py`). Failed reads never
publish partial decisions
(`test_failed_reads_never_publish_partial_decisions`). No user-visible
change.

## How it was verified

- Manifest rewritten with the Firestore reads loop's `set_levers.py`,
then `compose_runtime_env.py` and `render_feature_flag_registry.py
--as-of 2026-11-02` regenerated the outputs.
- `backend/test.sh` with `test_render_backend_runtime_env.py`,
`test_verify_pusher_config_references.py`, `test_bpp_generation_memo.py`
and `test_bpp_generation_fence.py`: 98 + 32 + 91 + 28 passed.

## Tests

Updated pinned literals in `test_render_backend_runtime_env.py`
(including the per-host expected map) and
`test_verify_pusher_config_references.py`.

## UI evidence

None (backend config only).

🤖 Generated with [Claude Code](https://claude.com/claude-code)


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/24455?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="View guided diff"
src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a>
<a
href="https://www.cubic.dev/action/auto-fix/pr/BasedHardware/omi/24455?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F24455&source=description"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"><img
alt="Turn on auto-fix"
src="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->
YinkaAdepoju pushed a commit to YinkaAdepoju/omi that referenced this pull request Nov 3, 2026
…ver manifest

Sets bpp_generation_memo:100 in FIRESTORE_READ_LEVERS for listen, pusher,
the desktop backend, every Cloud Run service and job (base and prod
overlay), so the manifest matches the live lever the rollout lead sets and
the next deploy does not drop it. The writer fence (BasedHardware#23894) and its
follow-up (BasedHardware#24402) are on main and in the serving images.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Git-on-my-level added a commit that referenced this pull request Nov 4, 2026
… switch, plus decision-neutral shadow (#24622)

## What

60-second-bounded reuse of privacy, deletion, tombstone and legal-hold
decisions, per David's 2026-11-04 ruling (a cached decision may be
reused for at most 60s, so a deletion, privacy change or legal hold
takes effect everywhere within 60s). Three caches, each behind its own
`FIRESTORE_READ_LEVERS` key (absent = off), plus one runtime kill
switch:

| Lever | Covers | Reads per decision on a hit | Freshness |
|---|---|---|---|
| `bpp_decision_cache` |
`batch_pipeline_privacy.assert_batch_write_allowed` (transactional batch
intake/compute/projection) | ~5-6 -> 1 | **Exact**: the cached
generation is reused across task attempts only when THIS transaction's
token read matches. Every authority write rotates that token in the same
commit (`batch_privacy_write_fence`), and the token read stays in the
transaction's conflict set. Entries also expire 60s after the walk
started. |
| `privacy_ttl60` | `legal_holds.external_write_fence`
(non-transactional only), `conversation_tombstones.is_deleted`,
`account_deletion_marker.get_user_deletion_wipe_status` | 2 / 1 / 1 -> 0
| Bounded: a clear decision (or any marker status) is reused for at most
60s from the start of the live read that produced it. There is no token
read. Blocked, deleted and unavailable outcomes are never stored.
Transactional fence paths always read live. |

- New module `database/privacy_ttl_cache.py`: a thread-safe bounded LRU.
Expiry is anchored to the monotonic instant the authoritative read
started, so a slow read cannot extend the bound, and a read slower than
60s is never stored. Keys carry plane, uid, family and a hashed variant,
so one conversation's absence never answers for another.
- **Runtime kill switch, no deploy needed:** the data-plane document
`ops_kill_switches/privacy_decision_cache` `{disabled: true}` turns all
three caches off in every process within 30s. Each process polls it at
most once per 30s and only while one of the levers is on. If the switch
can't be read, the caches count as disabled and every decision reads
live. Gauge: `privacy_ttl_cache_disabled`.
- **Shadow:** with `privacy_checks_shadow`, live authority decides every
time. The candidate is what the cache would have answered before the
live read, and shadow costs no extra read for the `privacy_ttl60`
families. `compare()` now labels a stale allow whose cached entry is at
most 60s old `stale_within_ttl`: that is the accepted cost of the
ruling, kept apart from real mismatches (`stale_allow` / `stale_block` /
`block_reason`), and the kill-switch guard trips on real mismatches
only.
- **Metrics:** `privacy_ttl_cache_total{family,result=hit|miss|store}`
is new. The Cloud Run GMP keep-lists (`cloud_run_gmp_sidecar.yaml`,
`cloud_run_gmp_sync.yaml`) now export the `privacy_*_total` counters.
Before this, `privacy_decision_mismatch_total` from Cloud Run
(integration, sync, backend) never reached GMP, so the shadow evidence
couldn't be read there.

## Why

The firestore-reads loop snapshot for 2026-11-04 16Z shows
`batch_pipeline_privacy:read` at about 3.2M reads/h on
backend-integration and backend-sync. The fences (legal hold, deletion
marker, tombstone) add about 1.75M reads/h across sync, listen and
pusher. Coverage that hour was 0.70, so the true volume is higher. The
earlier token-validated caches (#24402) still paid one read per decision
(no saving for tombstones), and the batch memo was scoped to one task
attempt.

## Writer fencing (93d4a1)

No new writer-fencing project is needed.
`database/batch_privacy_write_fence.py` already appends a token rotation
to every commit that writes `account_deletions`, `legal_holds`,
`legal_hold_deletion_gates`, users privacy fields, conversation
authority fields or `deleted_conversations`. That makes the batch reuse
exact. The advisory caches rely on the 60s bound by ruling, not on the
token.

## Review fixes (round 1)

- Luna r1 P1: the deletion-marker cache could re-seed an already-aged
Redis negative, giving up to ~89s of staleness. Fixed: with
`privacy_ttl60` on, decisions and fills come only from a direct
Firestore read. The regression test fails without the fix.
- CI: `test_gpu_batch_retry_cap_does_not_reach_cloud_tasks`. The
kill-switch reader imported `account_deletion_marker`, which pulled
Redis and Cloud Tasks into the GPU batch worker's import closure. It now
uses `database._client.get_data_plane_firestore_client`.

## Rollout (David's 2026-11-04 soak policy for privacy levers)

1. This PR's second commit sets `privacy_checks_shadow:100,
privacy_ttl60:100, bpp_decision_cache:100` on every service, so the roll
that ships the code starts the live shadow. Shadow is decision-neutral:
live authority decides every time. It costs reads while it runs, because
shadow wins over `bpp_generation_memo` and batch re-walks the candidate
on a miss.
2. Evidence: at least ~1,000 synthetic plus replayed transitions with
zero real mismatches (cl2-replay `privacy_cache` stage and the prod
synthetic canary on dedicated test accounts), then 2h of live shadow at
100% with zero real mismatches.
3. Enforce: drop `privacy_checks_shadow`. A guard arms after one full
lookback window and sets the kill-switch document on the first real
mismatch.
4. Rollback: set the kill-switch document (seconds, no deploy), or set
the levers to 0.

## Verification

- Synthetic transitions with the real readers and real writers
(`data/run-2026-11-04-infracost/tools/privacy_canary.py` in
omi-workspace): Firestore emulator, 8 synthetic uids x 20 iterations:
1,120 transitions, 4,640 probes, **0 mismatches**, 320 within-bound
stale answers, and hits on all four families. Prod data plane
(prod-operator, synthetic uids `omi-privacy-canary-01..16` only, audit
`data/run-2026-11-04-infracost/canary-audit-prod.jsonl`): 1,559
transitions, 0 mismatches. Every document created was deleted.
- Config contract tests (`test_render_backend_runtime_env.py`,
`test_verify_pusher_config_references.py`,
`test_firestore_read_levers.py`): 143 passed.

- `pytest tests/unit/test_privacy_ttl_cache.py`: 20 passed. Covers the
bound, fixed at 60s and anchored to read start, with no storing of reads
slower than 60s. Also covers the LRU cap, tombstone reuse then deletion
visible at 60s, key isolation by conversation and plane, a never-cached
block on the external fence, transactional fences staying live,
deletion-marker reuse with uncached errors, shadow keeping live
authority and labelling within-bound staleness, batch reuse across
attempts with one token read, misses after token rotation, 60s expiry
and conversation-set keys, expected_generation, the lever off, and the
kill switch (including fail-closed and the poll interval).
- Related suites `test_privacy_shadow_and_session.py
test_bpp_generation_memo.py test_fsr_s4_caches.py
test_account_deletion_auth_fence.py
test_firestore_read_site_attribution.py test_firestore_read_levers.py
test_attach_cloud_run_gmp_sidecar.py`: 340 passed.

- Local push gate ran with `BACKEND_UNIT_FILE_BUDGET_SECONDS=900`: at
host load ~50, `test_firestore_query_shapes.py` hit the default 300s
wall twice (fixture setup alone took 202s; it passes 544/544 when run
directly). CI keeps its own 300s budget.

## Product invariants affected

- INV-MEM-4 (path match on `backend/deploy/runtime_env.yaml` only; no
memory promotion behavior changes)

## Failure class (fixes)

Failure-Class: none

The `fix:` commits repair review findings inside this PR's own new code
before merge, not a shipped failure class.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
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