feat(deletion): clean up media for users and owned agents (#9365)

## Why

User deletion must remove uploads by the user and their owned agents
while preserving files uploaded by anyone else. Attribution can span
communities and survive only in storage, so cleanup must combine
database and storage evidence.

## What

Add one media handler used by both the direct `user-deletions
media-batches` command and the persisted user-deletion workflow. Preview
is read-only by default; deletion requires `--delete`.

The workflow now always runs `gate_user` → `purge_media` → community
stages. The gate and community handlers remain placeholders. Media
failure stays on the same stage for retry; a saved completed media stage
is not executed again on restart.

## How

- Resolve the human and directly owned agents once across communities.
Sharing within that target set does not protect a file.
- Combine candidate discovery from `media_uploaders` and upload audit
history with a sharing check for those hashes. Check outside uploaders
across all communities. Storage-only candidates receive the same
database check in batches.
- Add four nonunique indexes for uploader and hash lookups. Current
membership cannot safely filter historical discovery: departed members
may have no remaining membership row.
- Scan `_uploads/` for candidates, then candidate claims for outside
ownership. List blob and thumbnail versions by each selected `{hash}.`
prefix. A separate `_meta/` listing preserves sidecar coverage when no
matching claim or current membership remains. There is no whole-bucket
listing.
- Finish all discovery before deletion. Read historical claims using
exact `versionId` values. Delete exclusive file versions and markers,
with upload-attribution objects last. Remove target uploader rows after
storage processing succeeds. Shared storage versions and outside
uploader rows remain.
- Stream one JSON document with file identity, keep/delete status,
versions, and outcome counts. Remove per-file owner queries and owner
arrays. Workflow stdout remains inspection JSON; media reporting goes to
stderr.

Database/inventory pages hold at most 500 rows. Storage listings use at
most 1,000 entries per page and 100,000 pages per listing. A disposable
in-memory inventory has a 128 MiB accounting budget and a 250,000-entry
cap, including candidates, filenames, versions, and listing markers.
Accounting includes string bytes, inline data, and a conservative
allowance for tree/allocator overhead; it is not a process RSS limit.
This removes the SQLite dependency without a security-policy exception.
Large jobs may reach capacity sooner than with the former 1 GiB disk
inventory. Exceeding a discovery limit aborts before mutation; no
truncated inventory is used for deletion.

Migration 0092 and the desired schema add the same indexes. The
migration builds missing indexes under short lock/statement budgets and
verifies existing definitions. Large deployments can prebuild
concurrently using the procedure in [the executor
guide](docs/operator-user-deletion-executor.md). Existing relay writes
remain compatible. A stale workflow test call from the merged main
branch also receives its required run-cause argument.

## Risk

This performs real storage deletion. Writers must remain stopped; the
placeholder gate does not prevent uploads. Immutable version IDs are
required for exclusive objects. All results report
`account_erasure_complete: false`. Existing synthetic progress saved
under the older gate-to-community sequence is not migrated into the new
sequence.

Shared storage claims and audit history remain. They can continue
protecting a blob after both uploaders leave; claim retirement is
separate work. Metadata namespace scans remain proportional to their
sizes. Bare blobs with no surviving attribution cannot be assigned to a
user.

## Testing

Before committing the replacement as
`38c60be7f6c3ee3f6942ab89858ce42e2a536c5d`, exercised the actual
`buzz-admin user-deletions media-batches` command against a fresh local
PostgreSQL database and versioned MinIO bucket. Preview preserved all 23
versions and all database rows. Deletion removed 14 exclusive versions,
preserved nine shared/unrelated versions, and removed only five target
uploader rows. Retry removed no further versions; events and
publications remained unchanged.

A standalone probe of the production inventory reached the default byte
budget after 243,148 short-key versions or 90,933 versions with 1 KiB
keys. Peak process RSS was approximately 108 MiB and 124 MiB on macOS;
these measurements describe the probe, not total command memory.

Manually removed `versionId` from the production adapter's request and
ran `cargo test -p buzz-deletion --lib
historical_claim_protects_shared_file_and_bad_claim_aborts_before_deletion`.
The regression failed because the historical outside uploader no longer
protected the file. Restored the adapter before final validation.

Earlier live-lab evidence used the direct command at
`633fdb2a48dce64f904c0077689704f136c722c1`, before this query/storage
update: 38 exclusive files and 300 versions were deleted; 24 shared
files and 10 unrelated files remained. Authenticated downloads returned
404 for all deleted originals and matching hashes for all preserved
originals. That live deletion was not repeated for this update, and does
not attest concurrent-upload safety or complete account erasure.

## Bigger picture

Media tracking:
[BUZZ-415](https://linear.app/squareup/issue/BUZZ-415/delete-user-and-owned-agent-media-and-storage-objects).
Deleted-image UI is separate work:
[BUZZ-727](https://linear.app/squareup/issue/BUZZ-727/show-a-clear-unavailable-state-for-deleted-images-in-chat-and-image).
Related: #9353. This replaces the media portion of #9329 and #9355;
those branches remain intact.

Generated with Codex

---------

Signed-off-by: Ravneet Arora <rarora@squareup.com>
Signed-off-by: dessert <7d616e7e143e5d408159614dccff1371350a1c1bd36c8de838a45ece5aca0aca@buzz.block.builderlab.xyz>
Co-authored-by: dessert <7d616e7e143e5d408159614dccff1371350a1c1bd36c8de838a45ece5aca0aca@buzz.block.builderlab.xyz>
Co-authored-by: salad <7be12d8db721c3c6d5feccf11f8389e39c6b4b717dc6aa7ce30fc80e45e8788f@buzz.block.builderlab.xyz>
This commit is contained in:
ravarora2
2026-11-16 13:13:39 -05:00
committed by GitHub
parent 63f1d6918c
commit 65b566ca72
28 changed files with 3580 additions and 575 deletions

View File

@@ -1,9 +1,14 @@
# Run and recover a dummy user-deletion workflow
# Run and recover a user-deletion workflow
This workflow tests orchestration using real PostgreSQL rows and dummy actions.
It never gates a real account or deletes user data. Submit still creates an
artificial inventory: B (participant), then C (former participant). Only `demo:`
targets are accepted. Owned communities and production fencing are future work.
The workflow runs a placeholder account gate, **real media cleanup**, then
placeholder community actions. Completion does not mean the whole account has
been erased. Media cleanup requires `--delete` and writers to remain stopped;
the placeholder gate does not stop uploads for you. Use a disposable database
and versioned storage bucket when testing.
Submit with `--pubkey` to discover current memberships. Legacy demo intake
remains available for inspecting orchestration rows, but its synthetic target
cannot execute the real media handler. Owned-community execution is unsupported.
## Code map: worker, policy, and persistence
@@ -15,7 +20,7 @@ there is no additional service or database-side workflow function.
| --- | --- |
| `buzz-deletion/src/user.rs` | Parse command arguments, call the user/shared stores or worker, print results |
| `buzz-deletion/src/user/worker.rs` | Claim, heartbeat, call transition, dispatch handler, repeat, release |
| `buzz-deletion/src/user/handlers.rs` | Dummy actions; save start/result/failure through the shared store |
| `buzz-deletion/src/user/handlers.rs` | Dispatch real media or placeholder actions; save outcomes through the shared store |
| `buzz-deletion/src/user/transition.rs` | `UserDeletionTransition.get_next_stage`: recover or choose the next saved position |
| `buzz-deletion/src/user/workflow.rs` | Allowed user stages, result-based branching, community-progress reconstruction |
| `buzz-db/src/store/entity_deletion/mod.rs` | Shared store definition and exports; no stage policy |
@@ -25,9 +30,9 @@ there is no additional service or database-side workflow function.
| `buzz-db/src/store/entity_deletion/stages.rs` | Save handler outcomes and commit stage transitions atomically |
| `buzz-db/src/store/user_deletion/mod.rs` | User-specific store definition and exports |
| `buzz-db/src/store/user_deletion/requests.rs` | Submit user requests and validate user inventory during approval |
| `buzz-db/src/store/user_deletion/inventory.rs` | Demo target checks, B/C inventory generation, and user inventory validation |
| `buzz-db/src/store/user_deletion/inventory.rs` | Validate approved inventory and construct handler inputs |
The common store does not know the names `gate_user`, `purge_db`, or
The common store does not know the names `gate_user`, `purge_media`, `purge_db`, or
`purge_agents`. `UserDeletionTransition` supplies a synchronous decision function
to `EntityDeletionStore.transition_stage`. The store locks the parent and loads
history, invokes that function while still holding the lock, checks the returned
@@ -45,7 +50,7 @@ User submission and inventory interpretation are deliberately separate from
common workflow storage, even though they use the same tables. User approval
runs its inventory validator inside the common approval transaction. Future
real PostgreSQL deletion operations belong in the user-specific database folder;
the current handlers still perform no real deletion. Existing community deletion
only the media handler currently performs real deletion. Existing community deletion
continues using its existing implementation.
## The execution contract
@@ -112,7 +117,8 @@ The version-1 workflow rules are:
| Stage | Allowed outcome | Runtime choice |
| --- | --- | --- |
| `gate_user` | Enter communities | Select the first uncovered community |
| `gate_user` | `purge_media` | Always enter request-wide media cleanup |
| `purge_media` | Enter communities | After saved success, select the first uncovered community |
| `purge_db` | `purge_agents` or community complete | Read saved boolean `result.has_agents` |
| `purge_agents` | Community complete | Mark this community covered |
@@ -142,163 +148,129 @@ detached renewal task survives cancellation. Generation checks reject stale
workers' status, result, transition, heartbeat, and release writes.
This is one request at a time through an explicit CLI command. There is no relay
scheduler or automatic retry daemon. Real handlers will need idempotent or
reconciled external actions: a crash after an external action but before saving
scheduler or automatic retry daemon. The media handler rescans on retry and treats absent versions as already removed;
external actions still need idempotence or reconciliation: a crash after an external action but before saving
its result may repeat that handler.
## Prepare a local test
## Run against disposable test resources
Follow [the intake guide](operator-user-deletion-intake.md) to build the binary
and migrate a fresh disposable database. The commands below use its container
`buzz-user-deletion-intake` and database `buzz`. Keep all commands in one shell.
These commands need PostgreSQL only, not a relay, Redis, or storage credentials.
Build `buzz-admin`, configure `DATABASE_URL` and the `BUZZ_S3_*` variables, and
apply the schema using the operator procedure in [database.md](database.md).
Use a real test public key and versioned test bucket. Stop every writer before
running with `--delete`; neither the dummy gate nor a database lease prevents
new uploads. Never point these examples at a live account for a smoke test.
The direct command uses the same media implementation without creating a workflow:
```bash
./target/debug/buzz-admin user-deletions media-batches --pubkey "$TEST_PUBKEY" --read-only
./target/debug/buzz-admin user-deletions media-batches --pubkey "$TEST_PUBKEY" --delete
```
To exercise the persisted workflow:
```bash
TARGET="demo:workflow-$(date +%s)"
REQUEST_JSON=$(./target/debug/buzz-admin user-deletions submit \
--target "$TARGET" --requested-by operator-a)
--pubkey "$TEST_PUBKEY" --requested-by operator-a)
REQUEST_ID=$(printf '%s\n' "$REQUEST_JSON" | jq -r '.id')
INVENTORY_DIGEST=$(printf '%s\n' "$REQUEST_JSON" | jq -r '.inventory_digest')
./target/debug/buzz-admin user-deletions approve "$REQUEST_ID" \
--approved-by operator-b --inventory-digest "$INVENTORY_DIGEST"
```
Expected after approval: parent `approved`, one approval, **zero stage rows**.
Define a helper to inspect the actual tables after each command:
```bash
show_rows() {
docker exec buzz-user-deletion-intake psql -X -U buzz -d buzz -c "
SELECT target, status, lease_owner, lease_generation, lease_expires_at,
heartbeat_at, retry_count, next_attempt_at, last_error, completed_at
FROM entity_deletion_requests WHERE id = '$REQUEST_ID';
SELECT id, stage, target_community_id, status, is_current,
started_at, finished_at, metadata_json, last_error
FROM entity_deletion_stage_history WHERE request_id = '$REQUEST_ID'
ORDER BY started_at NULLS LAST, id;
SELECT approved_by, approved_at, inventory_digest
FROM entity_deletion_approvals WHERE request_id = '$REQUEST_ID'
ORDER BY approved_at, id;"
}
show_rows
```
## Advance one stage at a time
Run the same command each time, then inspect the tables:
```bash
./target/debug/buzz-admin user-deletions run "$REQUEST_ID" --next-step
show_rows
./target/debug/buzz-admin user-deletions inspect "$REQUEST_ID"
./target/debug/buzz-admin user-deletions run "$REQUEST_ID" --next-step --delete
./target/debug/buzz-admin user-deletions inspect "$REQUEST_ID"
./target/debug/buzz-admin user-deletions run "$REQUEST_ID" --delete
```
Each invocation executes one handler, processes its saved result through
`get_next_stage`, and releases ownership. It leaves the successor pending and
current. The final invocation marks the request completed instead.
Approval creates no stages. The first run completes the dummy gate and leaves
`purge_media` pending. The second run performs media cleanup and advances to
community placeholders (or finishes if there are no communities). Omitting
`--delete` at media saves a retryable failure without deleting anything. Media
failure keeps the same stage current; no community action runs before media
succeeds. Resume after the saved retry deadline using the same request ID.
A saved completed media stage is transitioned without running media again.
Starting with a newly approved request, expect:
`--next-step` executes one handler, transitions, and releases the lease. Without
it, an invocation executes up to 100 handlers. Workflow stdout is one inspection
JSON document; media's file report goes to stderr. The direct command prints the
file report on stdout. Each file has its hash, filename when present,
keep/delete decision, versions, and outcome counts; uploader lists are omitted.
| Invocation | Handler completed | Current stage after the command |
| --- | --- | --- |
| 1 | `gate_user` | B `purge_db`, pending |
| 2 | B `purge_db` | B `purge_agents`, pending |
| 3 | B `purge_agents` | C `purge_db`, pending |
| 4 | C `purge_db` | C `purge_agents`, pending |
| 5 | C `purge_agents` | None; request completed |
`--fail-stage purge_db`, `--stage-delay-ms`, and `--demo-no-agents-in` exercise
placeholder failures and branching only. They do not simulate media success.
An injected community failure preserves the same retry semantics as before.
Ctrl-C releases the worker lease; after an abrupt kill wait for lease expiry.
All earlier rows remain completed and non-current. Every command releases the
worker lease. Re-running a completed request is read-only. If a handler fails,
the same row remains failed and current; the command exits 1 with a saved retry
deadline instead of advancing past the failure.
## Media discovery and remaining limits
To finish the remaining workflow in one command, omit `--next-step`:
The target set is the human and directly owned agents across communities.
Candidate hashes come from `media_uploaders`, `media_uploaded` audit entries,
and storage upload claims. A bounded database query combines candidate discovery
with outside-uploader classification. Storage-only candidates receive the same
hash-restricted database check in batches. Current membership is not a safe
history filter: relay membership rows can be deleted on departure.
```bash
./target/debug/buzz-admin user-deletions run "$REQUEST_ID"
show_rows
Sharing checks span all communities for the selected hashes. Any outside
uploader in either database source or an upload-record version protects the
file. No per-file owner-list query is made.
Storage discovery scans `_uploads/` for target claims, then reads candidate
claims in a second `_uploads/` listing to protect outside claims encountered
before a target claim. Blob and thumbnail versions are listed by `{hash}.`
prefix, never by an empty bucket prefix. A separate `_meta/` listing covers
sidecars, including ones whose community is absent from current membership or
upload claims. Unrelated Git objects and unrelated blobs are not listed.
The metadata namespace scans remain proportional to their namespace sizes.
All evidence and exact version IDs are collected before deletion begins.
Each listing is bounded to 100,000 pages of at most 1,000 entries. The disposable
in-memory inventory has a 128 MiB accounting budget and a 250,000-entry cap
across candidates, filenames, object versions, and listing markers. Accounting
includes inline data, string bytes, and a conservative 256-byte tree/allocator
allowance per entry. Individual fields and serialized version records are
limited to 16 KiB. The budget is not a process RSS limit: bounded listing/report
pages and database/HTTP clients allocate separately. It replaces the former
1 GiB disk inventory, so large jobs may reach capacity sooner. Exhausting a
limit aborts before mutation, with a capacity error; no partial inventory is
used for deletion. Retries rebuild discovery from PostgreSQL and storage.
Unversioned exclusive objects also abort. Upload claim objects are deleted
last, and the target's database uploader rows are removed only after that
file's storage processing succeeds, so a partial failure can be retried.
Shared files retain storage claims and audit history, even after the target's
uploader rows are removed. Those historical claims can protect a blob after
both uploaders have left; claim retirement is not implemented here. A bare blob
with no surviving attribution cannot be assigned to a user by this handler.
The result always reports `account_erasure_complete: false`.
## Index rollout
Migration 0092 adds uploader/hash and hash/uploader indexes to `media_uploaders`
and equivalent partial indexes for `media_uploaded` audit entries. Existing
community keys remain unchanged. Apply schema before deploying the cleanup code.
The migration builds missing indexes under a 1-second lock timeout and a
5-second statement timeout and verifies pre-existing definitions and validity.
It does not refuse populated tables merely because they contain rows.
Large deployments with auto-migration disabled can prebuild the exact indexes
outside a transaction, following [thread-window-deployment.md](thread-window-deployment.md):
```sql
CREATE INDEX CONCURRENTLY idx_media_uploaders_actor_hash
ON public.media_uploaders (pubkey, sha256);
CREATE INDEX CONCURRENTLY idx_media_uploaders_hash_actor
ON public.media_uploaders (sha256, pubkey);
CREATE INDEX CONCURRENTLY idx_audit_media_actor_hash
ON public.audit_log (actor_pubkey, object_id) WHERE action = 'media_uploaded';
CREATE INDEX CONCURRENTLY idx_audit_media_hash_actor
ON public.audit_log (object_id, actor_pubkey) WHERE action = 'media_uploaded';
```
Ordinary runs have an internal budget of 100 handler calls per invocation.
There are no `--max-stages` or `--pause-after-handler` options. A crash can still
leave a completed current row before its transition; the next run processes
that saved result before executing the next unfinished handler.
## Test runtime branching
Submit and approve a new request using the first block. Then:
```bash
./target/debug/buzz-admin user-deletions run "$REQUEST_ID" \
--executor-id worker-a \
--demo-no-agents-in 00000000-0000-0000-0000-00000000000c
show_rows
```
Expected: four completed rows: gate, B DB, B agents, C DB. C's DB result contains
`has_agents: false`; its saved transition is `community_complete`. There is no
C agents row. The flag simulates a runtime observation in the dummy handler; it
does not change the saved inventory or transition map. It may be repeated.
To inspect branching step by step, submit and approve another request. Run once
with `--next-step` to finish the gate, then run with
`--next-step --demo-no-agents-in 00000000-0000-0000-0000-00000000000b`.
B DB completes and transitions directly to C DB. Resume without the flag: the
saved B decision remains unchanged, and no B agents row appears.
## Test failure and retry
On a new approved request:
```bash
./target/debug/buzz-admin user-deletions run "$REQUEST_ID" \
--executor-id worker-a --fail-stage purge_db
echo "Exit code: $?"
show_rows
```
Expected exit 1. Gate has transitioned; B DB is failed and current. The parent
is `retry_wait`, with error, retry count 1, and `next_attempt_at` 30 seconds later.
The handler saved this outcome; `get_next_stage` returned `WaitUntil`, and the
worker released ownership. An immediate retry is refused.
After the saved deadline:
```bash
./target/debug/buzz-admin user-deletions run "$REQUEST_ID" --executor-id worker-b
show_rows
```
The same B DB row resumes with its original first start time. The request
finishes. Successful transition clears the parent retry state.
## Observe heartbeat and process interruption
On a new approved request:
```bash
./target/debug/buzz-admin user-deletions run "$REQUEST_ID" \
--executor-id worker-a --stage-delay-ms 60000
```
Inspect from another terminal using the same database/request. Heartbeat and
expiry advance every ten seconds. A competing worker is refused. Ctrl-C stops
execution and releases ownership; the interrupted row remains current. After
an abrupt process kill, wait for the saved lease expiry before running another
worker. It resumes the same unfinished row with a higher generation.
## Rollout, recovery, and retained demo data
Migrations 0069–0070 are additive. The serving relay does not schedule these
requests; only an operator explicitly running the demo CLI executes them.
The Helm chart defaults `migrate.autoMigrate=true`. After these migrations are
applied, rolling back to a binary that does not contain them fails at startup
with sqlx `VersionMissing`. For this rollout, recover by rolling forward to a
corrected binary that retains migrations 0069–0070. Do not remove migration
records or change their checksums to force an older binary to start. An older
binary deployed with auto-migration disabled requires a separately verified
schema-compatibility plan; it is not the recovery procedure assumed here.
Demo request rows, approval evidence, and stage history are deliberately retained
for inspection. This scaffold has no cleanup command or automatic retention job.
Then apply the migration, which verifies the indexes without rebuilding them.
A failed concurrent build must be inspected and repaired before retrying.
These additive nonunique indexes remain compatible with old relay writes.
The normal sqlx migration-version rollback constraints still apply: recover
with a corrected binary retaining the migration history, rather than deleting
migration records or changing checksums. Workflow requests and history are
retained for inspection; this scaffold has no automatic retention job.