From d9c3f4e99e9b92ac3e2eb3f4c0f9f9a44e8676a3 Mon Sep 17 00:00:00 2001 From: ravarora2 <130506156+ravarora2@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:13:31 -0500 Subject: [PATCH] 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 --pubkey --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> --- .../content_batches/agents_postgres_tests.rs | 1 + .../content_batches/authored.sql | 26 +- .../content_batches/copies_postgres_tests.rs | 199 ++++++++++++ .../user_deletion/content_batches/execute.rs | 4 + .../user_deletion/content_batches/grouped.rs | 31 +- .../user_deletion/content_batches/mod.rs | 30 +- .../content_batches/postgres_tests.rs | 5 +- .../private_state_postgres_tests.rs | 242 ++++++++++++++ .../user_deletion/content_batches/rows.rs | 13 + .../content_batches/safety_postgres_tests.rs | 16 +- .../schedule_postgres_tests.rs | 135 ++++++++ .../workflow_postgres_tests.rs | 295 ++++++++++++++++++ .../content_batches/workflows.rs | 160 ++++++++++ .../buzz-deletion/src/user/content_batches.rs | 2 +- docs/operator-user-deletion-executor.md | 40 +++ 15 files changed, 1184 insertions(+), 15 deletions(-) create mode 100644 crates/buzz-db/src/store/user_deletion/content_batches/copies_postgres_tests.rs create mode 100644 crates/buzz-db/src/store/user_deletion/content_batches/private_state_postgres_tests.rs create mode 100644 crates/buzz-db/src/store/user_deletion/content_batches/schedule_postgres_tests.rs create mode 100644 crates/buzz-db/src/store/user_deletion/content_batches/workflow_postgres_tests.rs create mode 100644 crates/buzz-db/src/store/user_deletion/content_batches/workflows.rs diff --git a/crates/buzz-db/src/store/user_deletion/content_batches/agents_postgres_tests.rs b/crates/buzz-db/src/store/user_deletion/content_batches/agents_postgres_tests.rs index 5a4589993f..224d96ed15 100644 --- a/crates/buzz-db/src/store/user_deletion/content_batches/agents_postgres_tests.rs +++ b/crates/buzz-db/src/store/user_deletion/content_batches/agents_postgres_tests.rs @@ -371,6 +371,7 @@ async fn owned_agents_share_bounded_batches_and_preserve_other_owners_and_commun "subscriptions" => !owned("owner_pubkey"), "delivery_log" => { !["sub-0", "sub-1"].contains(&row["subscription_id"].as_str().unwrap()) + && !selected.contains(&hex_field("event_id")) } "push_leases" | "push_wake_outbox" => !owned("author"), "operator_listener_outbox" => { diff --git a/crates/buzz-db/src/store/user_deletion/content_batches/authored.sql b/crates/buzz-db/src/store/user_deletion/content_batches/authored.sql index 6a5a3966ed..2e0b0bc93b 100644 --- a/crates/buzz-db/src/store/user_deletion/content_batches/authored.sql +++ b/crates/buzz-db/src/store/user_deletion/content_batches/authored.sql @@ -2,11 +2,31 @@ -- Relay attribution is opt-in: only the supplied trusted signer may use actor/p. SELECT e.* FROM events e WHERE e.community_id = $1 AND (e.pubkey = ANY($2::bytea[]) OR e.pubkey = decode($3, 'hex')) - AND CASE WHEN e.pubkey = decode($3, 'hex') THEN COALESCE( + AND CASE WHEN e.kind = 30622 THEN + -- Hidden-DM state belongs to its viewer, not the relay signer. Require + -- the producer's unambiguous subject shape; never infer it from actor, + -- the first of several p tags, or a client-signed lookalike. + CASE WHEN e.pubkey = decode($3, 'hex') AND e.channel_id IS NULL + AND e.d_tag ~ '^[0-9a-f]{64}$' AND jsonb_typeof(e.tags) = 'array' + AND NOT EXISTS ( + SELECT 1 FROM jsonb_array_elements( + CASE WHEN jsonb_typeof(e.tags) = 'array' THEN e.tags ELSE '[]'::jsonb END + ) tag WHERE jsonb_typeof(tag) <> 'array' OR EXISTS ( + SELECT 1 FROM jsonb_array_elements( + CASE WHEN jsonb_typeof(tag) = 'array' THEN tag ELSE '[]'::jsonb END + ) value WHERE jsonb_typeof(value) <> 'string' + ) + ) + AND jsonb_path_query_array(e.tags, 'strict $[*] ? (@[0] == "d")', '{}'::jsonb, true) + = jsonb_build_array(jsonb_build_array('d', e.d_tag)) + AND jsonb_path_query_array(e.tags, 'strict $[*] ? (@[0] == "p")', '{}'::jsonb, true) + = jsonb_build_array(jsonb_build_array('p', e.d_tag)) + THEN decode(e.d_tag, 'hex') END + WHEN e.pubkey = decode($3, 'hex') THEN COALESCE( (SELECT CASE WHEN t->>1 ~ '^[0-9a-fA-F]{64}$' THEN decode(t->>1, 'hex') END FROM jsonb_array_elements(e.tags) t WHERE t->>0 = 'actor' AND t->>1 IS NOT NULL LIMIT 1), (SELECT decode(t->>1, 'hex') FROM jsonb_array_elements(e.tags) t WHERE t->>0 = 'p' AND t->>1 ~ '^[0-9a-fA-F]{64}$' LIMIT 1), e.pubkey) ELSE e.pubkey END = ANY($2::bytea[]) - -- Only the original message kinds support trusted relay attribution. - AND (e.kind IN (7,9,40001,40002,40003,40004,40005,40006,40007,40008,45001,45002,45003) OR e.pubkey = ANY($2::bytea[])) + -- Only these message kinds and the checked private snapshot support relay attribution. + AND (e.kind IN (7,9,30622,40001,40002,40003,40004,40005,40006,40007,40008,45001,45002,45003) OR e.pubkey = ANY($2::bytea[])) diff --git a/crates/buzz-db/src/store/user_deletion/content_batches/copies_postgres_tests.rs b/crates/buzz-db/src/store/user_deletion/content_batches/copies_postgres_tests.rs new file mode 100644 index 0000000000..2c996fcba0 --- /dev/null +++ b/crates/buzz-db/src/store/user_deletion/content_batches/copies_postgres_tests.rs @@ -0,0 +1,199 @@ +use super::scrub_postgres_tests::{options, setup, PauseAfterPlan}; +use super::*; +use crate::user_deletion::ExecutionMode; +use nostr::{EventBuilder, Kind}; + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn event_batch_deletion_preserves_large_unrelated_delivery_history() { + let (db, c, _, alice, _) = setup().await; + for n in 0..100 { + let event = EventBuilder::new(Kind::Custom(1063), format!("personal metadata {n}")) + .sign_with_keys(&alice) + .unwrap(); + db.insert_event(c, &event, None).await.unwrap(); + } + // Event IDs have no delivery-log index. A per-event dependency probe scans + // this unrelated history 100 times and exceeds the executor's 3s timeout. + sqlx::query( + "INSERT INTO delivery_log(community_id,subscription_id,event_id,error_message) + SELECT $1,'unrelated',decode(md5(g::text)||md5(g::text),'hex'),repeat('x',128) + FROM generate_series(1,500000) g", + ) + .bind(c.as_uuid()) + .execute(db.pool()) + .await + .unwrap(); + // Many tiny tenants make generic-plan estimates underestimate this tenant. + // A plain IN semi join can compare every log to every event after ANALYZE. + sqlx::query( + "WITH tenants AS ( + INSERT INTO communities(id,host) + SELECT gen_random_uuid(),'delivery-'||g||'.example' + FROM generate_series(1,9999) g RETURNING id + ) INSERT INTO delivery_log(community_id,event_id) + SELECT id,decode(repeat('ff',32),'hex') FROM tenants", + ) + .execute(db.pool()) + .await + .unwrap(); + sqlx::query("ANALYZE delivery_log") + .execute(db.pool()) + .await + .unwrap(); + let pool = sqlx::postgres::PgPoolOptions::new() + .connect_with( + (*db.pool().connect_options()) + .clone() + .options([("plan_cache_mode", "force_generic_plan")]), + ) + .await + .unwrap(); + let db = crate::Db::from_pool(pool); + let mut opts = options(c, &alice); + opts.batch_size = 100; + for (mode, expected) in [ + (ExecutionMode::ReadOnly, 100), + (ExecutionMode::Delete, 100), + (ExecutionMode::Delete, 0), + ] { + let result = db + .user_deletion_store() + .run_message_batches(&opts, mode, None, &mut Vec::new()) + .await + .unwrap(); + assert_eq!(result.items, expected); + } + let events: i64 = sqlx::query_scalar("SELECT count(*) FROM events WHERE community_id=$1") + .bind(c.as_uuid()) + .fetch_one(db.pool()) + .await + .unwrap(); + assert_eq!(events, 0); + let logs: i64 = sqlx::query_scalar("SELECT count(*) FROM delivery_log WHERE community_id=$1") + .bind(c.as_uuid()) + .fetch_one(db.pool()) + .await + .unwrap(); + assert_eq!(logs, 500_000); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[ignore = "requires Postgres"] +async fn historical_file_publications_and_late_delivery_copies_follow_source_scope() { + let (db, c, _, alice, bob) = setup().await; + let other = db + .ensure_configured_community(&format!("copies-{}.example", Uuid::new_v4())) + .await + .unwrap() + .id; + let source = EventBuilder::new(Kind::Custom(1063), "personal file description") + .sign_with_keys(&alice) + .unwrap(); + let survivor = EventBuilder::new(Kind::Custom(1063), "another publisher's description") + .sign_with_keys(&bob) + .unwrap(); + for community in [c, other] { + db.ensure_user(community, bob.public_key().as_bytes()) + .await + .unwrap(); + db.insert_event(community, &source, None).await.unwrap(); + db.insert_event(community, &survivor, None).await.unwrap(); + sqlx::query( + "INSERT INTO subscriptions(community_id,id,owner_pubkey) VALUES($1,'survivor',$2)", + ) + .bind(community.as_uuid()) + .bind(bob.public_key().as_bytes().as_slice()) + .execute(db.pool()) + .await + .unwrap(); + } + let (planned_tx, planned_rx) = tokio::sync::oneshot::channel(); + let (resume_tx, resume_rx) = std::sync::mpsc::channel(); + let store = db.user_deletion_store(); + let opts = options(c, &alice); + let task = tokio::spawn(async move { + let mut writer = PauseAfterPlan { + record: "delete_start", + line: Vec::new(), + planned: Some(planned_tx), + resume: resume_rx, + }; + store + .run_message_batches(&opts, ExecutionMode::Delete, None, &mut writer) + .await + }); + planned_rx.await.unwrap(); + for community in [c, other] { + for event in [&source, &survivor] { + sqlx::query("INSERT INTO delivery_log(community_id,subscription_id,event_id,error_message) VALUES($1,'survivor',$2,'copied payload')") + .bind(community.as_uuid()).bind(event.id.as_bytes().as_slice()) + .execute(db.pool()).await.unwrap(); + } + } + resume_tx.send(()).unwrap(); + let error = task.await.unwrap().unwrap_err(); + assert!( + error.to_string().contains("new dependent records"), + "{error}" + ); + let exists: bool = + sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM events WHERE community_id=$1 AND id=$2)") + .bind(c.as_uuid()) + .bind(source.id.as_bytes().as_slice()) + .fetch_one(db.pool()) + .await + .unwrap(); + assert!( + exists, + "source must survive until all dependent logs can be planned" + ); + for mode in [ExecutionMode::ReadOnly, ExecutionMode::Delete] { + let result = db + .user_deletion_store() + .run_message_batches(&options(c, &alice), mode, None, &mut Vec::new()) + .await + .unwrap(); + assert_eq!(result.items, 2); + } + for (community, expected) in [(c, 1_i64), (other, 2)] { + for table in ["events", "delivery_log"] { + let count: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!( + "SELECT count(*) FROM {table} WHERE community_id=$1" + ))) + .bind(community.as_uuid()) + .fetch_one(db.pool()) + .await + .unwrap(); + assert_eq!(count, expected, "{table}"); + } + let subscriptions: i64 = + sqlx::query_scalar("SELECT count(*) FROM subscriptions WHERE community_id=$1") + .bind(community.as_uuid()) + .fetch_one(db.pool()) + .await + .unwrap(); + assert_eq!(subscriptions, 1); + } + let preserved: String = + sqlx::query_scalar("SELECT content FROM events WHERE community_id=$1 AND id=$2") + .bind(c.as_uuid()) + .bind(survivor.id.as_bytes().as_slice()) + .fetch_one(db.pool()) + .await + .unwrap(); + assert_eq!(preserved, survivor.content); + assert_eq!( + db.user_deletion_store() + .run_message_batches( + &options(c, &alice), + ExecutionMode::Delete, + None, + &mut Vec::new() + ) + .await + .unwrap() + .items, + 0 + ); +} diff --git a/crates/buzz-db/src/store/user_deletion/content_batches/execute.rs b/crates/buzz-db/src/store/user_deletion/content_batches/execute.rs index a089bc57f1..eef9cab310 100644 --- a/crates/buzz-db/src/store/user_deletion/content_batches/execute.rs +++ b/crates/buzz-db/src/store/user_deletion/content_batches/execute.rs @@ -104,6 +104,10 @@ pub(super) fn selection(item: &Value) -> Result<(&'static str, &'static str)> { Some("push_wake_outbox") => ("push_wake_outbox", "id=($2->>'id')::uuid"), Some("operator_listener_outbox") => ("operator_listener_outbox", "id=($2->>'id')::uuid"), Some("delivery_log") => ("delivery_log", "id=($2->>'id')::bigint AND delivered_at=($2->>'delivered_at')::timestamptz"), + Some("workflows") => ("workflows", "id=($2->>'id')::uuid"), + Some("workflow_runs") => ("workflow_runs", "id=($2->>'id')::uuid"), + Some("workflow_approvals") => ("workflow_approvals", "token=decode($2->>'token','hex')"), + Some("scheduled_workflow_fires") => ("scheduled_workflow_fires", "workflow_id=($2->>'workflow_id')::uuid AND scheduled_for=($2->>'scheduled_for')::timestamptz"), Some("subscriptions") => ("subscriptions", "id=$2->>'id'"), Some("push_leases") => ("push_leases", "author=decode($2->>'author','hex') AND installation_id=$2->>'installation_id'"), _ => return Err(invalid("unknown internal batch table")), diff --git a/crates/buzz-db/src/store/user_deletion/content_batches/grouped.rs b/crates/buzz-db/src/store/user_deletion/content_batches/grouped.rs index f3873bf2b8..8e96de7f6b 100644 --- a/crates/buzz-db/src/store/user_deletion/content_batches/grouped.rs +++ b/crates/buzz-db/src/store/user_deletion/content_batches/grouped.rs @@ -14,7 +14,7 @@ fn tables(batch: &Value) -> Result> { // A batch can straddle selection pages, with an event from the previous // page preceding the next page's side rows. Always remove dependants first. tables.sort_by_key(|table| match *table { - "subscriptions" | "push_leases" => 1, + "subscriptions" | "push_leases" | "workflows" => 1, "events" => 2, _ => 0, }); @@ -115,6 +115,8 @@ pub(super) async fn execute(tx: &mut AdmittedTx, batch: &Value) -> Result<()> { children(tx.conn(), community, number, table).await?; if table == "events" { erase_events(tx, number).await?; + } else if matches!(table, "workflow_runs" | "workflow_approvals") { + workflows::scrub(tx, number, table, expected).await?; } else { let query = format!( "DELETE FROM {table} t USING content_batch_work w @@ -151,6 +153,8 @@ async fn children( OR EXISTS(SELECT 1 FROM push_match_queue WHERE community_id=$1 AND event_id=decode(w.row_key->>'id','hex')) OR EXISTS(SELECT 1 FROM push_wake_outbox WHERE community_id=$1 AND event_id=decode(w.row_key->>'id','hex')) OR EXISTS(SELECT 1 FROM operator_listener_outbox WHERE community_id=$1 AND event_id=decode(w.row_key->>'id','hex'))", + "workflows" => workflows::DEFINITION_CHILDREN, + "scheduled_workflow_fires" => workflows::FIRE_HISTORY, _ => return Ok(()), }; let query = format!( @@ -161,8 +165,25 @@ async fn children( .bind(community) .bind(table) .bind(number) - .fetch_one(conn) + .fetch_one(&mut *conn) .await?; + // Delivery logs have no event-ID index. Probe the whole batch as a set so + // unrelated history is not scanned again for every selected event. IS TRUE + // keeps membership as a hashed subplan instead of a nested-loop semi join + // when tenant or temporary-worklist estimates are too small. + let remains = remains + || (table == "events" + && sqlx::query_scalar::<_, bool>( + "SELECT EXISTS(SELECT 1 FROM delivery_log d + WHERE d.community_id=$1 AND (d.event_id IN ( + SELECT decode(w.row_key->>'id','hex') FROM content_batch_work w + WHERE w.table_name=$2 AND w.batch=$3)) IS TRUE)", + ) + .bind(community) + .bind(table) + .bind(number) + .fetch_one(&mut *conn) + .await?); if remains { return Err(invalid( "new dependent records appeared; current batch rolled back; rerun to plan them", @@ -253,12 +274,12 @@ pub(super) async fn verify_remaining( OR EXISTS(SELECT 1 FROM operator_listener_outbox WHERE community_id=$1 AND (target_pubkey=ANY($2) OR listener_pubkey=ANY($2)))",include_str!("authored.sql")); let remains: bool = sqlx::query_scalar(sqlx::AssertSqlSafe(query)) .bind(options.community) - .bind(targets) + .bind(&targets) .bind(relay) .bind(KINDS) - .fetch_one(conn) + .fetch_one(&mut *conn) .await?; - if remains { + if remains || workflows::remaining(conn, options.community, &targets).await? { return Err(invalid( "supported rows remain after execution; deletion incomplete; rerun", )); diff --git a/crates/buzz-db/src/store/user_deletion/content_batches/mod.rs b/crates/buzz-db/src/store/user_deletion/content_batches/mod.rs index f685d96f0c..1ab1141985 100644 --- a/crates/buzz-db/src/store/user_deletion/content_batches/mod.rs +++ b/crates/buzz-db/src/store/user_deletion/content_batches/mod.rs @@ -20,6 +20,7 @@ mod owned; mod ownership; mod retention; mod rows; +mod workflows; const KINDS: &[i32] = &[ 5, 41010, 41011, 41012, 46020, 46030, 46031, 3, 10000, 10001, 10002, 10003, 30000, 30003, @@ -28,6 +29,8 @@ const KINDS: &[i32] = &[ // Signer-owned definitions, including shared publications. Project membership // grants no ownership over its repositories; their events remain excluded. 30175, 30176, 30178, 30030, 30180, 30621, + // Private per-viewer state: only the trusted relay's matching d/p snapshot. + 30622, 1063, ]; const PAGE_SIZE: i64 = 100; const MAX_TARGETS: usize = 10_000; @@ -243,8 +246,9 @@ async fn plan( "excluded_agents": excluded_agents, "target_pubkeys": target_pubkeys, "trusted_relay_pubkey": relay, "included_event_kinds": KINDS, "batch_size": options.batch_size, "max_items": options.max_items, - "scope": "user- and owned-agent-attributed events (including persona, team, emoji and project definitions) and reactions, owned subscriptions and notification delivery", - "preserved": "other users' events and reactions; member repositories; workflow database records and other owners' delivery logs", + "scope": "user- and owned-agent-attributed events (including persona, team, emoji and project definitions), trusted-relay private hidden-DM snapshots, reactions, owned subscriptions and notification delivery; unused owned workflows and recorded personal workflow inputs/notes", + "hidden_dm_selection": "kind 30622 requires a trusted relay signer, no channel, and exactly one matching canonical d/p viewer; ambiguous or untrusted snapshots are not selected", + "preserved": "other users' events and reactions; member repositories; workflow history except recorded personal trigger inputs and approval notes; other owners' delivery logs unrelated to selected events", "relay_attribution": if relay.is_some() { "enabled" } else { "not included; supply --relay-pubkey for relay-authored history" }, "execution": "preview only; --delete prints and commits batches after execution checks", "thread_repairs": "reported separately from row items; metadata mutations are not expanded", @@ -265,6 +269,7 @@ async fn plan( collected: collect.then(Vec::new), }; owned::plan(conn, &targets, &mut output).await?; + workflows::plan(conn, &targets, &mut output).await?; rows::authored_reactions(conn, &targets, &mut output).await?; let mut cursor = Cursor::default(); let mut selected = Vec::new(); @@ -320,8 +325,13 @@ async fn plan( } } let query = format!( - "WITH authored AS ({}) SELECT jsonb_build_object('kind',kind,'count',count(*)) - FROM authored WHERE NOT(kind=ANY($4)) GROUP BY kind ORDER BY kind", + "WITH authored AS ({}), excluded AS ( + SELECT kind FROM authored WHERE NOT(kind=ANY($4)) + UNION ALL + SELECT kind FROM events WHERE community_id=$1 AND kind=30622 + AND pubkey=ANY($2::bytea[]) + ) SELECT jsonb_build_object('kind',kind,'count',count(*)) + FROM excluded GROUP BY kind ORDER BY kind", include_str!("authored.sql") ); let excluded: Vec = sqlx::query_scalar(sqlx::AssertSqlSafe(query)) @@ -358,3 +368,15 @@ mod scrub_postgres_tests; #[cfg(test)] mod safety_postgres_tests; + +#[cfg(test)] +mod private_state_postgres_tests; + +#[cfg(test)] +mod workflow_postgres_tests; + +#[cfg(test)] +mod copies_postgres_tests; + +#[cfg(test)] +mod schedule_postgres_tests; diff --git a/crates/buzz-db/src/store/user_deletion/content_batches/postgres_tests.rs b/crates/buzz-db/src/store/user_deletion/content_batches/postgres_tests.rs index 5d763cfe20..3f9ef7a1ef 100644 --- a/crates/buzz-db/src/store/user_deletion/content_batches/postgres_tests.rs +++ b/crates/buzz-db/src/store/user_deletion/content_batches/postgres_tests.rs @@ -242,7 +242,10 @@ async fn preview_delete_and_retry_preserve_other_users_contributions() { .fetch_all(&pool) .await .unwrap(); - assert_eq!(deliveries, vec!["bob-sub"]); + assert!( + deliveries.is_empty(), + "copies of the erased source must go too" + ); let reply_count: i32 = sqlx::query_scalar( "SELECT reply_count FROM thread_metadata WHERE community_id=$1 AND event_id=$2", ) diff --git a/crates/buzz-db/src/store/user_deletion/content_batches/private_state_postgres_tests.rs b/crates/buzz-db/src/store/user_deletion/content_batches/private_state_postgres_tests.rs new file mode 100644 index 0000000000..dacda7b40f --- /dev/null +++ b/crates/buzz-db/src/store/user_deletion/content_batches/private_state_postgres_tests.rs @@ -0,0 +1,242 @@ +use super::scrub_postgres_tests::{options, setup}; +use super::*; +use crate::user_deletion::ExecutionMode; +use nostr::{EventBuilder, Keys, Kind, Tag}; + +async fn state(pool: &sqlx::PgPool, community: Uuid, table: &str) -> Vec { + sqlx::query_scalar(sqlx::AssertSqlSafe(format!( + "SELECT to_jsonb(t) FROM {table} t WHERE community_id=$1 ORDER BY to_jsonb(t)" + ))) + .bind(community) + .fetch_all(pool) + .await + .unwrap() +} + +pub(super) struct InterruptAfterCommit(pub(super) Vec); +impl Write for InterruptAfterCommit { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + for byte in bytes { + if *byte == b'\n' { + let value: Value = serde_json::from_slice(&self.0).unwrap(); + self.0.clear(); + if value["record"] == "batch_committed" { + return Err(std::io::Error::other("simulated lost output after commit")); + } + } else { + self.0.push(*byte); + } + } + Ok(bytes.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn private_dm_snapshot_cleanup_checks_subject_signer_and_resumes_without_shared_deletion() { + let (db, community, channel, alice, bob) = setup().await; + let relay = Keys::generate(); + let agent = Keys::generate(); + db.ensure_user(community, agent.public_key().as_bytes()) + .await + .unwrap(); + sqlx::query("UPDATE users SET agent_owner_pubkey=$2 WHERE community_id=$1 AND pubkey=$3") + .bind(community.as_uuid()) + .bind(alice.public_key().as_bytes().as_slice()) + .bind(agent.public_key().as_bytes().as_slice()) + .execute(db.pool()) + .await + .unwrap(); + let other = db + .ensure_configured_community(&format!("private-state-{}.example", Uuid::new_v4())) + .await + .unwrap() + .id; + let a = alice.public_key().to_hex(); + let b = bob.public_key().to_hex(); + let g = agent.public_key().to_hex(); + sqlx::query( + "INSERT INTO subscriptions (community_id,id,owner_pubkey) VALUES ($1,'surviving',$2)", + ) + .bind(community.as_uuid()) + .bind(bob.public_key().as_bytes().as_slice()) + .execute(db.pool()) + .await + .unwrap(); + let mut selected = HashSet::new(); + let cases = [ + (&relay, vec![("d", &a), ("p", &a)], None, true), + (&relay, vec![("d", &g), ("p", &g)], None, true), + (&relay, vec![("d", &b), ("p", &b)], None, false), + (&bob, vec![("d", &a), ("p", &a)], None, false), + (&alice, vec![("d", &a), ("p", &a)], None, false), + (&relay, vec![("d", &a), ("p", &b)], None, false), + (&relay, vec![("d", &b), ("p", &a)], None, false), + (&relay, vec![("d", &a), ("p", &a), ("p", &b)], None, false), + (&relay, vec![("d", &a), ("d", &b), ("p", &a)], None, false), + (&relay, vec![("d", &a), ("actor", &a)], None, false), + (&relay, vec![("p", &a)], None, false), + (&relay, vec![("d", &a), ("p", &a)], Some(channel), false), + ]; + for (index, (signer, subject, scoped_channel, delete)) in cases.into_iter().enumerate() { + let mut tags: Vec = subject + .into_iter() + .map(|(name, value)| Tag::parse([name, value.as_str()]).unwrap()) + .collect(); + tags.push(Tag::parse(["h", &Uuid::new_v4().to_string()]).unwrap()); + let event = EventBuilder::new(Kind::Custom(30622), "") + .tags(tags) + .sign_with_keys(signer) + .unwrap(); + // insert_event preserves historical/imported shapes; production snapshot + // publishing uses the same d-tag extraction through replaceable storage. + db.insert_event(community, &event, scoped_channel) + .await + .unwrap(); + db.insert_event(other, &event, None).await.unwrap(); + if delete { + selected.insert(event.id.to_hex()); + } + // Logs in either community and under a surviving subscription must + // follow only the selected private snapshot, not its claimed subject. + for c in [community, other] { + sqlx::query("INSERT INTO delivery_log (community_id,subscription_id,event_id,error_message) VALUES ($1,'surviving',$2,'historical private delivery')") + .bind(c.as_uuid()).bind(event.id.as_bytes().as_slice()).execute(db.pool()).await.unwrap(); + } + if index == 0 { + sqlx::query("UPDATE events SET deleted_at=now() WHERE community_id=$1 AND id=$2") + .bind(community.as_uuid()) + .bind(event.id.as_bytes().as_slice()) + .execute(db.pool()) + .await + .unwrap(); + } + } + // Historical malformed JSON must be excluded without preventing valid + // personal snapshots from being previewed and deleted. + for extra in [json!(0), json!(["legacy", 0]), json!(["legacy", null])] { + let event = EventBuilder::new(Kind::Custom(30622), Uuid::new_v4().to_string()) + .tags([ + Tag::parse(["d", &a]).unwrap(), + Tag::parse(["p", &a]).unwrap(), + ]) + .sign_with_keys(&relay) + .unwrap(); + db.insert_event(community, &event, None).await.unwrap(); + sqlx::query("UPDATE events SET tags=$3 WHERE community_id=$1 AND id=$2") + .bind(community.as_uuid()) + .bind(event.id.as_bytes().as_slice()) + .bind(json!([["d", a], ["p", a], extra])) + .execute(db.pool()) + .await + .unwrap(); + } + // A target signature must not make a shared document/repository/wrapped DM + // or another durable huddle record eligible for this private-state change. + for kind in [40100, 45010, 30617, 30618, 1059, 48101] { + let event = EventBuilder::new(Kind::Custom(kind), "shared content stays") + .tags([Tag::parse(["d", &a]).unwrap()]) + .sign_with_keys(&alice) + .unwrap(); + db.insert_event(community, &event, None).await.unwrap(); + } + let tables = [ + "events", + "event_mentions", + "delivery_log", + "channels", + "channel_members", + "users", + "subscriptions", + ]; + let mut before = Vec::new(); + let mut foreign = Vec::new(); + for table in tables { + before.push(state(db.pool(), *community.as_uuid(), table).await); + foreign.push(state(db.pool(), *other.as_uuid(), table).await); + } + let store = db.user_deletion_store(); + let mut opts = options(community, &alice); + opts.batch_size = 1; + assert_eq!( + store + .run_message_batches(&opts, ExecutionMode::ReadOnly, None, &mut Vec::new()) + .await + .unwrap() + .items, + 0 + ); + opts.relay_pubkey = Some(relay.public_key().to_hex()); + let mut output = Vec::new(); + let preview = store + .run_message_batches(&opts, ExecutionMode::ReadOnly, None, &mut output) + .await + .unwrap(); + assert!(preview + .excluded_event_kinds + .contains(&json!({"kind":30622,"count":1}))); + let records: Vec = std::str::from_utf8(&output) + .unwrap() + .lines() + .map(|line| serde_json::from_str(line).unwrap()) + .collect(); + let selected_in_preview: HashSet<_> = records + .iter() + .filter_map(|r| r["items"].as_array()) + .flatten() + .filter(|item| item["table"] == "events") + .map(|item| item["key"]["id"].as_str().unwrap().to_owned()) + .collect(); + assert_eq!(selected_in_preview, selected); + for (i, table) in tables.into_iter().enumerate() { + assert_eq!( + state(db.pool(), *community.as_uuid(), table).await, + before[i] + ); + } + let error = store + .run_message_batches( + &opts, + ExecutionMode::Delete, + None, + &mut InterruptAfterCommit(Vec::new()), + ) + .await + .unwrap_err(); + assert!( + error.to_string().contains("simulated lost output"), + "{error}" + ); + let resumed = store + .run_message_batches(&opts, ExecutionMode::Delete, None, &mut Vec::new()) + .await + .unwrap(); + assert_eq!(resumed.items + 1, preview.items); + for (i, table) in tables.into_iter().enumerate() { + assert_eq!(state(db.pool(), *other.as_uuid(), table).await, foreign[i]); + let expected: Vec = before[i] + .iter() + .filter(|row| { + let field = if table == "events" { "id" } else { "event_id" }; + !selected.contains(row[field].as_str().unwrap_or("").trim_start_matches("\\x")) + }) + .cloned() + .collect(); + assert_eq!( + state(db.pool(), *community.as_uuid(), table).await, + expected, + "{table}" + ); + } + assert_eq!( + store + .run_message_batches(&opts, ExecutionMode::Delete, None, &mut Vec::new()) + .await + .unwrap() + .items, + 0 + ); +} diff --git a/crates/buzz-db/src/store/user_deletion/content_batches/rows.rs b/crates/buzz-db/src/store/user_deletion/content_batches/rows.rs index 418bea35e4..70690908a7 100644 --- a/crates/buzz-db/src/store/user_deletion/content_batches/rows.rs +++ b/crates/buzz-db/src/store/user_deletion/content_batches/rows.rs @@ -81,6 +81,19 @@ pub(super) async fn event_rows( ) .await?; } + // Capture copies under surviving subscriptions before erasing the source. + rows( + conn, + output, + "delivery_log", + "SELECT jsonb_build_object('delivered_at',delivered_at,'id',id) AS row_key, + NULL::text AS warning FROM delivery_log + WHERE community_id=$1 AND event_id=ANY($2::bytea[])", + &ids, + &reason, + "would_delete", + ) + .await?; Ok(()) } diff --git a/crates/buzz-db/src/store/user_deletion/content_batches/safety_postgres_tests.rs b/crates/buzz-db/src/store/user_deletion/content_batches/safety_postgres_tests.rs index bf25b4df55..655cfa09c0 100644 --- a/crates/buzz-db/src/store/user_deletion/content_batches/safety_postgres_tests.rs +++ b/crates/buzz-db/src/store/user_deletion/content_batches/safety_postgres_tests.rs @@ -389,9 +389,22 @@ async fn ownership_change_after_planning_preserves_agent_content() { .unwrap(); let event = message(&db, c, ch, &agent, "must survive transfer", None).await; let before = row(&db, c, &event).await; + let relay = Keys::generate(); + let viewer = agent.public_key().to_hex(); + let private_state = EventBuilder::new(Kind::Custom(30622), "") + .tags([ + Tag::parse(["d", &viewer]).unwrap(), + Tag::parse(["p", &viewer]).unwrap(), + Tag::parse(["h", &ch.to_string()]).unwrap(), + ]) + .sign_with_keys(&relay) + .unwrap(); + db.insert_event(c, &private_state, None).await.unwrap(); + let private_before = row(&db, c, &private_state).await; let (planned, ready) = tokio::sync::oneshot::channel(); let (resume, receive) = std::sync::mpsc::channel(); - let opts = options(c, &alice); + let mut opts = options(c, &alice); + opts.relay_pubkey = Some(relay.public_key().to_hex()); let store = db.user_deletion_store(); let task = tokio::spawn(async move { let mut writer = PauseAfterPlan { @@ -420,6 +433,7 @@ async fn ownership_change_after_planning_preserves_agent_content() { .to_string() .contains("ownership changed")); assert_eq!(row(&db, c, &event).await, before); + assert_eq!(row(&db, c, &private_state).await, private_before); } #[tokio::test] diff --git a/crates/buzz-db/src/store/user_deletion/content_batches/schedule_postgres_tests.rs b/crates/buzz-db/src/store/user_deletion/content_batches/schedule_postgres_tests.rs new file mode 100644 index 0000000000..392bc7d5b1 --- /dev/null +++ b/crates/buzz-db/src/store/user_deletion/content_batches/schedule_postgres_tests.rs @@ -0,0 +1,135 @@ +use super::scrub_postgres_tests::{options, setup, PauseAfterPlan}; +use super::workflow_postgres_tests::definition; +use super::*; +use crate::user_deletion::ExecutionMode; + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn unused_definition_and_claims_commit_atomically_or_refuse_small_batch() { + let (db, c, _, alice, _) = setup().await; + let workflow = Uuid::new_v4(); + definition(&db, c, workflow, &alice).await; + let instant = Utc::now(); + assert!(db + .claim_scheduled_workflow_fire(c, workflow, instant) + .await + .unwrap() + .is_some()); + let store = db.user_deletion_store(); + let mut opts = options(c, &alice); + for mode in [ExecutionMode::ReadOnly, ExecutionMode::Delete] { + let error = store + .run_message_batches(&opts, mode, None, &mut Vec::new()) + .await + .unwrap_err(); + assert!(error.to_string().contains("exceed --batch-size"), "{error}"); + assert!( + db.claim_scheduled_workflow_fire(c, workflow, instant) + .await + .unwrap() + .is_none(), + "refusal must preserve the dedupe claim" + ); + } + opts.batch_size = 2; + let mut output = Vec::new(); + let preview = store + .run_message_batches(&opts, ExecutionMode::ReadOnly, None, &mut output) + .await + .unwrap(); + assert_eq!((preview.items, preview.batches), (2, 1)); + let error = store + .run_message_batches( + &opts, + ExecutionMode::Delete, + None, + &mut super::private_state_postgres_tests::InterruptAfterCommit(Vec::new()), + ) + .await + .unwrap_err(); + assert!( + error.to_string().contains("simulated lost output"), + "{error}" + ); + // A lost commit receipt must not expose an enabled workflow without a claim. + for table in ["workflows", "scheduled_workflow_fires"] { + let count: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!( + "SELECT count(*) FROM {table} WHERE community_id=$1" + ))) + .bind(c.as_uuid()) + .fetch_one(db.pool()) + .await + .unwrap(); + assert_eq!(count, 0); + } + assert!(db + .claim_scheduled_workflow_fire(c, workflow, instant) + .await + .unwrap() + .is_none()); + assert_eq!( + store + .run_message_batches(&opts, ExecutionMode::Delete, None, &mut Vec::new()) + .await + .unwrap() + .items, + 0 + ); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[ignore = "requires Postgres"] +async fn late_schedule_claim_rolls_back_the_entire_unused_workflow_group() { + let (db, c, _, alice, _) = setup().await; + let workflow = Uuid::new_v4(); + definition(&db, c, workflow, &alice).await; + let instant = Utc::now(); + db.claim_scheduled_workflow_fire(c, workflow, instant) + .await + .unwrap(); + let (planned_tx, planned_rx) = tokio::sync::oneshot::channel(); + let (resume_tx, resume_rx) = std::sync::mpsc::channel(); + let store = db.user_deletion_store(); + let mut opts = options(c, &alice); + opts.batch_size = 3; + let task = tokio::spawn(async move { + let mut writer = PauseAfterPlan { + record: "delete_start", + line: Vec::new(), + planned: Some(planned_tx), + resume: resume_rx, + }; + store + .run_message_batches(&opts, ExecutionMode::Delete, None, &mut writer) + .await + }); + planned_rx.await.unwrap(); + let later = instant + chrono::Duration::seconds(1); + db.claim_scheduled_workflow_fire(c, workflow, later) + .await + .unwrap(); + resume_tx.send(()).unwrap(); + let error = task.await.unwrap().unwrap_err(); + assert!( + error.to_string().contains("new dependent records"), + "{error}" + ); + // The planned claim deletion must roll back along with the parent. + for scheduled in [instant, later] { + assert!(db + .claim_scheduled_workflow_fire(c, workflow, scheduled) + .await + .unwrap() + .is_none()); + } + let mut opts = options(c, &alice); + opts.batch_size = 3; + assert_eq!( + db.user_deletion_store() + .run_message_batches(&opts, ExecutionMode::Delete, None, &mut Vec::new()) + .await + .unwrap() + .items, + 3 + ); +} diff --git a/crates/buzz-db/src/store/user_deletion/content_batches/workflow_postgres_tests.rs b/crates/buzz-db/src/store/user_deletion/content_batches/workflow_postgres_tests.rs new file mode 100644 index 0000000000..302e8e4a4d --- /dev/null +++ b/crates/buzz-db/src/store/user_deletion/content_batches/workflow_postgres_tests.rs @@ -0,0 +1,295 @@ +use super::scrub_postgres_tests::{options, setup, PauseAfterPlan}; +use super::*; +use crate::{user_deletion::ExecutionMode, CommunityId, Db}; +use nostr::{EventBuilder, Keys, Kind, Tag}; + +pub(super) async fn definition(db: &Db, c: CommunityId, id: Uuid, owner: &Keys) { + sqlx::query( + "INSERT INTO workflows(community_id,id,name,owner_pubkey,definition,definition_hash) + VALUES($1,$2,'personal automation',$3,'{}',$4)", + ) + .bind(c.as_uuid()) + .bind(id) + .bind(owner.public_key().as_bytes().as_slice()) + .bind(vec![0u8; 32]) + .execute(db.pool()) + .await + .unwrap(); +} + +async fn run( + db: &Db, + c: CommunityId, + workflow: Uuid, + source: Option<&str>, + caller: Option<&Keys>, + context: Value, +) -> Uuid { + let id = Uuid::new_v4(); + sqlx::query("INSERT INTO workflow_runs(community_id,id,workflow_id,status,cause_source,cause_pubkey,trigger_context,execution_trace,error_message) + VALUES($1,$2,$3,'completed',$4,$5,$6,'[{\"body\":\"external response\"}]','retained error')") + .bind(c.as_uuid()).bind(id).bind(workflow).bind(source) + .bind(caller.map(|k|k.public_key().as_bytes().to_vec())).bind(context) + .execute(db.pool()).await.unwrap(); + id +} + +async fn state(db: &Db, c: CommunityId, table: &str) -> Vec { + sqlx::query_scalar(sqlx::AssertSqlSafe(format!( + "SELECT to_jsonb(t) FROM {table} t WHERE community_id=$1 ORDER BY to_jsonb(t)" + ))) + .bind(c.as_uuid()) + .fetch_all(db.pool()) + .await + .unwrap() +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn personal_workflow_cleanup_preserves_history_and_other_subjects_on_retry() { + let (db, c, _, alice, bob) = setup().await; + let agent = Keys::generate(); + db.ensure_user(c, agent.public_key().as_bytes()) + .await + .unwrap(); + sqlx::query("UPDATE users SET agent_owner_pubkey=$2 WHERE community_id=$1 AND pubkey=$3") + .bind(c.as_uuid()) + .bind(alice.public_key().as_bytes().as_slice()) + .bind(agent.public_key().as_bytes().as_slice()) + .execute(db.pool()) + .await + .unwrap(); + let other = db + .ensure_configured_community(&format!("workflow-other-{}.example", Uuid::new_v4())) + .await + .unwrap() + .id; + let empty = Uuid::new_v4(); + let shared = Uuid::new_v4(); + let context = json!({"text":"private trigger","emoji":"private emoji","author":alice.public_key().to_hex(), + "webhook_fields":{"input":"manual input"},"channel_id":"retained","message_id":"retained","timestamp":"retained","is_reply":false}); + let mut scrub_inputs = HashSet::new(); + let mut scrub_notes = HashSet::new(); + for community in [c, other] { + for author in [&alice, &bob, &agent] { + db.ensure_user(community, author.public_key().as_bytes()) + .await + .unwrap(); + } + definition(&db, community, empty, &alice).await; + definition(&db, community, shared, &alice).await; + let others = Uuid::new_v4(); + definition(&db, community, others, &bob).await; + for workflow in [empty, shared, others] { + sqlx::query("INSERT INTO scheduled_workflow_fires(community_id,workflow_id,scheduled_for) VALUES($1,$2,now())") + .bind(community.as_uuid()).bind(workflow).execute(db.pool()).await.unwrap(); + } + // Ownership of a run's parent is irrelevant to the input's author. + for (source, caller, payload, scrub) in [ + (Some("event"), Some(&alice), context.clone(), true), + (Some("manual"), Some(&alice), context.clone(), true), + (Some("event"), Some(&agent), context.clone(), true), + (Some("event"), Some(&bob), context.clone(), false), + (Some("manual"), Some(&bob), context.clone(), false), + (Some("webhook"), Some(&alice), context.clone(), false), + (Some("schedule"), Some(&alice), context.clone(), false), + (None, None, context.clone(), false), + (Some("event"), None, context.clone(), false), + (Some("event"), Some(&alice), json!(["legacy"]), false), + ( + Some("manual"), + Some(&alice), + json!({"webhook_fields":"legacy"}), + false, + ), + ] { + let id = run(&db, community, others, source, caller, payload).await; + if community == c && scrub { + scrub_inputs.insert(id.to_string()); + } + } + let id = run(&db, community, shared, None, None, context.clone()).await; + // Independent foreign keys allow history linked to another parent's run. + let approval_only = Uuid::new_v4(); + let linked_only = Uuid::new_v4(); + definition(&db, community, approval_only, &alice).await; + definition(&db, community, linked_only, &alice).await; + sqlx::query("INSERT INTO workflow_approvals(community_id,token,workflow_id,run_id,step_id,step_index,approver_spec,status,expires_at) + VALUES($1,$2,$3,$4,'review',0,'reviewers','pending',now()+interval '1 day')") + .bind(community.as_uuid()).bind(Uuid::new_v4().as_bytes().to_vec()).bind(approval_only).bind(id) + .execute(db.pool()).await.unwrap(); + sqlx::query("INSERT INTO scheduled_workflow_fires(community_id,workflow_id,scheduled_for,workflow_run_id) VALUES($1,$2,now(),$3)") + .bind(community.as_uuid()).bind(linked_only).bind(id).execute(db.pool()).await.unwrap(); + for workflow in [empty, shared] { + let event = EventBuilder::new(Kind::Custom(30620), "signed workflow publication") + .tags([Tag::parse(["d", &workflow.to_string()]).unwrap()]) + .sign_with_keys(&alice) + .unwrap(); + db.insert_event(community, &event, None).await.unwrap(); + } + sqlx::query("UPDATE workflow_runs SET status='waiting_approval' WHERE community_id=$1 AND cause_source='manual'") + .bind(community.as_uuid()).execute(db.pool()).await.unwrap(); + for author in [&alice, &agent, &bob] { + let token = Uuid::new_v4().as_bytes().to_vec(); + sqlx::query("INSERT INTO workflow_approvals(community_id,token,workflow_id,run_id,step_id,step_index,approver_spec,status,approver_pubkey,note,expires_at) + VALUES($1,$2,$3,$4,'review',0,'reviewers','granted',$5,'personal approval note',now()+interval '1 day')") + .bind(community.as_uuid()).bind(&token).bind(shared).bind(id) + .bind(author.public_key().as_bytes().as_slice()).execute(db.pool()).await.unwrap(); + if community == c && author.public_key() != bob.public_key() { + scrub_notes.insert(format!("\\x{}", hex::encode(token))); + } + } + } + // Existing signed-event cleanup still removes publications, independently + // of the newly supported database-row policy. + let tables = [ + "workflows", + "workflow_runs", + "workflow_approvals", + "scheduled_workflow_fires", + ]; + let mut before = Vec::new(); + let mut foreign = Vec::new(); + for table in tables { + before.push(state(&db, c, table).await); + foreign.push(state(&db, other, table).await); + } + let store = db.user_deletion_store(); + let mut opts = options(c, &alice); + opts.batch_size = 3; + let mut output = Vec::new(); + let preview = store + .run_message_batches(&opts, ExecutionMode::ReadOnly, None, &mut output) + .await + .unwrap(); + assert_eq!(preview.items, 9); + assert!(!String::from_utf8(output) + .unwrap() + .contains("personal approval note")); + for (i, table) in tables.iter().enumerate() { + assert_eq!(state(&db, c, table).await, before[i]); + } + let error = store + .run_message_batches( + &opts, + ExecutionMode::Delete, + None, + &mut super::private_state_postgres_tests::InterruptAfterCommit(Vec::new()), + ) + .await + .unwrap_err(); + assert!( + error.to_string().contains("simulated lost output"), + "{error}" + ); + let resumed = store + .run_message_batches(&opts, ExecutionMode::Delete, None, &mut Vec::new()) + .await + .unwrap(); + assert_eq!(resumed.items + 3, preview.items); + for (i, table) in tables.iter().enumerate() { + let mut expected = before[i].clone(); + expected.retain(|row| match *table { + "workflows" => row["id"] != empty.to_string(), + "scheduled_workflow_fires" => row["workflow_id"] != empty.to_string(), + _ => true, + }); + for row in &mut expected { + if *table == "workflow_runs" && scrub_inputs.contains(row["id"].as_str().unwrap()) { + if row["cause_source"] == "event" { + row["trigger_context"]["text"] = json!(""); + row["trigger_context"]["emoji"] = json!(""); + } else { + row["trigger_context"]["webhook_fields"] = json!({}); + } + } + if *table == "workflow_approvals" + && scrub_notes.contains(row["token"].as_str().unwrap()) + { + row["note"] = Value::Null; + } + } + // jsonb order can change after a field is cleared; compare full rows as sets. + let as_set = |v: Vec| v.into_iter().map(|r| r.to_string()).collect::>(); + assert_eq!( + as_set(state(&db, c, table).await), + as_set(expected), + "{table}" + ); + assert_eq!(state(&db, other, table).await, foreign[i]); + } + let remaining_events: i64 = + sqlx::query_scalar("SELECT count(*) FROM events WHERE community_id=$1 AND kind=30620") + .bind(c.as_uuid()) + .fetch_one(db.pool()) + .await + .unwrap(); + assert_eq!(remaining_events, 0); + assert_eq!( + store + .run_message_batches(&opts, ExecutionMode::Delete, None, &mut Vec::new()) + .await + .unwrap() + .items, + 0 + ); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[ignore = "requires Postgres"] +async fn workflow_history_arriving_after_plan_prevents_cascade_and_claim_deletion() { + let (db, c, _, alice, _) = setup().await; + for with_claim in [false, true] { + let workflow = Uuid::new_v4(); + definition(&db, c, workflow, &alice).await; + if with_claim { + sqlx::query("INSERT INTO scheduled_workflow_fires(community_id,workflow_id,scheduled_for) VALUES($1,$2,now())") + .bind(c.as_uuid()).bind(workflow).execute(db.pool()).await.unwrap(); + } + let (planned_tx, planned_rx) = tokio::sync::oneshot::channel(); + let (resume_tx, resume_rx) = std::sync::mpsc::channel(); + let mut opts = options(c, &alice); + opts.batch_size = 2; + let store = db.user_deletion_store(); + let task = tokio::spawn(async move { + let mut writer = PauseAfterPlan { + record: "delete_start", + line: Vec::new(), + planned: Some(planned_tx), + resume: resume_rx, + }; + store + .run_message_batches(&opts, ExecutionMode::Delete, None, &mut writer) + .await + }); + planned_rx.await.unwrap(); + run(&db, c, workflow, None, None, json!({"external":"keep"})).await; + let tables = ["workflows", "workflow_runs", "scheduled_workflow_fires"]; + let mut before = Vec::new(); + for table in tables { + before.push(state(&db, c, table).await); + } + resume_tx.send(()).unwrap(); + let error = task.await.unwrap().unwrap_err(); + assert!( + error.to_string().contains("new dependent records"), + "{error}" + ); + for (i, table) in tables.iter().enumerate() { + assert_eq!(state(&db, c, table).await, before[i]); + } + assert_eq!( + db.user_deletion_store() + .run_message_batches( + &options(c, &alice), + ExecutionMode::Delete, + None, + &mut Vec::new() + ) + .await + .unwrap() + .items, + 0 + ); + } +} diff --git a/crates/buzz-db/src/store/user_deletion/content_batches/workflows.rs b/crates/buzz-db/src/store/user_deletion/content_batches/workflows.rs new file mode 100644 index 0000000000..f5c88598a7 --- /dev/null +++ b/crates/buzz-db/src/store/user_deletion/content_batches/workflows.rs @@ -0,0 +1,160 @@ +//! Personal workflow fields and unused definitions; shared execution history stays. +use super::*; +use crate::AdmittedTx; + +const RUN_INPUT: &str = "cause_pubkey=ANY($2::bytea[]) AND jsonb_typeof(trigger_context)='object' + AND ((cause_source='event' AND jsonb_typeof(trigger_context->'text')='string' + AND jsonb_typeof(trigger_context->'emoji')='string' + AND (trigger_context->>'text'<>'' OR trigger_context->>'emoji'<>'')) + OR (cause_source='manual' AND jsonb_typeof(trigger_context->'webhook_fields')='object' + AND trigger_context->'webhook_fields'<>'{}'::jsonb))"; +const APPROVAL_NOTE: &str = "approver_pubkey=ANY($2::bytea[]) AND note IS NOT NULL"; + +// A schedule claim can link to a run independently of the run's workflow_id. +// Preserve even malformed cross-workflow links rather than cascade any history. +fn unused(alias: &str) -> String { + format!("NOT EXISTS(SELECT 1 FROM workflow_runs r WHERE r.community_id={alias}.community_id AND r.workflow_id={alias}.id) + AND NOT EXISTS(SELECT 1 FROM workflow_approvals a WHERE a.community_id={alias}.community_id AND a.workflow_id={alias}.id) + AND NOT EXISTS(SELECT 1 FROM scheduled_workflow_fires s WHERE s.community_id={alias}.community_id AND s.workflow_id={alias}.id AND s.workflow_run_id IS NOT NULL)") +} + +fn selections() -> Vec<(&'static str, String, &'static str)> { + let empty = unused("f"); + vec![ + ("workflow_runs", format!("SELECT jsonb_build_object('id',id) AS row_key, NULL::text AS warning + FROM workflow_runs WHERE community_id=$1 AND {RUN_INPUT}"), "would_scrub"), + ("workflow_approvals", format!("SELECT jsonb_build_object('token',encode(token,'hex')) AS row_key, NULL::text AS warning + FROM workflow_approvals WHERE community_id=$1 AND {APPROVAL_NOTE}"), "would_scrub"), + ("workflows", format!("SELECT jsonb_build_object('id',f.id) AS row_key, NULL::text AS warning + FROM workflows f WHERE f.community_id=$1 AND f.owner_pubkey=ANY($2::bytea[]) AND {empty}"), "would_delete"), + ] +} + +pub(super) async fn plan( + conn: &mut PgConnection, + targets: &[Vec], + output: &mut Output<'_, impl Write>, +) -> Result<()> { + for (table, select, action) in selections() + .into_iter() + .filter(|(t, _, _)| *t != "workflows") + { + rows::rows( + conn, + output, + table, + &select, + targets, + &json!({"type":"personal_workflow_data"}), + action, + ) + .await?; + } + // A claim and its unused parent must commit together: a partial prefix + // must never leave enabled automation without its at-most-once claim. + let query = format!( + "SELECT f.id FROM workflows f WHERE f.community_id=$1 + AND f.owner_pubkey=ANY($2::bytea[]) AND {} AND ($3::uuid IS NULL OR f.id>$3) + ORDER BY f.id LIMIT 100", + unused("f") + ); + let mut cursor: Option = None; + loop { + let ids: Vec = sqlx::query_scalar(sqlx::AssertSqlSafe(query.clone())) + .bind(output.community) + .bind(targets) + .bind(cursor) + .fetch_all(&mut *conn) + .await?; + if ids.is_empty() { + break; + } + for id in ids { + cursor = Some(id); + let claims: Vec = sqlx::query_scalar("SELECT jsonb_build_object('workflow_id',workflow_id,'scheduled_for',scheduled_for) + FROM scheduled_workflow_fires WHERE community_id=$1 AND workflow_id=$2 ORDER BY scheduled_for LIMIT $3") + .bind(output.community).bind(id).bind(output.limit as i64).fetch_all(&mut *conn).await?; + if claims.len() >= output.limit { + return Err(invalid("unused workflow and its schedule claims exceed --batch-size; increase it (maximum 100); nothing deleted")); + } + output.flush()?; + let reason = json!({"type":"unused_workflow", "atomic_with_schedule_claims":true}); + for key in claims { + output.add( + "scheduled_workflow_fires", + key, + "would_delete", + &reason, + None, + )?; + } + output.add("workflows", json!({"id":id}), "would_delete", &reason, None)?; + output.flush()?; + } + } + Ok(()) +} + +pub(super) async fn remaining( + conn: &mut PgConnection, + community: Uuid, + targets: &[Vec], +) -> Result { + for (_, select, _) in selections() { + let exists: bool = + sqlx::query_scalar(sqlx::AssertSqlSafe(format!("SELECT EXISTS({select})"))) + .bind(community) + .bind(targets) + .fetch_one(&mut *conn) + .await?; + if exists { + return Ok(true); + } + } + Ok(false) +} + +// Recheck after locking the planned parent, including unplanned children. Never +// use its ON DELETE CASCADE to erase runs, approvals or unplanned schedule rows. +pub(super) const DEFINITION_CHILDREN: &str = "EXISTS(SELECT 1 FROM workflow_runs WHERE community_id=$1 AND workflow_id=(w.row_key->>'id')::uuid) + OR EXISTS(SELECT 1 FROM workflow_approvals WHERE community_id=$1 AND workflow_id=(w.row_key->>'id')::uuid) + OR EXISTS(SELECT 1 FROM scheduled_workflow_fires WHERE community_id=$1 AND workflow_id=(w.row_key->>'id')::uuid)"; + +pub(super) const FIRE_HISTORY: &str = "EXISTS(SELECT 1 FROM workflow_runs WHERE community_id=$1 AND workflow_id=(w.row_key->>'workflow_id')::uuid) + OR EXISTS(SELECT 1 FROM workflow_approvals WHERE community_id=$1 AND workflow_id=(w.row_key->>'workflow_id')::uuid) + OR EXISTS(SELECT 1 FROM scheduled_workflow_fires WHERE community_id=$1 AND workflow_id=(w.row_key->>'workflow_id')::uuid AND workflow_run_id IS NOT NULL) +"; + +pub(super) async fn scrub( + tx: &mut AdmittedTx, + number: i64, + table: &str, + expected: usize, +) -> Result<()> { + let query = match table { + // Keep the required serialized TriggerContext fields, so retained runs + // remain readable. Do not touch outputs, provenance or unrelated input. + "workflow_runs" => "UPDATE workflow_runs t SET trigger_context=CASE t.cause_source + WHEN 'event' THEN t.trigger_context || '{\"text\":\"\",\"emoji\":\"\"}'::jsonb + WHEN 'manual' THEN t.trigger_context || '{\"webhook_fields\":{}}'::jsonb END + FROM content_batch_work w WHERE w.table_name='workflow_runs' AND w.batch=$2 + AND w.action='would_scrub' AND t.community_id=$1 AND t.id=(w.row_key->>'id')::uuid", + "workflow_approvals" => "UPDATE workflow_approvals t SET note=NULL + FROM content_batch_work w WHERE w.table_name='workflow_approvals' AND w.batch=$2 + AND w.action='would_scrub' AND t.community_id=$1 AND t.token=decode(w.row_key->>'token','hex')", + _ => return Err(invalid("unsupported workflow scrub")), + }; + let community = *tx.community().as_uuid(); + let affected = sqlx::query(query) + .bind(community) + .bind(number) + .execute(tx.conn()) + .await? + .rows_affected(); + if affected as usize != expected { + return Err(invalid( + "workflow rows missing or unsupported action; current batch rolled back", + )); + } + Ok(()) +} diff --git a/crates/buzz-deletion/src/user/content_batches.rs b/crates/buzz-deletion/src/user/content_batches.rs index 3d3c2b2896..51206adb02 100644 --- a/crates/buzz-deletion/src/user/content_batches.rs +++ b/crates/buzz-deletion/src/user/content_batches.rs @@ -18,7 +18,7 @@ pub struct Args { /// Print selected rows without changing data (the default). #[arg(long, alias = "print-only", conflicts_with = "delete")] read_only: bool, - /// Delete selected rows. + /// Delete selected rows. Stop the relay, workflow engine and external writers first. #[arg(long)] delete: bool, /// Trusted relay signer for historical actor/p attribution. diff --git a/docs/operator-user-deletion-executor.md b/docs/operator-user-deletion-executor.md index ce9cf44f00..913dfc1fd0 100644 --- a/docs/operator-user-deletion-executor.md +++ b/docs/operator-user-deletion-executor.md @@ -14,12 +14,52 @@ execution is unsupported. ## Content batches +Run deletion offline with the relay, workflow engine and external writers stopped. +Read-only preview does not require stopping them. This command does not install +a lasting account fence. + `content-batches` selects the user plus agents owned by that user **in the target community**. Ownership in another community does not authorize cleanup here. The start record reports excluded agent keys with missing or conflicting local ownership. Every batch rechecks ownership; a change aborts the batch. Former membership does not prevent cleanup of historical content. +With `--relay-pubkey`, content cleanup also selects private hidden-DM visibility +snapshots (kind 30622) for the user and currently owned agents. A snapshot must be +signed by that trusted relay, have no channel, and have exactly one canonical +`d` tag and one `p` tag matching its stored viewer coordinate. Conflicting, +malformed or untrusted snapshots are left outside the supported scope. Without +the trusted relay key, these snapshots are not selected. Selected snapshots and +their dependent delivery records are removed, including historical soft-deleted +rows. DM conversations, other participants' preferences and encrypted message +copies are not selected by this rule. + +Content cleanup also removes signed file-metadata publications (kind 1063), +without deleting referenced blobs. Delivery logs under surviving subscriptions +follow every selected source event, including events reduced to tombstones. +Mentions and pending delivery rows are removed before their source events. + +Workflow cleanup deletes owned definitions with no runs, approvals or linked +schedule history, removing each definition and its unused schedule claims in the same transaction. +The complete group must fit `--batch-size` (maximum 100 rows); otherwise planning +fails before deletion. Increase the batch size for a larger group. More than 99 +claims on one unused definition requires a separately reviewed cleanup. +Definitions with history and all run/approval rows are retained. For recorded +`event` causes, it clears the signer's saved trigger text and emoji; for recorded +`manual` causes, it empties the caller's input map. It clears the recorded +approver's note. These field changes also apply inside another owner's workflow. +Required trigger fields remain present, and every other field is preserved. +Retained runs, including waiting approvals, will read the cleared inputs if +resumed later. This change does not cancel those runs. The existing signed-event +cleanup of kind 30620 is unchanged; retained definitions here mean database rows. +Missing provenance, malformed input shapes, webhook payloads, execution traces +and errors are not selected. This is partial content cleanup, not a claim of +complete workflow erasure or stopped workflow execution. + +Workflow rows use the same bounded preview, fingerprint and retry checks as +other content. New history or schedule claims block definition deletion before +any cascade can occur. No device installations or gateway delegations are deleted. + The handler preserves actual reply ancestry and other users' reactions by erasing selected messages into structural tombstones. Plain links, quotes and unmarked references do not require retaining their destinations. Other authors' signed