Commit Graph

7 Commits

Author SHA1 Message Date
Luke Tornquist
7e94503fe9 Stop using the unused delivery_log and subscriptions tables (#9746)
## Summary

`delivery_log` and `subscriptions` came with the initial schema for a
delivery feature that was never built. No code has ever written to them.
This PR removes every reader, writer, partition-manager entry and
deletion selection, so a follow-up contract migration can drop both
tables (`docs/database.md` Rule 5: drop only after the release that
stops using a table is fully deployed).

- **Partition manager:** manages `events` only. It no longer creates or
audits `delivery_log` partitions.
- **User deletion:** the content, account and profile handlers no longer
select, delete or recheck rows in either table.
- **Community deletion:** both tables move from
`EXPECTED_SCOPED_TABLES`/`PURGE_SCOPED_TABLES` to a new
`RETIRING_SCOPED_TABLES` list. The catalog accepts each one present or
absent. The purge deletes its rows only while it exists.
`validate_approved_schema` accepts a frozen retiring table that has
since been dropped, and no other missing table. Without this, every
community deletion would fail its exact catalog check once the tables
are gone.
- **Docs:** a short "Retiring a tenant-owned table" section in
`docs/database.md`, plus partition-monitoring and cleanup docs.

The tables, their schema files, `.pgschemaignore` entries and the
partition primary-key lint exception stay until the drop migration.

### Rollout

1. Deploy this release to every relay, deletion executor and operator
CLI. Older binaries fail community deletion's exact catalog check after
the drop.
2. Then ship the drop migration and remove the schema entries. Operators
with external tooling that expects `delivery_log` to exist must update
it first.

The partition audit stops emitting `buzz_partition_audit_*` series with
`table="delivery_log"`. Alerts keyed on that label will go quiet.

### What got simpler

Two tables' worth of code paths are gone: partition management, the
audit, and five deletion handlers stop special-casing them. The
follow-up removes the tables and the `RETIRING_SCOPED_TABLES` entries.

### Testing

On a remote workstation at `3675ff17`: `cargo fmt --check`, `clippy -D
warnings` for buzz-db, buzz-deletion and buzz-relay (all targets), unit
tests for buzz-db (lib and tests), buzz-deletion and buzz-relay bins,
and `scripts/postgres-test-run.sh` for buzz-db
partition/deletion/migration tests (294 passed) and all buzz-deletion
Postgres tests (44 passed). The new tests cover: retiring tables purged
and verified while present; a request inventoried before a real `DROP
TABLE` still purges and verifies; `validate_approved_schema` tolerates
only retiring tables vanishing.

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

---------

Signed-off-by: Luke Tornquist <tornquist@squareup.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 22:19:15 -05:00
ravarora2
69ea27343c Fix media deletion’s community ownership and share agent discovery (#9670)
## Summary

Deleting a human must preserve an agent's uploads in communities where
someone else owns that agent or its profile is missing. Media cleanup
now carries community/key pairs through database and storage discovery,
shared-file decisions, and uploader-row deletion.

Media, content, account and profile cleanup share one direct-agent
discovery utility. Each caller retains its previous limits and
transaction behavior. Media discovers ownership once per invocation,
including retries, and uses a hash set for storage matching. The report
shape stays unchanged. The operator guide explains that community/agent
pairs have no separate cap and sit outside the inventory budget. The
discovery helper documents that global, identity-grouped discovery
requires `lock: false` because PostgreSQL cannot combine `GROUP BY` with
`FOR SHARE`.

Run a read-only preview first, then keep writers stopped throughout
deletion. Reverting the binary restores the old cross-community
selection bug; it cannot restore deleted objects.

### Related issue

Follow-up to the merged media handler in #9365 and the
content/account/profile handlers in #9363, #9364 and #9580. No duplicate
of this ownership correction was identified.

### Testing

Exercised the rebuilt `buzz-admin user-deletions media-batches --pubkey
<fixture-human> --read-only`, then `--delete`, against isolated
PostgreSQL and versioned MinIO. Preview changed neither rows nor
storage. Exclusive versions and in-scope uploader rows were deleted;
shared originals, thumbnails and historical versions survived. All four
handler commands agreed before and after a between-invocation ownership
change. Failure followed by retry used fresh ownership, and repeat
deletion removed zero versions.

Compared the production candidate SQL with the pre-PR query on about
50,000 local upload/audit rows. With 9,999 agents, execution took
120–185 ms per 500-row page versus 38–83 ms before community matching.
Three runs per query; this excludes planning, Rust preparation and
storage operations. The added per-version ownership queries are removed
entirely.

Full database/deletion/admin package runs passed (339 tests). The
PostgreSQL database/deletion run passed 904 tests; after strengthening
the retry fixture, the full deletion PostgreSQL package passed all 45
tests. The retry case retains ownership in another community, and media
tests assert exactly one ownership lookup per invocation.

Local `just test` completed with one failure in the unchanged relay
logging test `composition_log_does_not_leak_issuer_url` (expected
warning not captured); all other test groups passed. Two pre-push
attempts failed in unchanged ACP tests: first a launch timeout, then
credential tests using Git 2.40 where 2.46+ is required. All four
credential integration tests passed with Git 2.54; the full pre-push
retry was stopped at the author’s request to skip local checks and push.
Local `just ci` was also stopped before completion. Neither interrupted
run is a full pass; local hooks were skipped for publication.

The follow-up for the optional review comments changes documentation
only. Its statements were checked against the query and all five
production callers; `git diff --check` passed. Runtime suites were not
repeated for this follow-up.

Human local acceptance remains pending.

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>
2026-11-19 18:23:24 -05:00
ravarora2
d9c3f4e99e Remove personal workflow data and missed event copies (#9675)
## Summary

User content cleanup left private hide-list snapshots, saved workflow
inputs and notes, unused automation, and some delivery copies behind.
This extends the existing per-community content handler to remove them
with the same preview, ownership and retry checks.

- Delete trusted-relay hidden-DM snapshots and author-signed historical
file-metadata events (kind 1063).
- Clear recorded event-trigger text/emoji, authenticated manual inputs,
and the recorded approver's note while preserving the rest of each run
or approval.
- Delete unused workflow database definitions and their schedule claims
together. Any run, approval or linked claim protects the definition. The
entire group must fit the requested batch size, capped at 100 rows, or
planning refuses before mutation.
- Delete delivery logs under surviving subscriptions before erasing
their source events; reject newly arrived dependent rows before
committing. Check the whole event batch with hashed membership to avoid
repeated work across unrelated delivery history.

Run deletion offline with the relay, workflow engine and external
writers stopped. Shared history, canvases, artifacts, Git data and
device registrations remain outside these additions. Retained runs can
subsequently read the cleared inputs; this does not cancel them or claim
complete account erasure. Existing signed kind 30620 event cleanup is
unchanged.

This is an application-only change against existing tables. It adds no
migrations, indexes, triggers, functions or foreign keys. Existing
per-statement timeouts and community write admission remain in use.

### Related issue

Related: #9353. Extends the content handler in #9363. Shared workflow
ownership policy remains separate from these personal-field deletions.

### Testing

Ran the rebuilt `buzz-admin user-deletions content-batches --community
<fixture-community> --pubkey <fixture-user> --batch-size 100` against
disposable PostgreSQL 17 fixtures with 100 events, 500,000 unrelated
delivery logs, and 9,999 small communities. `--read-only` selected 100;
`--delete` removed 100 in 0.39 seconds locally; a second `--delete`
selected zero. All 500,000 unrelated same-community delivery rows
survived.

EXPLAIN used hashed membership under both custom and generic plans.
Independent review also exercised stale statistics. Removing the planner
safeguard made the regression fail at the executor's actual 3-second
timeout. The late-copy test still refuses deletion and preserves the
source until retry can include the new copy.

Independent agent review completed with no remaining blockers. Earlier
command validation on the original patch exercised all agreed additions:
preview nine operations, delete nine, retry zero, with whole-row
preservation checks for the other community, shared canvas, surviving
subscriptions, workflow output/provenance, and other approvers' notes.

The repository-wide `just ci` run passed static checks, then stopped on
two timeouts in unchanged `buzz-agent` OAuth tests. Both cases passed a
serial recheck. The subsequent normal push hooks passed, including the
complete Rust unit lane and Tauri checks. Later app build/test recipes
were not reached; the full local CI command is not claimed green.

Human command verification is pending, so this PR remains draft. On
disposable fixtures, run the same preview/delete/retry sequence and
verify that only the planned rows/fields change.

Generated with Codex

---------

Signed-off-by: maincourse <37ce551b493d4a998caf030929c47bce0b6a0e43f1178b3a63c4151d7c16b76e@buzz.block.builderlab.xyz>
Co-authored-by: maincourse <37ce551b493d4a998caf030929c47bce0b6a0e43f1178b3a63c4151d7c16b76e@buzz.block.builderlab.xyz>
2026-11-19 16:13:31 -05:00
Logan Johnson
50cfc54337 Apply the private-to-open rule in update_channel too (#9581)
## Summary
- Follow-up to https://github.com/block/buzz/pull/9307, which made the
relay refuse to open a private channel that has, or once had, any member
other than the sender and the sender's own agents. That rule lived only
in the channel metadata edit path (kind:9002). The store's other
channel-settings function, `update_channel`, could still open such a
channel.
- Now both paths apply the same rule, because it runs in the one
function that writes channel settings for both. `update_channel` takes
the authenticated sender so it can decide the rule. Today only tests
call `update_channel`, so nothing user-visible changes; the gap is
closed before any real caller arrives.
- The user-deletion executor doc now says what the rule needs from a
purge: if a purge keeps any of a user's messages in a channel, it must
also keep that user's membership row there, marked removed. The relay
finds former members only through those rows, so dropping the row would
let the channel be opened and its history, those messages included, be
made public.

## Details
- The check moved out of `apply_channel_metadata_event` into
`update_channel_on`, which both paths call. It still runs under the
membership lock that a visibility change takes, so members cannot be
added between the check and the commit.
- One ordering change: a single kind:9002 that opens a private channel
with other members, archives it and sets `auto_join` to true now gets
the `auto_join` refusal instead of the private-to-open one, because the
`auto_join` check now runs first. Both refuse, and nothing is stored
either way.
- This PR also carries doc-comment wording that was reviewed on
https://github.com/block/buzz/pull/9307 but not merged with it: the
comments now give the reason, that opening publishes the existing
history, so removed members count.
- Every call site of `update_channel` is a test, and each now passes the
channel owner as sender.

### Related issue
Follow-up to https://github.com/block/buzz/pull/9307 (review notes on
its store gap and on purge).

### Testing
- New Postgres test
`update_channel_refuses_opening_a_private_channel_with_other_members`:
opening fails for both the owner and the other member as sender, while
the other member is current and after they are removed, and the channel
stays private. A channel that holds only the owner opens.
- The existing kind:9002 test `private_to_open_needs_no_other_members`
still passes. Both tests fail when the check is removed.

buzz-review-completed

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

---------

Signed-off-by: Logan Johnson <loganj@squareup.com>
Co-authored-by: Larry <627498bd4bd1f281a16431e3c6cce3b5c25b6692798c78672298aefbf2f8f8b5@buzz.block.builderlab.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 11:52:27 -05:00
ravarora2
a8f55e637a Add real content cleanup for users and agents (#9363)
## Summary

Add one shared content-cleanup handler for a user and their agents in a
specified community. Preview is the default; deletion commits bounded
batches and preserves other people's replies and reactions.

Agent selection requires ownership by this user in the target community.
Ownership elsewhere is insufficient. The start record reports missing or
conflicting ownership, and every batch rechecks the selected agents
before deleting anything.

### Reply preservation and live writes

Keep erased placeholders for messages needed by surviving reply chains
or reactions. Plain links and quotes may point to a deleted message;
their signed source messages stay unchanged. Nested reply ancestry uses
the existing parent/root indexes. No new permanent index or schema
migration is added.

Replies without thread metadata use the existing tags GIN index to
search for each selected message ID in lowercase and uppercase. The
shared marker parser checks which matches are actual replies. Mixed-case
references without thread metadata may be missed; metadata-backed
replies use binary IDs and remain covered. Planning and hard-delete
rechecks each run the probes in one SQL statement with a one-second
timeout and a 10,000-match limit. A reply matching several probes counts
several times. Exceeding either bound aborts cleanup. This avoids the
broad search through unrelated replies; production-scale performance has
not been measured.

Each batch revalidates its work under the community lock.
Transaction-local timeouts apply before locking, including after
reconnect. Planned output is written before locking and receipts after
commit. A changed row, owner, or surviving reply aborts the batch; retry
replans remaining work.

Normal reply insertion retains the added indexed parent-existence check.
This changes the live write path and prevents saving a reply whose
parent disappeared while the writer waited. Erased messages appear
unavailable in moderation lookups instead of carrying an empty author
key.

### Included content

Supported authored events and owned reaction, subscription and
notification records are included. Signer-owned personas (30175), team
definitions/catalogs (30176/30178), emoji sets/entries (30030/30180),
and project groupings (30621) include shared publications and stored
revisions. Deleting a project grouping leaves member repositories, their
announcements/state and name mappings intact.

### Testing

Local runtime tests and hooks are skipped at the owner's request. Source
review, Rust formatting and diff checks were completed. The updated
revision requires CI validation; earlier test runs and index benchmarks
do not validate this replacement. Regression cases cover ownership
conflicts/transfers, missing thread records, nested ancestry, plain
links, late replies, lookup limits, reconnects, blocked output, and
unavailable moderation targets.

No new manual relay or UI test was run for this revision. Account
blocking remains unfinished; these changes do not establish complete
online account erasure.

### Scope and compatibility

**Deferred to a separate follow-up PR to keep this PR smaller:** the
following work will extend **the same content cleanup handler**
(`purge_content` / `content-batches`), rather than introduce another
handler:

- Workflow database definitions, runs, traces, approvals, schedules and
copied inputs; some source events are already covered here.
- Canvas revision events and current canvas text.
- Artifact events, revision records and current heads.
- Channel topics and purposes.
- Gift-wrapped DMs and additional huddle history that require different
attribution rules.
- Git issues, PRs, patches, comments/status and required repository
metadata, subject to preservation rules. Repositories themselves stay.
- Remaining stored workflow, delivery and projection copies outside this
PR's current coverage.

These categories remain unfinished. Deferring them is not a permanent
retention decision or a claim of complete content erasure. The follow-up
must settle shared-document and mixed-owner workflow behavior and test
surviving content.

Profiles and managed-agent identity definitions belong to profile
cleanup. Memberships, personal preferences and access belong to account
cleanup. Media cleanup was implemented separately in #9365 and is now on
main. Deletion requests, approvals, progress/history and replay
protection stay.

The workflow orders account gating, global media cleanup, then
per-community content cleanup. Real requests still stop at the
unfinished account gate; demos simulate every stage without deletion.
Other unfinished real workflow stages fail explicitly. Existing demo
requests saved with `purge_db` must be recreated for `purge_content`.

Bulk client notifications remain separate work. Open views may retain
cached content and counts until refresh. The existing missing
reply-count button after refresh and ordinary UI access when the root is
deleted are outside this PR.

Replaces the content portion of #9355 and #9332. Related prior handler:
#8698.

Generated with Codex

---------

Signed-off-by: Ravneet Arora <rarora@squareup.com>
Co-authored-by: maincourse <37ce551b493d4a998caf030929c47bce0b6a0e43f1178b3a63c4151d7c16b76e@buzz.block.builderlab.xyz>
2026-11-17 10:17:45 -05:00
ravarora2
65b566ca72 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>
2026-11-16 13:13:39 -05:00
ravarora2
4250014bae Run user deletion through saved stage transitions (#8520)
## Summary

An operator can submit, approve, and run a synthetic user-deletion
request through a durable workflow. The actions print messages; they do
not gate real users or delete data. The inventory contains artificial
participant and former-participant communities.

The worker calls one transition function, `get_next_stage(lease,
previous_stage_id)`. It receives a full stage row, passes it to the
handler, then asks again. All branching, community tracking,
initialization, and recovery live behind that function. Existing
community-deletion execution is unchanged.

### Related issue

Builds on merged #8496 and targets `main`. Inventory, separate approval
records, and the dummy executor remain together in this PR.

### Execution design

```text
approve → save approval; create no stages
run → claim request
    get_next_stage(lease, None) → full stage row
    handler(lease, row) → persist status and result
    get_next_stage(lease, Some(row.id)) → next row / Finished / WaitUntil
    repeat, then release ownership
```

- **Approval:** bind an operator's decision to the saved inventory
digest. Approval creates no execution rows. Operator names remain
self-asserted demo input.
- **Initialization:** claiming preserves the parent lifecycle. The first
transition creates `gate_user` and changes `approved` to `running`
atomically. A crash after claim but before initialization can safely
restart.
- **Handler:** read `metadata_json.inputs`, mark the row running, and
save its result or failure. A successful action leaves its row
`completed` and `is_current = true`. This is a durable transition
waiting to be processed.
- **Transition:** lock the parent, validate ownership, reload history
and the handler's saved result, and choose an allowed destination. Clear
the old current flag, save the decision, and insert the successor with
its inputs in one transaction. Terminal transitions complete the parent
instead. An insertion failure leaves the completed old row current.
- **Recovery:** `previous_stage_id` identifies the handler that just
returned; it must belong to the request. A restarted worker passes
`None` and finds the saved current row. If that row is completed,
transition it without repeating its action. If the switch already
committed, return the saved successor. Repeated calls never apply the
old transition twice.
- **Progress:** reconstruct covered communities from saved decisions and
the approved inventory. Each stage records its predecessor ID, so
reconstruction does not depend on timestamp ordering. Missing current
state in a started request, disconnected history, unknown stages, and
malformed results fail without inventing progress.
- **Ownership:** parent leases last 60 seconds and handlers renew them
every ten seconds. Generation checks reject stale writes. Handler and
renewal futures remain independently polled; renewal cannot prevent a
handler holding the parent lock from committing.
- **Step-by-step testing:** `run --next-step` executes one handler,
commits its transition, and exits with the successor pending. Repeat the
same command to advance again; the final step completes the request. The
former `--max-stages` and `--pause-after-handler` flags are removed.
- **Failure:** the handler saves the current row's error and a 30-second
retry deadline. The transition returns `WaitUntil`; the worker exits and
releases its lease. A later invocation retries the same row. No
background scheduler or automatic retry daemon is added.

The user workflow definition in `buzz-deletion/src/user/workflow.rs`
declares allowed destinations and a decision function per stage.
`gate_user` enters the first uncovered community. `purge_db` reads saved
`has_agents`: true selects `purge_agents`; false completes the community
immediately. Community completion selects the next uncovered community,
or finishes the request when all are covered. No full stage plan is
created upfront. The transition transaction contains no stage-name
comparisons or fixed community count.

Stage metadata stores `inputs`, `result`, `transition`, and
`previous_stage_id`. The parent retains inventory, ownership, retry, and
overall status. Approval evidence stays in `entity_deletion_approvals`.
A completed-current row bridges the two transactions; real handlers will
still need idempotent or reconciled actions if a process dies before
saving its result.

### Code organization

`buzz-deletion/src/user/worker.rs` runs the loop and heartbeat. Sibling
`handlers.rs` executes dummy actions. `transition.rs` defines
`UserDeletionTransition.get_next_stage()`, and `workflow.rs` owns the
user stage rules and community-progress reconstruction. The CLI remains
in `user.rs`.

`buzz-db/src/store/entity_deletion/` contains shared workflow
persistence: a small `mod.rs`, request reads/inspection in
`requests.rs`, approval evidence in `approvals.rs`, ownership in
`leases.rs`, and stage outcomes/atomic transitions in `stages.rs`.
User-specific submission, demo inventory, and inventory validation live
separately in `buzz-db/src/store/user_deletion/{requests,inventory}.rs`;
its `mod.rs` only defines and exports the store.

The worker calls the user transition object, which supplies a
synchronous decision function to `EntityDeletionStore.transition_stage`.
The store locks the parent, reads saved state, invokes that function,
checks the returned operation, and commits its writes. The decision
function performs no SQL or external calls. Reading, deciding, and
writing remain in one transaction; there is no stale-state gap. Shared
storage contains no user stage names or community-routing rules.
User-specific approval validation also runs inside the shared approval
transaction.

This reorganization changes no tables, migrations, stage metadata, or
CLI behavior. Requests using the existing saved-result format continue
to work. `--next-step` still runs one handler and commits its transition
before returning.

### Testing

The walkthrough in
[docs/operator-user-deletion-executor.md](https://github.com/block/buzz/blob/rarora/user-deletion-approval/docs/operator-user-deletion-executor.md)
includes commands, SQL inspection, expected rows, and recovery
boundaries.

Submitted and approved a fresh local request and verified zero stage
rows. Ran `run --next-step` five times. Each call completed exactly one
handler, released ownership, and left its successor pending: B DB, B
agents, C DB, C agents, then request completed. A sixth call left saved
state unchanged. Verified both removed flags are rejected.

Ran `--demo-no-agents-in 00000000-0000-0000-0000-00000000000c` and
verified four completed rows, with no C agents stage.

Injected a DB-stage failure, verified immediate retry refusal, waited
for the real deadline, and resumed the same stage row. Observed
heartbeat renewal and rejection of a competing worker, killed the owned
worker process, waited for its actual lease expiry, and resumed the same
unfinished stage with a new generation. Re-running a completed request
left its saved state unchanged. Repeated the CLI walkthrough after the
file reorganization, including runtime branching and a retry after the
real deadline; a completed request created before the reorganization
remained unchanged.

Mutation-tested the ownership and recovery guards against local
PostgreSQL 17. Reclaiming with the same executor ID rejects
old-generation operations. Independently disabling the ownership
generation check, release generation check, saved-transition/result
comparison, or heartbeat-failure handling made the corresponding test
fail. Restored all four protections afterward. The heartbeat test takes
over the request while its handler is already running.

### Schema and rollout

Unmerged migrations 0069–0070 add inventory and execution fields, widen
request lifecycle states, and create operator-global approval and
stage-history tables. They set five-second lock and thirty-second
statement timeouts; constraint validation has its own transaction. No
triggers, functions, foreign keys, or data backfills are added.
Desired-state and migration catalog parity cover all three tables. The
transition redesign adds no further schema changes.

The serving relay does not schedule these requests. Only the explicit
operator CLI runs them, using PostgreSQL. Only `demo:` targets are
accepted. Real account discovery, user-write fencing, owned-community
handling, and actual deletion remain future work. Verify staging with a
new demo label and the documented commands.

Older draft requests do not have the new stage metadata contract.
Preserve them and create a new demo request for this version; they are
not a supported resume format. Use a fresh database if an earlier draft
applied a different migration checksum. Never alter sqlx migration
checksums. With Helm `migrate.autoMigrate=true` (the chart default), a
relay binary that lacks 0069/0070 fails at boot with sqlx
`VersionMissing` after those migrations are applied. Recovery for this
rollout is a roll-forward: deploy a corrected binary that retains the
migrations. Do not delete migration records or change checksums to force
an older binary to boot. Rolling back with auto-migration disabled
requires a separately verified schema-compatibility plan. Demo requests,
stage history, and approvals are intentionally retained; this scaffold
has no cleanup command or retention job. Recheck migration numbering
before merge.

Generated with Codex

---------

Signed-off-by: Ravneet Arora <rarora@squareup.com>
2026-10-26 10:44:32 -04:00