Skip to content

feat(storage): wipe lake content and shred space keys on account and conversation deletion - #24897

Merged
Git-on-my-level merged 60 commits into
mainfrom
pgf/c4-wipe-coverage
Nov 11, 2026
Merged

Git-on-my-level merged 60 commits into
mainfrom
pgf/c4-wipe-coverage

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

Requested by David

Builds on the merged per-object DEK foundation (#24883).

What changed and why

Account wipe requires a verified lake prefix purge after the cell/directory step and before Firestore deletion. Its final key step cancels every pending upload session and verifies terminal storage status, repeats the current-bucket prefix purge, then repeats session fencing and deletes each candidate's object in its recorded bucket with verified absence before transactional compare-and-delete. It verifies candidate absence and destroys wrapped space keys LAST. Failures retain discovery and keys for retry, including when current bucket configuration is unset.

Explicit conversation deletion durably fences the conversation and merge donors and purges objects before document deletion. It synchronously cancels pending sessions, queries terminal status, deletes each recorded bucket binding, verifies absence, and compare-and-deletes unchanged candidate rows. Storage/discovery failures return retryable 503; success stays HTTP 204. Former buckets remain covered. Fenced writers retain their post-upload authority checks and transactional settlement; create-only retries preserve reused referenced objects for the deleting orchestrator.

Each upload attempt uses a separate GCS resumable session initiated with exact size, fixed metadata and generation-zero precondition before any payload bytes. Its session URI is persisted with the candidate attempt under the same transactional deletion fences. A refused candidate transaction cancels the empty session best-effort. One PUT sends the complete encrypted payload, capped at 8 MiB, without SDK retries. 412 at initiation or finalization follows the create-only replay path. A five-second pointer-success budget splits remaining time between connect/read waits; deletion authority comes from storage session fencing, never elapsed time.

Fencing sends DELETE to the recorded session URI, followed by the documented status query: a zero-byte PUT with Content-Range: bytes */<declared size> (the attempt records its size). The terminal set is an allowlist measured against GCS in a dev bucket on 2026-11-09:

  • 200/201: finalized. Status and cancel both return 200 once the upload has finalized.
  • 412: a generation-0 finalize was refused. This is sticky: every later status, cancel or upload returns 412, and the session cannot create the object even after it is deleted.
  • 499: cancelled. Every later status, cancel or upload returns 499, including the final chunk of a partly uploaded session.
  • 404/410: the service no longer knows the session.

Any other response fails closed and retains discovery: 308 (open), 400 (a malformed request, which poisons the session with 400 without proving its state), auth errors, throttling, 5xx and transport errors. Every retry cancels and queries again. GCS resumable upload protocol supplies the storage fence. The session URI is a sensitive capability: it is stored only in candidate state and excluded from pointers, logs, metrics and raised exception messages. Local/offline uses persistent filesystem sessions with the same transport path and cancel/finalize locking.

Legacy timestamp-only attempts, including the legacy key and candidates predating in_flight, fail closed at any age because they have no recorded session to cancel. Lake writes have never been admitted outside local/offline/dev (_WRITE_STAGES); no production legacy rows exist. Production admission remains closed. No age-based erasure, delayed re-purge, Cloud Tasks scheduling, internal re-purge handler or wipe-drain setting remains. No new infrastructure or production configuration changes.

Product invariants affected

INV-DATA-1: deletion markers, candidates and key authority use the customer data-plane Firestore client. INV-CUTOVER-1 and INV-MEM-3 cover B2/C2 dependencies against main; C4 retains their admission and continuity contracts.

How it was verified

Round 12 passed 860 distinct targeted tests (0 failures/skips), including 12 loopback Firestore tests. Runtime Pyright passed with 0 errors / 530 warnings; expanded changed test/support typing remains red with 99 errors / 2999 warnings. The route-policy baseline, async-blocker gate and formatting passed. Exact commands and exclusions are recorded in .agent-artifacts/pgf/c4-fix-r12-result.md. Tests use local encrypted storage, strict synthetic Firestore transactions, real HTTP deletion serialization, scrubbed agent credentials and the prescribed synthetic encryption secret. No GCP tier, production data or api.omi.me access. Full selector/preflight and repository-wide typecheck are excluded by this fix-round brief. No push, merge or deployment.

Tests

Regressions cover lost-writer sessions cancelled by conversation deletion/account wipe, rejected late finalization after key destruction, finalization immediately before cancellation, terminal-status classification, nonterminal/transport failure retention and key preservation, legacy attempts at arbitrary ages, fenced candidate transactions, capability redaction, initiation/finalization 412 replay, independent same-key settlement, and existing owner/conversation settlement races. Existing former-bucket deletion, absent current configuration, delete/absence-check failures, wipe ceremony and HTTP deletion contracts remain covered. Session persistence across local client restart and generation-zero finalization are tested. Erasure APIs accept no clock/expiry arguments. Candidate range drivers remain single-field automatic-index maintenance queries (serving=False); obsolete clock/expiry/scheduling driver arguments are removed. The route-policy baseline is checked after route removal.

UI evidence

UI-Evidence: none -- backend only

Failure class (fixes)

Failure-Class: none

Scoped cleanups (optional)

The artifact orchestrator reads raw donor inventory and performs candidate cleanup even with the bucket unset. The developer delete endpoint shares this orchestrator and retains its existing HTTP 500 failure behavior. Merge-internal donor deletion and pre-existing orphans remain C3 scope. The accepted seven-day wrapped-key PITR tail remains. Object/candidate purges remain pinned to release v1. Activation remains separately authorized and requires the wipe-coverage gate and deployed session-aware writers and deletion handling.

Line-Count-Exception: backend/routers/conversations.py | 2590 -> 2599 | Preserve the existing delete route and its retryable storage/discovery failure mapping; session mechanics live in the lake modules. Measured against merge-base 697e744.

Review fixes (round 15)

  • 307c4f: with BUCKET_CANONICAL_AUDIO set, the conversation delete route's donor-inventory read (get_conversation_raw_snapshot, now narrowed to sync_merged_from) ran outside the 503 mapping. A failure there now returns the retryable 503, before any audio or lake purge is scheduled.
  • fd278c: the single payload PUT now carries its full Content-Range: bytes 0-(n-1)/n. Measured in GCS: it finalizes with 200 for 5 B and 300 KB payloads. The local session model accepts that exact range (or none, as GCS also does) and rejects any other range.

Review fixes (round 14)

  • dffbc2: a finalize that returns 412 now fences its own session (cancel, then a terminal status check through the session's client) before settlement drops the URI. A status that is not terminal keeps the attempt discoverable. Measured in GCS: 412 is sticky and terminal.
  • babf78: the deletion protocol doc now records size and describes the sized status query and the measured allowlist.

Review fixes (round 13)

  • c47184: the fence now uses an allowlist (200/201/404/410/499) instead of a 4xx denylist, and the status query names the session's declared size. Both were confirmed against GCS behavior measured in a dev bucket. CI: local session records no longer use the lifecycle field name status.

Review fixes (round 12)

  • Replaced elapsed-time upload assumptions with per-attempt GCS resumable-session cancellation and terminal-status verification before recorded-bucket deletion, absence checking and candidate erasure.
  • Removed age-based cleanup, delayed scheduling/handler/policy entry, the drain setting and registry entry, and their obsolete tests. Erasure has no now parameter.
  • Retained final key destruction, post-upload checks, create-only replay and transactional settlement fences. Finalize responses populate the blob generation so conditional fenced-writer deletion retains the SDK behavior. Initiation-time 412 records settled discovery without a session capable of committing.
  • Legacy attempts fail closed indefinitely; malformed candidate state is rejected. Session capabilities never appear in returned references or raised messages.
  • Updated persistent local session transport, query-driver signatures, deletion protocol documentation and the required regression suites.

Earlier review fixes retained

  • Import FieldFilter from the public google.cloud.firestore_v1 seam for isolated test imports.
  • Settlement re-reads conversation and account deletion fences in its transaction and refuses a pointer after fenced object cleanup. Conversation deletion always writes the durable tombstone, including bucketless revisions.
  • The R14 test guard retains quarantine behavior for legacy account markers without wipe_status; no task claim or reconciliation re-drive is admitted.

@Git-on-my-level Git-on-my-level self-assigned this Nov 8, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-09T09:44:50.475678Z 6a4d385 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@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.

2 issues found across 35 files

Confidence score: 4/5

  • The reload and import-graph setup in backend/tests/unit/test_lake_wipe_step.py puts ceremony and merge tests in the fast unit lane. Mark them slow or remove the reload-based setup.
  • backend/docs/listen_pusher_pipeline/changes/2026-11-07-per-object-dek.md says the upload and deletion fences are unchanged, but this PR changes them. Clarify the document to reflect the new transaction fences and generation-scoped cleanup.

You’re at about 97% 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/tests/unit/test_lake_wipe_step.py">

<violation number="1" location="backend/tests/unit/test_lake_wipe_step.py:189">
P2: These tests perform fresh service-module reloads and full import-graph setup in the fast unit lane without a `slow` marker. Mark the ceremony/merge tests slow (or remove the reload-based setup) so the required fast-unit budget and lane classification remain valid.</violation>
</file>

<file name="backend/docs/listen_pusher_pipeline/changes/2026-11-07-per-object-dek.md">

<violation number="1" location="backend/docs/listen_pusher_pipeline/changes/2026-11-07-per-object-dek.md:16">
P3: This says the upload and deletion fences are unchanged, but this PR adds conversation tombstone and upload-candidate transaction fences and changes late-upload cleanup to generation-scoped deletion. Clarify that the DEK codec preserves the owner-fence behavior while the deletion work adds these lifecycle protections.</violation>
</file>

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

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

Comment thread backend/utils/other/object_lake.py Resolved
lake_steps.destroy_owner_lake_keys = lake_wipe.destroy_owner_lake_keys
fakes[lake_steps.__name__] = lake_steps
with stub_modules(fakes):
service = load_module_fresh(

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 tests perform fresh service-module reloads and full import-graph setup in the fast unit lane without a slow marker. Mark the ceremony/merge tests slow (or remove the reload-based setup) so the required fast-unit budget and lane classification remain valid.

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_lake_wipe_step.py, line 189:

<comment>These tests perform fresh service-module reloads and full import-graph setup in the fast unit lane without a `slow` marker. Mark the ceremony/merge tests slow (or remove the reload-based setup) so the required fast-unit budget and lane classification remain valid.</comment>

<file context>
@@ -0,0 +1,457 @@
+    lake_steps.destroy_owner_lake_keys = lake_wipe.destroy_owner_lake_keys
+    fakes[lake_steps.__name__] = lake_steps
+    with stub_modules(fakes):
+        service = load_module_fresh(
+            'services.users.account_deletion', Path(__file__).parents[2] / 'services/users/account_deletion.py'
+        )
</file context>

Comment thread backend/utils/other/lake_wipe.py Resolved
Create-only retries retain the first payload. Space-key rotation affects new
objects only; retired versions remain readable, with no eager or lazy re-wrap.
Destroying the space-key authority shreds both formats even with a warm cache.
Upload and deletion fences are unchanged. C4 must cover v2 objects in 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.

P3: This says the upload and deletion fences are unchanged, but this PR adds conversation tombstone and upload-candidate transaction fences and changes late-upload cleanup to generation-scoped deletion. Clarify that the DEK codec preserves the owner-fence behavior while the deletion work adds these lifecycle protections.

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/listen_pusher_pipeline/changes/2026-11-07-per-object-dek.md, line 16:

<comment>This says the upload and deletion fences are unchanged, but this PR adds conversation tombstone and upload-candidate transaction fences and changes late-upload cleanup to generation-scoped deletion. Clarify that the DEK codec preserves the owner-fence behavior while the deletion work adds these lifecycle protections.</comment>

<file context>
@@ -0,0 +1,28 @@
+Create-only retries retain the first payload. Space-key rotation affects new
+objects only; retired versions remain readable, with no eager or lazy re-wrap.
+Destroying the space-key authority shreds both formats even with a warm cache.
+Upload and deletion fences are unchanged. C4 must cover v2 objects in its
+prefix-purge / keys-last account-wipe test.
+
</file context>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: fb9af607d0

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread backend/utils/other/lake_wipe.py Outdated
Comment on lines +23 to +25
time.sleep(config.wipe_drain_seconds())
count = object_lake.delete_space_prefix(uid)
candidates = object_lake.delete_space_upload_candidates(uid)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Quiesce in-flight uploads before erasing their discovery intents

With a configured lake, an upload that records its candidate before the deletion fence can remain in flight beyond the fixed drain interval. This step then verifies an empty prefix and deletes the candidate, but the upload can subsequently commit. If its response is lost, put_space_object raises LakeFetchError without reaching _check_put_authority, so the late blob is not self-deleted. The account wipe can therefore complete while leaving an encrypted object and its owner/conversation-identifying path behind, with its discovery intent already erased. Use a durable upload-drain barrier or durable late-upload cleanup rather than relying on the delay and the uploading worker's successful return.

Useful? React with 👍 / 👎.

Comment on lines +74 to +76
lake_wipe.purge_conversation_lake_objects(uid, conversation_id, source_ids)
if default_deleter is not None and conversation is not None:
default_deleter(uid, conversation_id, conversation_row=conversation)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Use raw existence checks when retrying developer deletions

For a lake-backed conversation deleted through the developer API, if this purge removes the parent transcript and a subsequent donor purge or metadata deletion fails, the next DELETE cannot resume cleanup. delete_conversation_endpoint in backend/routers/developer.py first calls get_conversation, whose prepare_conversation_for_read decoder returns None for the now-absent transcript blob, so the endpoint returns 404 before reaching this orchestrator even though the conversation document and remaining cleanup inventory still exist. Update that endpoint's existence/lock check to use the raw snapshot as well, so a partial deletion remains retryable.

Useful? React with 👍 / 👎.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: bda2772c94

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

need a complete ``utils.memory.retraction_scope``.
"""

from utils.other import lake_wipe, object_lake

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Move the new lake imports to module scope

The new function-local import violates backend/AGENTS.md, which requires “All imports at module top level — never inside functions.” Move lake_wipe and object_lake into the module-level imports; the existing lazy merge-deleter import does not exempt newly added dependencies from this repository convention.

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

Useful? React with 👍 / 👎.

Git-on-my-level and others added 21 commits November 8, 2026 18:14
…ure queries as maintenance

A raised put can still commit server-side, so only a returned put settles
its candidate attempt; the quiescence bound ages out the rest. The three
candidate erasure queries are non-serving maintenance profiles.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…lement

Also import FieldFilter from the package root so suites that stub
google.cloud.firestore_v1 as a module still collect, and correct the drain
flag note to the 24-hour quiescence assumption.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…wipe_status

Neither claim path writes or enqueues a marker with no wipe_status, and the
reconciler's equality-only status queries never enumerate one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…action

A tombstone landing after settlement's pre-read let the transaction mark the
attempt settled while deletion purged the object, so the put returned a
reference to erased data. The transaction now reads the tombstone; a late
fence keeps the attempt in flight, purges the recorded object, settles, and
fails the put with LakeWriteFenced.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…cket

An empty candidate query on a bucketless revision does not prove no
bucket-enabled writer sits between admission and candidate recording during
a mixed-revision rollout. Reverts the unconfigured fence skip (e893774); the
create-if-absent tombstone is the durable fence on every path.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
An account wipe marker landing after the put's authority check let
settlement clear the attempt and return a reference the wipe then erased.
The settlement transaction now reads the account marker alongside the
conversation tombstone; either fence purges the object and fails the put.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Failure-Class: none

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ion terminal

Failure-Class: none

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…eclared size

Measured against GCS in a dev bucket: cancel yields a sticky 499, finalize
yields 200 on status and cancel, and a malformed request yields a sticky 400
that proves nothing about the session. Only 200/201/404/410/499 now release
discovery; the status query names the attempt's recorded size.

Failure-Class: none

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…g it

A generation-0 finalize refusal is sticky in GCS (measured: every later
status/cancel/upload returns 412 and the session cannot create the object
even after deletion). The replay path now fences its own session with the
session's client before settlement drops the URI; a non-terminal status
keeps the attempt discoverable. The deletion protocol doc now matches the
sized status query and the measured allowlist.

Failure-Class: none

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…payload range

The cascade delete route's donor-inventory read now maps failure to the
retryable 503 before any purge is scheduled, reading only sync_merged_from.
The single payload PUT carries its full Content-Range (measured: GCS
finalizes it); local sessions and test hooks recognize status queries by
the 'bytes */' prefix.

Failure-Class: none

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Git-on-my-level added a commit that referenced this pull request Nov 10, 2026
)

## What and why

Retire summary due indexes atomically when donor tombstones, manual
title/overview edits or already-enriched merges refuse repair. Preserve
`summary_first_pending_at`. Undo/manual-field removal and discard
restore recover owed debt in the same transaction using original
acceptance plus the row's policy deadline, without replacing a non-null
due or arming a refused/owned row. Internal debt metadata stays outside
reversible user-field receipts.

The guarded operator script clears legacy residue using the serving
refusal classifier. Unknown provenance is retained for provenance
repair; processing, local-only, BYOK and active finalization ownership
are explicitly retained even when another refusal has precedence. Both
completion metadata and output-present metadata retire copied legacy
due. No serving rate, feature flag, deadline, capacity, repair-service
or released-client schema changes.

## Merge order — required hold

Merge **after #25019 and #25032. This PR must not merge before #25032.**
Both dependency PRs were OPEN when this batch began. After #25019 lands,
rebase onto current `origin/main`, regenerate inventories and retain
both sides' tests; never resolve a shared-file conflict by taking one
side wholesale. Repeat exact inventory guards after any overlapping PR
lands. #25032 owns its upstream registry/flag-budget train conflicts;
this batch does not edit them.

## Operator run plan — cl2-deploy only

1. Deploy the merged code first, then identify the exact serving
revision. Old writer sites keep re-arming due during the sweep, so a
pre-deploy sweep or dry-run is insufficient.
2. Re-run a fresh dry-run **after deployment on that serving revision**.
Verify the deployed `summary_due_at` collection-group index and inspect
class/retained/eligible/conflict counts before any apply.
3. Run a bounded **5,000 scanned-row canary**, using an apply cursor
separate from the dry-run cursor. Production `--apply` additionally
requires `--confirm-production-project based-hardware` matching the
actual client's project. Review canary counts.
4. Run the full sweep **only on lead2's go**. Re-run the
serving-revision dry-run after any intervening code deployment; restart
without a cursor to reconsider conflicts as needed.

The sweep runs **two disjoint passes** at one cutoff instant: a numeric
`summary_due_at <= now` pass, then a Timestamp `summary_due_at <=
datetime(now, UTC)` pass. Each uses `(summary_due_at, __name__)`
pagination, classifier-only projection and batches of at most 400
writes. Every clear retains the original snapshot `update_time`
precondition, including individual retries after atomic batch failure.
Concurrent re-arm/delete is skipped. `--limit` bounds the combined
scanned rows across both passes, including retained rows. Aggregate
counts remain available, with scanned/eligible/classes/written/conflicts
also reported separately under `passes.numeric` and `passes.timestamp`.
Output is counts-only; private cursor files are written to unique
same-directory `mkstemp` files, explicitly set to mode `0600`, flushed
and fsynced before atomic replacement; any failed attempt removes its
temporary file and preserves the previous checkpoint. They include a
`pass` marker plus a numeric or tagged RFC3339 due and document path,
with no IDs printed. Cursors are separate for each pass: completing
numeric scanning checkpoints `{pass: "timestamp", due: null, __name__:
null}` before the first timestamp query. Resuming a timestamp checkpoint
skips the completed numeric pass. Older unmarked cursors infer their
pass from the due type. Keep apply/dry-run cursor files separate. This
operator-only metadata cleanup is exempt from content-generation batch
privacy admission: it never reads transcripts/generated summaries or
changes protection levels or content. No production access or operator
run was performed in this lane.

## Follow-up: private atomic checkpoints

Review-desk FIX-FIRST at `f940cf9dd489` found that the predictable
`.tmp` path could expose private cursor document paths through a
pre-existing permissive file or symlink. Checkpoint publication now uses
a unique file in the checkpoint directory, explicit `0600`, flush/fsync
before `os.replace`, and unconditional temporary-file cleanup on
failure. Atomic replacement also replaces a final-path symlink without
following its target.

- Backfill suite through omi-heavy: **101 passed / 1 existing
loopback-only skip**, 1.33s, completed approximately 2026-11-10 17:51Z.
All eight new filesystem/security cases passed. This follow-up changes
only the backfill script and its test file; no operator --apply or
production access.
- Checkpoint follow-up head: `8159c89608d86c4c67a9bfc5d077e57c7df2f48f`.
`make preflight`: **39 checks passed in 64.42s**, completed
approximately 2026-11-10 17:55Z. Full PR non-test scope: **397 changed
lines**, within the original 500-line cap. The single authorized
checkpoint follow-up push succeeded as a fast-forward, approximately
2026-11-10 17:55:43–17:57:17Z. Its normal hook passed **39 shared checks
(67.26s), typecheck with zero errors, 250 passing changed-file tests
plus 23 explicit loopback-only skips**, and pinned formatting.
Exact-head CI is being monitored with a 90-minute deadline.

## Follow-up: two-pass sweep

Review-desk FIX-FIRST at `50f47f8058fc` found that a numeric cutoff
never selects Timestamp-valued due. The backfill now queries both types
and keeps the same classifier, fences, dry-run default and counts-only
output in each pass. Checkpoints explicitly mark the active pass and
survive interruption at the pass boundary.

Read-only inspection also confirms the serving query/repair blind spot:
`database/summary_debt_queries.py:13,24` uses a numeric cutoff/cursor;
`services/summary_debt_repair.py:50` rejects nonnumeric due and its
overdue-age arithmetic assumes a number. Those files are **unchanged**,
as requested; cl2-fixnow should route that finding to #25019's owner.

- Focused selection re-run through omi-heavy, 2026-11-10 approximately
17:12Z: **2,209 passed / 23 skipped / 86 xfailed**. Adjacent **117
passed**; extra chat/tool/strict transaction selection **55 passed**.
Per-file commands, exact timestamps and results:
`focused-results-followup-m1.json` in the supplied task directory.
- Backfill tests against synthetic loopback Firestore: **94 passed**,
receipt completed 2026-11-10T17:12:06.668829+00:00. Includes actual
mixed-type inequality behavior, refused clears, owed/future retention,
shared limits, both cursor types, interruption at the pass boundary and
bounded/fenced writes. Emulator shut down normally.
- Follow-up at earlier head `f940cf9dd4898798c72e854c0dd5226554b76866`.
`make preflight`: **39 checks passed in 46.50s**, 2026-11-10
approximately 17:15–17:16Z. Full PR scope: **388 non-test changed
lines**, within the 500-line cap.
- Only the backfill script and its test file changed in this follow-up.
Serving query and repair files remain untouched. The single follow-up
fast-forward push succeeded on 2026-11-10 approximately
17:16:32–17:17:52Z. Its normal hook passed 39 shared checks (57.04s),
typecheck with zero errors, 242 passing changed-file tests plus 23
explicit loopback-only skips, and pinned formatting. CI is being
monitored on this exact head with a 90-minute deadline.


## Verification of the preceding batch

Verification is hermetic code and synthetic loopback Firestore evidence,
not deployed-runtime evidence. Commands use
`/Users/david/workspace/omi-workspace/bin/omi-heavy run --` and the
worktree's Python 3.11, with GCP credential environment scrubbed. Pytest
files run in isolated processes under the backend unit contract.

- Requested focused selection on this batch: **2,170 passed, 22 skipped
(loopback tests run separately), 86 xfailed**, 2026-11-10
16:14:30–16:15:06Z. The old ae48104 selection measured 2,087/4/86; new
guards add passing cases and the new emulator cases increase the
explicit loopback-only skips.
- Adjacent selection: **117 passed**, 16:15:06–16:15:13Z; additional
chat/tool/strict People transaction selection: **55 passed**,
16:15:13–16:15:18Z. Exact per-file commands, timestamps and logs:
`/Volumes/scratch/cl2-fixnow-move25020/focused-results-m1.json`.
- Synthetic loopback Firestore: **22 chat edit/undo tests passed** and
**31 People-generation emulator checks passed**, 2026-11-10
approximately 16:13–16:14Z. Emulator stopped. Used the installed Java 21
in the process environment only.
- `make preflight` on commit `50f47f8058fcb904bb5bd185184c1473284783cc`:
**39 checks passed in 55.79s**, 2026-11-10 approximately 16:17–16:18Z.
The full PR has **354 non-test changed lines** (342 additions / 12
deletions), below 500.
- Regenerated the lifecycle payload inventory for changed owners and all
People fingerprints (only the four already-audited chat scopes differ);
People generator check reports no delta. Exact lifecycle
inventory/state-table guard is included above; serving lifecycle write
guard passed in preflight. Normal pre-push on
`50f47f8058fcb904bb5bd185184c1473284783cc` passed all 39 shared checks,
typecheck with zero errors, 203 passing changed-file tests plus 22
explicit loopback-only skips, and pinned formatting for all 15 PR Python
files (2026-11-10 16:18:28–16:19:46Z). The single fast-forward push
succeeded with no bypass.


UI-Evidence: none — backend metadata and an operator script only.

## Finding dispositions

| Finding (review sources) | Disposition in this batch |
|---|---|
| Predictable checkpoint temp path can follow a symlink or reuse
permissive permissions (review-desk 72a878, FIX-FIRST) | Use exclusive
unique same-directory `tempfile.mkstemp`, enforce `0600` via `fchmod`,
write/flush/fsync, then `os.replace`. Cleanup runs on failure, leaving
the previous checkpoint intact. Regressions cover the old predictable
symlink/permissive file, permissive umask, write/fsync/replace/fchmod
failures, descriptor closure and safe replacement of a final-path
symlink. |
| Numeric-only cutoff misses timestamp-valued due (review-desk e7b7dc,
FIX-FIRST) | Replaced with numeric and Timestamp passes, distinct
pass-aware checkpoints and per-pass counts. Tests cover
refused/owed/future rows in both types, shared limits, resumable pass
boundary, update-time conflicts and 400-write caps. A loopback Firestore
regression verifies actual mixed-type query behavior. |
| Unknown provenance retired as durable; #25032 late projection stranded
(pd correctness/custody/tests/merge/Kimi) | Removed from
`DURABLE_REFUSALS` and durable test cases. Regression retains the legacy
due and first-pending anchor. Missing provenance still needs its owning
repair; this batch never clears it. |
| Manual undo loses owed debt (all correctness/custody/test reviews, old
merge/CI) | Chat restore and explicit null/DELETE_FIELD removals re-arm
atomically from preserved first pending plus the stored
`first_summary_policy` deadline, falling back to `deadline_seconds()`.
Refused rows and already-armed rows never acquire a replacement due.
Real codec, strict transaction and loopback emulator coverage. |
| Every other manual removal path needs coverage (sdclear-fix1) | Title
UI and offline empty titles remain non-null manual values, covered by
retirement tests. Chat tools reject blank title/overview edits before
IO. Sync restore and generated persistence preserve manual fields. All
actual removal writers are declared in the lifecycle inventory. |
| Summary BYOK reason not excluded; terminal BYOK semantics untested (pd
correctness/custody/tests) | Explicitly retain
`summary_blocked_reason=blocked_byok`, including a competing deleted
flag and no active job. Existing finalization BYOK exclusion remains. No
terminal-BYOK policy expansion. |
| Detached queued/leased finalization rows (pd correctness) | Explicitly
retain both statuses even without a job ID, including competing
manual/discard flags. Re-arm also respects these owners. |
| Output-present enriched row can retain copied due (pd custody) | Both
completion metadata and `summary_output_present=True` take the enriched
return and retire due. Empty reprocessing preserves banked structured
content without requiring a completion stamp. |
| Discarded rows recoverable after sweep (pd correctness/tests) | The
existing restore transaction re-arms only currently owed, unarmed rows
from original acceptance and policy. Tests cover cleared legacy rows
without receipts, manual/enriched/locked refusal, existing due and
writer ownership. |
| Refusal classes can later reopen (pd correctness/custody) | Manual and
discard inverses now recover debt. Empty-output revision re-arm stays
intact and is covered by the adjacent recovery suite.
Privacy/content-floor decisions remain governed by their existing
policy; this metadata cleanup does not introduce a new privacy/content
transition. `DURABLE_REFUSALS` now documents current-obligation
retirement rather than permanent lifecycle finality. |
| Backfill bypasses batch privacy fence (pd custody) | Documented
metadata-only operator exemption: no transcript or generated summary is
read or written; only the due index is cleared with a snapshot
update-time fence. Serving content-generation fences remain unchanged. |
| Non-JSON due checkpoint (pd custody) | Timestamp cursors use private
tagged RFC3339 values and decode on resume, preserving Firestore
timestamp type and nanoseconds. Numeric cursor format remains supported.
|
| No explicit prod apply guard (pd custody) | `--apply` on
`based-hardware` requires matching `--confirm-production-project
based-hardware`; an unknown project fails closed. Synthetic unit
coverage only; no operator apply was run. |
| CLI failure path / deleted cursor not tested (pd tests) | Added
counts-only CLI error regression and resume after a deleted numeric
cursor; timestamp cursor also resumes after a missing cursor document. |
| Unchanged-title path lacks assertion (pd tests nit) | Added
no-write/no-due-move assertion for an unchanged offline title. |
| Legacy exact title assertion fails CI (old CI/merge) | Already
corrected at ae48104; retained and re-run the full revision-contract
file. |
| Update-time fence, dry-run, bounded cursor, counts-only output (all
reviews) | Preserved; original race, atomic-batch, tie/resume,
scanned-row limit, batch-size and privacy tests remain intact. |
| Deploy must precede sweep (old merge, sdclear-fix1) | Run plan below
requires code serving first and a fresh post-deploy dry-run on that
exact serving revision before the 5k canary. Old writers would keep
re-arming due during a sweep. |
| Code revert cannot restore cleared rows (pd merge, old custody) |
Rollback explicitly requires a separately authorized re-stamp keyed on
preserved `summary_first_pending_at`, current owed rows only. |
| #25019 / #25032 ordering and same-file inventories (pd merge, old
merge, sdclear-fix1) | Must merge after both, never before #25032. Both
were OPEN at intake; no premature rebase. After #25019 lands, rebase and
regenerate inventories, preserving both sides and tests rather than
taking a side wholesale. |
| Upstream #25032 registry / #25034 flag-budget conflicts (pd merge) |
Dependency-owner work outside this batch. The merge train must resolve
those before #25020; no workflow/flag-budget edits here. |
| #25018 / #24866 / #24801 / #24897 / stale #24607 overlaps (old and pd
merge) | Re-fetch before integration; if these land first, rebase and
re-run exact inventories and both branches' tests. No unrelated PR
changes or merges performed here. |
| Operator query excluded from serving-query inventory (pd merge) |
Preserve script scope. Uses the existing `summary_due_at`
COLLECTION_GROUP single-field index; cl2-deploy must verify the deployed
index with the serving-revision dry-run before canary. No production
query in this lane. |
| People audit and lifecycle inventories after shared-scope changes (all
test reviews) | Regenerated reviewed entries and four existing People
fingerprints after strict transaction and loopback emulator proof;
exact-match guards re-run. |

## Rollback

A code revert **does not restore rows whose due indexes the backfill
already cleared**. Preserve the operator receipts/cursors and stop the
sweep. A separately authorized repair must enumerate/re-stamp keyed on
the preserved `summary_first_pending_at`; only rows the current
classifier calls owed, with no competing owner and a null/missing due,
may receive `summary_first_pending_at + stored first_summary_policy
deadline` (or `deadline_seconds()` without a snapshot). Never reset the
anchor, move a non-null due, or blindly re-arm refused rows. Do not use
the due index itself to find already-cleared rows.

Failure-Class: FC-obligation-outlives-terminal-owner

Line-Count-Exception: backend/database/conversations.py | 4960 -> 4969 |
Keep atomic due retirement and guarded discard-restore re-arm at their
owning writes.

Line-Count-Exception: backend/utils/sync/assignment.py | 1538 -> 1539 |
Keep atomic summary-debt retirement at the donor redirect write.
@Git-on-my-level
Git-on-my-level merged commit c8a75e2 into main Nov 11, 2026
63 checks passed
@Git-on-my-level
Git-on-my-level deleted the pgf/c4-wipe-coverage branch November 11, 2026 04:01
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