From fdf8a8363f2b701a85253dcffe948c8a92e5f99e Mon Sep 17 00:00:00 2001 From: Ravneet Arora Date: Mon, 16 Nov 2026 12:05:49 -0500 Subject: [PATCH 1/5] Add standalone profile cleanup batches Preview and delete scoped identity data for a user and owned agents. Keep shared archive snapshots signed and preserve other communities. Leave workflow integration and online fencing separate. Co-authored-by: dessert <7d616e7e143e5d408159614dccff1371350a1c1bd36c8de838a45ece5aca0aca@buzz.block.builderlab.xyz> Signed-off-by: Ravneet Arora --- crates/buzz-db/src/store/user_deletion/mod.rs | 2 + .../user_deletion/profile_batches/events.rs | 276 +++++++++++ .../user_deletion/profile_batches/mod.rs | 266 +++++++++++ .../user_deletion/profile_batches/plan.rs | 128 ++++++ .../profile_batches/postgres_tests.rs | 431 ++++++++++++++++++ .../user_deletion/profile_batches/rows.rs | 156 +++++++ crates/buzz-deletion/src/user.rs | 8 + .../buzz-deletion/src/user/profile_batches.rs | 120 +++++ docs/profile-cleanup.md | 99 ++++ 9 files changed, 1486 insertions(+) create mode 100644 crates/buzz-db/src/store/user_deletion/profile_batches/events.rs create mode 100644 crates/buzz-db/src/store/user_deletion/profile_batches/mod.rs create mode 100644 crates/buzz-db/src/store/user_deletion/profile_batches/plan.rs create mode 100644 crates/buzz-db/src/store/user_deletion/profile_batches/postgres_tests.rs create mode 100644 crates/buzz-db/src/store/user_deletion/profile_batches/rows.rs create mode 100644 crates/buzz-deletion/src/user/profile_batches.rs create mode 100644 docs/profile-cleanup.md diff --git a/crates/buzz-db/src/store/user_deletion/mod.rs b/crates/buzz-db/src/store/user_deletion/mod.rs index 1c093946945..f223f8c75ba 100644 --- a/crates/buzz-db/src/store/user_deletion/mod.rs +++ b/crates/buzz-db/src/store/user_deletion/mod.rs @@ -3,6 +3,8 @@ use crate::Db; use sqlx::PgPool; mod discovery; mod inventory; +/// Standalone, offline profile cleanup with read-only preview. +pub mod profile_batches; mod requests; pub use discovery::normalize_user_deletion_pubkey; pub use inventory::UserDeletionInventory; diff --git a/crates/buzz-db/src/store/user_deletion/profile_batches/events.rs b/crates/buzz-db/src/store/user_deletion/profile_batches/events.rs new file mode 100644 index 00000000000..f4f8c90f9dc --- /dev/null +++ b/crates/buzz-db/src/store/user_deletion/profile_batches/events.rs @@ -0,0 +1,276 @@ +use super::*; +use chrono::{DateTime, Utc}; +use nostr::{Event, EventBuilder, Kind, Tag, Timestamp}; +use sqlx::Row; +use std::collections::HashMap; +use std::sync::Arc; + +pub(super) struct Snapshot { + signer: String, + time: u64, + survivors: Arc>, +} +pub(super) struct Selected { + pub id: Vec, + pub key: Value, + pub fingerprint: String, + pub snapshot: Option, +} + +fn subject(tags: &Value, name: &str) -> Result { + let all = tags + .as_array() + .ok_or_else(|| invalid("profile tags are not an array"))?; + let tagged: Vec<_> = all + .iter() + .filter(|t| t.get(0).and_then(Value::as_str) == Some(name)) + .collect(); + if tagged.len() != 1 { + return Err(invalid(format!( + "profile requires exactly one {name} subject" + ))); + } + let value = tagged[0] + .get(1) + .and_then(Value::as_str) + .ok_or_else(|| invalid("missing profile subject"))?; + if value.len() != 64 || !value.bytes().all(|c| c.is_ascii_hexdigit()) { + return Err(invalid("malformed profile subject")); + } + normalize_user_deletion_pubkey(value) +} + +pub(super) async fn select( + conn: &mut PgConnection, + scope: &Scope, + max: u32, +) -> Result> { + // Scope before payload inspection. Case-insensitive subject comparison covers historical hex. + // The statement budget bounds the fallback tag scan; no new schema is required. + let candidate_sql="SELECT id,created_at,kind,encode(pubkey,'hex') AS author,channel_id, + CASE WHEN pg_column_size(tags)<=65536 THEN tags END AS tags, + jsonb_build_object('id',id,'created_at',created_at) AS key,encode(sha256(convert_to(to_jsonb(e)::text,'UTF8')),'hex') AS fingerprint + FROM events e WHERE community_id=$1 AND kind IN (0,10100,30177,30179,30382,9035,9036,8002,8003,13535) + AND (pubkey=ANY($2::bytea[]) OR EXISTS(SELECT 1 FROM jsonb_array_elements(CASE WHEN jsonb_typeof(tags)='array' THEN tags ELSE '[]'::jsonb END) tag + WHERE (tag->>0 IN ('p','d') AND lower(tag->>1)=ANY($3::text[])) OR (tag->>0='consent' AND lower(tag->>2)=ANY($3::text[])))) + ORDER BY created_at,id LIMIT $4"; + // Bound payload memory before materializing candidate tags. The query remains read-only. + let budget_sql = format!("SELECT count(*) AS count, COALESCE(sum(pg_column_size(tags)),0)::bigint AS bytes FROM ({candidate_sql}) candidates"); + let budget = sqlx::query(sqlx::AssertSqlSafe(budget_sql)) + .bind(scope.community) + .bind(&scope.bytes) + .bind(&scope.targets) + .bind((i64::from(max) + 1).min(65_537)) + .fetch_one(&mut *conn) + .await?; + if budget.try_get::("count")? > i64::from(max).min(65_536) + || budget.try_get::("bytes")? > 32 * 1024 * 1024 + { + return Err(invalid( + "profile candidates exceed item or 32 MiB payload budget", + )); + } + let candidates = sqlx::query(candidate_sql) + .bind(scope.community) + .bind(&scope.bytes) + .bind(&scope.targets) + .bind((i64::from(max) + 1).min(65_537)) + .fetch_all(&mut *conn) + .await?; + if candidates.len() > max as usize { + return Err(invalid( + "profile candidates exceed max-items; no deletion performed", + )); + } + let survivors:Vec=sqlx::query_scalar("SELECT pubkey FROM archived_identities WHERE community_id=$1 AND NOT(pubkey=ANY($2::text[])) ORDER BY pubkey LIMIT 10001") + .bind(scope.community).bind(&scope.targets).fetch_all(&mut *conn).await?; + let survivors = Arc::new(survivors); + let mut out: Vec = Vec::new(); + // Every replacement is strictly newer than every current snapshot from that signer. + let mut next_time: HashMap = HashMap::new(); + let mut snapshot_index: HashMap = HashMap::new(); + for row in candidates { + let kind: i32 = row.try_get("kind")?; + let author: String = row.try_get("author")?; + let tags: Value = row + .try_get::, _>("tags")? + .ok_or_else(|| invalid("profile tags exceed 64 KiB"))?; + let authored = scope.targets.contains(&author); + let mut snapshot = None; + let selected = match kind { + 0 | 10100 => authored, + 30177 | 30179 => { + let agent = subject(&tags, "d")?; + if authored && !scope.targets.contains(&agent) { + return Err(invalid( + "managed definition names an unselected agent; save its inventory first", + )); + } + if scope.targets.contains(&agent) && author != scope.human { + return Err(invalid("managed agent definition belongs to another owner")); + } + authored && scope.targets.contains(&agent) + } + 30382 => { + let target = subject(&tags, "p")?; + if target != subject(&tags, "d")? { + return Err(invalid("verified profile d/p subjects disagree")); + } + if scope.targets.contains(&target) { + trusted(scope, &author)?; + true + } else { + false + } + } + 9035 | 9036 => { + let target = subject(&tags, "p")?; + if authored && !scope.targets.contains(&target) { + return Err(invalid("archive request concerns a surviving identity; shared-history disposition required")); + } + scope.targets.contains(&target) + } + 8002 | 8003 => { + let target = subject(&tags, "p")?; + if scope.targets.contains(&target) { + trusted(scope, &author)?; + true + } else { + return Err(invalid("archive delta names a target actor on a surviving identity; shared-history disposition required")); + } + } + 13535 => { + trusted(scope, &author)?; + if survivors.len() > 10_000 { + return Err(invalid( + "archive snapshot exceeds 10000 retained identities", + )); + } + let previous = if let Some(previous) = next_time.get(&author) { + *previous + } else { + let max_time:Option>=sqlx::query_scalar("SELECT max(created_at) FROM events WHERE community_id=$1 AND kind=13535 AND pubkey=decode($2,'hex')") + .bind(scope.community).bind(&author).fetch_one(&mut *conn).await?; + max_time + .map_or(0, |t| t.timestamp().max(0) as u64) + .max(Timestamp::now().as_secs()) + }; + let time = previous + .checked_add(1) + .ok_or_else(|| invalid("archive snapshot timestamp overflow"))?; + next_time.insert(author.clone(), time); + snapshot = Some(Snapshot { + signer: author.clone(), + time, + survivors: survivors.clone(), + }); + true + } + _ => false, + }; + if selected { + if row.try_get::, _>("channel_id")?.is_some() { + return Err(invalid("channel-bearing profile requires content cleanup")); + } + if let Some(new_snapshot) = &snapshot { + if let Some(previous) = + snapshot_index.insert(new_snapshot.signer.clone(), out.len()) + { + out[previous].snapshot = None; + } + } + out.push(Selected { + id: row.try_get("id")?, + key: row.try_get("key")?, + fingerprint: row.try_get("fingerprint")?, + snapshot, + }); + } + } + Ok(out) +} +fn trusted(scope: &Scope, author: &str) -> Result<()> { + if !scope.relays.iter().any(|r| r == author) { + return Err(invalid("subject profile/archive event has an untrusted relay signer; supply verified --relay-pubkey")); + } + Ok(()) +} + +pub(super) fn sign_snapshots( + plan: &Plan, + signer: Option<&nostr::Keys>, +) -> Result> { + let mut out = HashMap::new(); + let Some(signer) = signer else { + return Ok(out); + }; + for op in &plan.ops { + let Some(snapshot) = &op.snapshot else { + continue; + }; + if signer.public_key().to_hex() != snapshot.signer { + return Err(invalid( + "relay signing key does not match archive snapshot signer", + )); + } + let mut tags = vec![Tag::parse(["-"]).map_err(|_| invalid("invalid archive marker"))?]; + for p in snapshot.survivors.iter() { + tags.push( + Tag::parse(["p", p.as_str()]).map_err(|_| invalid("invalid archive subject"))?, + ); + } + let event = EventBuilder::new(Kind::Custom(13535), "") + .tags(tags) + .custom_created_at(Timestamp::from(snapshot.time)) + .sign_with_keys(signer) + .map_err(|_| invalid("could not sign archive snapshot"))?; + out.insert(op.key.to_string(), event); + if out.len() > 64 { + return Err(invalid("too many archive signers")); + } + } + Ok(out) +} + +pub(super) async fn replace_snapshot( + tx: &mut crate::AdmittedTx, + scope: &Scope, + op: &rows::Operation, + replacements: &HashMap, +) -> Result { + let event = replacements + .get(&op.key.to_string()) + .ok_or_else(|| invalid("missing signed archive replacement"))?; + let current: Vec = sqlx::query_scalar( + "SELECT pubkey FROM archived_identities WHERE community_id=$1 ORDER BY pubkey LIMIT 10001", + ) + .bind(scope.community) + .fetch_all(tx.conn()) + .await?; + let expected: Vec = event + .tags + .iter() + .filter_map(|t| { + let t = t.as_slice(); + (t.first().map(String::as_str) == Some("p")) + .then(|| t.get(1).cloned()) + .flatten() + }) + .collect(); + if current != expected { + return Err(invalid( + "archive membership changed; re-preview before snapshot replacement", + )); + } + // A shared event writer preserves the normal insert hooks and replica rules. + let removed=sqlx::query("DELETE FROM events e WHERE community_id=$1 AND id=($2->>'id')::bytea AND created_at=($2->>'created_at')::timestamptz AND encode(sha256(convert_to(to_jsonb(e)::text,'UTF8')),'hex')=$3") + .bind(scope.community).bind(&op.key).bind(&op.fingerprint).execute(tx.conn()).await?.rows_affected(); + if removed != 1 { + return Ok(removed); + } + let (_, inserted) = crate::event::insert_event_in_transaction(tx, event, None).await?; + if !inserted { + return Err(invalid("archive replacement already exists; re-preview")); + } + Ok(removed) +} diff --git a/crates/buzz-db/src/store/user_deletion/profile_batches/mod.rs b/crates/buzz-db/src/store/user_deletion/profile_batches/mod.rs new file mode 100644 index 00000000000..b4b6c0220bf --- /dev/null +++ b/crates/buzz-db/src/store/user_deletion/profile_batches/mod.rs @@ -0,0 +1,266 @@ +//! Offline profile erasure. Preview and deletion share the exact immutable plan. +//! Writers must remain stopped until the caller's full deletion verification ends. +use super::{normalize_user_deletion_pubkey, UserDeletionStore}; +use crate::{DbError, Result}; +use serde::Serialize; +use serde_json::{json, Value}; +use sqlx::{Connection, PgConnection}; +use std::io::Write; +use uuid::Uuid; + +mod events; +mod plan; +#[cfg(test)] +mod postgres_tests; +mod rows; + +/// Explicit scope for standalone profile preview and deletion. +pub struct ProfileBatchOptions { + /// Surviving community whose profiles are selected. + pub community: Uuid, + /// Human key as hex or npub. + pub pubkey: String, + /// Additional previously inventoried agents, retained across retries. + pub agent_pubkeys: Vec, + /// Explicitly trusted current/historical relay signing keys. + pub relay_pubkeys: Vec, + /// Row mutations per transaction, 1..=100. + pub batch_size: u16, + /// Maximum planned mutations, 1..=1,000,000; overflow makes no changes. + pub max_items: u32, +} + +/// Result for this profile scope, never a claim of complete account erasure. +#[derive(Debug, Serialize)] +pub struct ProfileBatchSummary { + /// preview_complete or delete_complete, emitted only on success. + pub record: &'static str, + /// Proposed or committed row mutations. + pub items: usize, + /// Proposed or committed transactions. + pub batches: usize, + /// Frozen human/agent keys. Supply agent keys on retries after row removal. + pub target_pubkeys: Vec, + /// Always false; the independent final verifier owns that claim. + pub account_erasure_complete: bool, +} + +struct Scope { + community: Uuid, + human: String, + targets: Vec, + bytes: Vec>, + relays: Vec, +} + +struct Plan { + scope: Scope, + ops: Vec, + blockers: Vec, +} + +impl UserDeletionStore { + /// Preview or execute a standalone profile plan with stopped writers. + /// + /// No workflow is enabled, lease acquired or deletion journal modified. + /// `relay_secret` is required only to replace a shared archive snapshot; + /// it must match that snapshot's trusted signer and is never printed. + pub async fn run_profile_batches( + &self, + options: &ProfileBatchOptions, + delete: bool, + relay_secret: Option<&str>, + writer: &mut impl Write, + ) -> Result { + if !(1..=100).contains(&options.batch_size) || !(1..=1_000_000).contains(&options.max_items) + { + return Err(invalid( + "batch-size must be 1..100 and max-items 1..1000000", + )); + } + let mut conn = self.pool.acquire().await?.detach(); + // Detached connection closes on every return/cancellation; settings never leak to the pool. + sqlx::query("SET statement_timeout='30s'") + .execute(&mut conn) + .await?; + sqlx::query("SET lock_timeout='3s'") + .execute(&mut conn) + .await?; + sqlx::query("SET TIME ZONE 'UTC'") + .execute(&mut conn) + .await?; + let mut snapshot = conn.begin().await?; + sqlx::query("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ, READ ONLY") + .execute(&mut *snapshot) + .await?; + let plan = plan::build(&mut snapshot, options).await?; + snapshot.rollback().await?; + line( + writer, + &json!({"record":"profile_batches_start", "community":options.community, + "target_pubkeys":plan.scope.targets, "read_only":!delete, + "blockers":plan.blockers, + "retained":["deletion records", "replay protection", "repositories"], + "external_work":["media objects", "client caches", "online admission and writer fencing"], + "account_erasure_complete":false}), + )?; + let signer = if delete && plan.ops.iter().any(|o| o.snapshot.is_some()) { + Some( + nostr::Keys::parse(relay_secret.ok_or_else(|| { + invalid("archive snapshot replacement requires BUZZ_RELAY_PRIVATE_KEY") + })?) + .map_err(|_| invalid("invalid relay signing key"))?, + ) + } else { + None + }; + if delete && !plan.blockers.is_empty() { + return Err(invalid( + "profile prerequisites unresolved; see printed blockers; no changes made", + )); + } + // Sign before the first mutation: a missing/wrong key cannot strand a partial deletion. + let replacements = events::sign_snapshots(&plan, signer.as_ref())?; + let mut groups = Vec::new(); + let mut start = 0; + let mut count = 0; + for (index, op) in plan.ops.iter().enumerate() { + if op.cost() > usize::from(options.batch_size) { + return Err(invalid( + "archive replacement needs batch-size of at least 2", + )); + } + if count + op.cost() > usize::from(options.batch_size) { + groups.push(&plan.ops[start..index]); + start = index; + count = 0; + } + count += op.cost(); + } + if start < plan.ops.len() { + groups.push(&plan.ops[start..]); + } + let items: usize = plan.ops.iter().map(rows::Operation::cost).sum(); + if items > options.max_items as usize { + return Err(invalid( + "profile mutations exceed max-items; no changes made", + )); + } + let mut batches = 0; + for (batch_index, batch) in groups.iter().enumerate() { + line( + writer, + &json!({"record":"proposed_batch", "number":batch_index+1, + "items":batch.iter().map(rows::Operation::description).collect::>()}), + )?; + if delete { + let mut raw = self.pool.begin().await?; + for setting in [ + "SET LOCAL statement_timeout='30s'", + "SET LOCAL lock_timeout='3s'", + "SET LOCAL TIME ZONE 'UTC'", + ] { + sqlx::query(setting).execute(&mut *raw).await?; + } + lock(&mut raw, &plan.scope).await?; + let mut tx = crate::AdmittedTx::admit( + raw, + &crate::deletion::DeletionStore::new(self.pool.clone()), + buzz_core::CommunityId::from_uuid(plan.scope.community), + ) + .await?; + plan::validate_ownership(tx.conn(), &plan.scope).await?; + for op in *batch { + rows::apply(&mut tx, &plan.scope, op, &replacements).await?; + } + tx.commit().await?; + line( + writer, + &json!({"record":"batch_committed","number":batch_index+1,"items":batch.iter().map(rows::Operation::cost).sum::()}), + )?; + } + batches += 1; + } + if !plan.blockers.is_empty() { + return Err(invalid( + "preview has unresolved prerequisites; no completion marker", + )); + } + if delete { + // Replan using the saved targets: identity deletion must not shrink verification scope. + let check = ProfileBatchOptions { + community: options.community, + pubkey: plan.scope.human.clone(), + agent_pubkeys: plan + .scope + .targets + .iter() + .filter(|p| *p != &plan.scope.human) + .cloned() + .collect(), + relay_pubkeys: plan.scope.relays.clone(), + batch_size: options.batch_size, + max_items: options.max_items, + }; + let mut tx = conn.begin().await?; + lock(&mut tx, &plan.scope).await?; + let remaining = plan::build(&mut tx, &check).await?; + if !remaining.ops.is_empty() || !remaining.blockers.is_empty() { + return Err(invalid( + "profile rows or dependencies remain; rerun with the printed target keys", + )); + } + tx.commit().await?; + } + let summary = ProfileBatchSummary { + record: if delete { + "delete_complete" + } else { + "preview_complete" + }, + items, + batches, + target_pubkeys: plan.scope.targets, + account_erasure_complete: false, + }; + line(writer, &summary)?; + conn.close().await?; + Ok(summary) + } +} + +async fn lock(conn: &mut PgConnection, scope: &Scope) -> Result<()> { + sqlx::query("SELECT pg_advisory_xact_lock_shared($1)") + .bind(crate::deletion::SCHEMA_DESTRUCTION_LOCK_KEY) + .execute(&mut *conn) + .await?; + sqlx::query("SELECT pg_advisory_xact_lock(hashtextextended($1,0))") + .bind(crate::deletion::community_deletion_lock_key( + buzz_core::CommunityId::from_uuid(scope.community), + )) + .execute(&mut *conn) + .await?; + let active: bool = sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM communities WHERE id=$1 AND deletion_state='active' AND deleted_at IS NULL)") + .bind(scope.community).fetch_one(conn).await?; + if !active { + return Err(invalid( + "community is absent or undergoing whole-community deletion", + )); + } + Ok(()) +} + +fn invalid(message: impl Into) -> DbError { + DbError::DeletionSafety(message.into()) +} +fn line(writer: &mut impl Write, value: &impl Serialize) -> Result<()> { + let bytes = serde_json::to_vec(value)?; + if bytes.len() > 2 * 1024 * 1024 { + return Err(invalid("output exceeds 2 MiB; reduce batch-size")); + } + writer + .write_all(&bytes) + .and_then(|()| writer.write_all(b"\n")) + .and_then(|()| writer.flush()) + .map_err(|e| invalid(format!("profile batch output failed: {e}"))) +} diff --git a/crates/buzz-db/src/store/user_deletion/profile_batches/plan.rs b/crates/buzz-db/src/store/user_deletion/profile_batches/plan.rs new file mode 100644 index 00000000000..0925f9b9450 --- /dev/null +++ b/crates/buzz-db/src/store/user_deletion/profile_batches/plan.rs @@ -0,0 +1,128 @@ +use super::*; +use sqlx::Row; +use std::collections::BTreeSet; + +pub(super) async fn build(conn: &mut PgConnection, options: &ProfileBatchOptions) -> Result { + let human = normalize_user_deletion_pubkey(&options.pubkey)?; + let mut targets = BTreeSet::from([human.clone()]); + for p in &options.agent_pubkeys { + targets.insert(normalize_user_deletion_pubkey(p)?); + } + // Match the content command's cross-community ownership discovery; mutation stays tenant-scoped. + let agents: Vec> = sqlx::query_scalar("SELECT DISTINCT pubkey FROM users WHERE agent_owner_pubkey=decode($1,'hex') ORDER BY pubkey LIMIT 10001") + .bind(&human).fetch_all(&mut *conn).await?; + targets.extend(agents.iter().map(hex::encode)); + if targets.len() > 10_000 { + return Err(invalid("profile target limit exceeded (10000)")); + } + let targets: Vec = targets.into_iter().collect(); + let relays: Vec = options + .relay_pubkeys + .iter() + .map(|p| normalize_user_deletion_pubkey(p)) + .collect::>()?; + if relays.iter().any(|p| targets.contains(p)) { + return Err(invalid("target keys and trusted relay keys must differ")); + } + let bytes = targets + .iter() + .map(|p| hex::decode(p).map_err(|_| invalid("invalid target key"))) + .collect::>()?; + let scope = Scope { + community: options.community, + human, + targets, + bytes, + relays, + }; + let active: bool = sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM communities WHERE id=$1 AND deletion_state='active' AND deleted_at IS NULL)") + .bind(scope.community).fetch_one(&mut *conn).await?; + if !active { + return Err(invalid( + "community is absent or undergoing whole-community deletion", + )); + } + validate_ownership(conn, &scope).await?; + let blockers = dependencies(conn, &scope).await?; + let mut plan = Plan { + scope, + ops: Vec::new(), + blockers, + }; + let selected = events::select(conn, &plan.scope, options.max_items).await?; + let ids: Vec> = selected.iter().map(|e| e.id.clone()).collect(); + // Threaded/channel-bearing data belongs to content cleanup; never break a surviving discussion. + let threaded: bool = sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM thread_metadata WHERE community_id=$1 AND (event_id=ANY($2::bytea[]) OR parent_event_id=ANY($2::bytea[]) OR root_event_id=ANY($2::bytea[])))") + .bind(plan.scope.community).bind(&ids).fetch_one(&mut *conn).await?; + if threaded { + plan.blockers + .push("selected profiles have thread dependencies; content cleanup required".into()); + } + for table in rows::CHILDREN { + rows::collect(conn, &mut plan, table, &ids, options.max_items).await?; + } + let mut snapshots = Vec::new(); + for event in selected { + let op = rows::Operation { + table: &rows::EVENTS, + key: event.key, + fingerprint: event.fingerprint, + snapshot: event.snapshot, + }; + if op.snapshot.is_some() { + snapshots.push(op); + } else { + rows::push(&mut plan, op, options.max_items)?; + } + } + rows::collect(conn, &mut plan, &rows::HEADS, &[], options.max_items).await?; + rows::collect(conn, &mut plan, &rows::ARCHIVES, &[], options.max_items).await?; + // Archive rows go first, then snapshots; retries can find stale snapshots while identities remain. + for op in snapshots { + rows::push(&mut plan, op, options.max_items)?; + } + let before_users = plan.ops.len(); + rows::collect(conn, &mut plan, &rows::USERS, &[], options.max_items).await?; + let human_bytea = format!("\\x{}", plan.scope.human); + plan.ops[before_users..].sort_by_key(|op| op.key["pubkey"].as_str() == Some(&human_bytea)); + Ok(plan) +} + +pub(super) async fn validate_ownership(conn: &mut PgConnection, scope: &Scope) -> Result<()> { + let conflict: bool=sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM users WHERE community_id=$1 AND \ + ((pubkey=ANY($2::bytea[]) AND pubkey<>decode($3,'hex') AND agent_owner_pubkey IS DISTINCT FROM decode($3,'hex')) \ + OR (agent_owner_pubkey=ANY($2::bytea[]) AND NOT(pubkey=ANY($2::bytea[])))))") + .bind(scope.community).bind(&scope.bytes).bind(&scope.human).fetch_one(conn).await?; + if conflict { + return Err(invalid( + "agent ownership changed, is missing, or has unselected dependents", + )); + } + Ok(()) +} + +pub(super) async fn dependencies(conn: &mut PgConnection, scope: &Scope) -> Result> { + let mut blockers = Vec::new(); + // Static fragments only. These checks also run immediately before final user removal. + for (table, selector) in [ + ("api_tokens","owner_pubkey=ANY($2::bytea[])"), + ("workflows","owner_pubkey=ANY($2::bytea[])"), + ("subscriptions","owner_pubkey=ANY($2::bytea[])"), + ("channel_members","pubkey=ANY($2::bytea[])"), + ("relay_members","pubkey=ANY(SELECT encode(k,'hex') FROM unnest($2::bytea[]) k)"), + ("events","pubkey=ANY($2::bytea[]) AND kind NOT IN (0,10100,30177,30179,9035,9036)"), + ("archived_identities","NOT(pubkey=ANY(SELECT encode(k,'hex') FROM unnest($2::bytea[]) k)) AND (actor=ANY(SELECT encode(k,'hex') FROM unnest($2::bytea[]) k) OR replaced_by=ANY(SELECT encode(k,'hex') FROM unnest($2::bytea[]) k))"), + ] { + let sql=format!("SELECT EXISTS(SELECT 1 FROM {table} WHERE community_id=$1 AND ({selector}))"); + let exists:bool=sqlx::query_scalar(sqlx::AssertSqlSafe(sql)).bind(scope.community).bind(&scope.bytes).fetch_one(&mut *conn).await?; + if exists {blockers.push(format!("{table}: content/account cleanup or shared-reference disposition required"));} + } + // Avoid silently erasing an ownership link through the users self-FK. + let rows=sqlx::query("SELECT encode(pubkey,'hex') AS pubkey FROM users WHERE community_id=$1 AND agent_owner_pubkey=ANY($2::bytea[]) AND NOT(pubkey=ANY($2::bytea[])) LIMIT 1") + .bind(scope.community).bind(&scope.bytes).fetch_all(conn).await?; + if let Some(row) = rows.first() { + let _: String = row.try_get("pubkey")?; + blockers.push("unselected agent depends on a target identity".into()); + } + Ok(blockers) +} diff --git a/crates/buzz-db/src/store/user_deletion/profile_batches/postgres_tests.rs b/crates/buzz-db/src/store/user_deletion/profile_batches/postgres_tests.rs new file mode 100644 index 00000000000..9f314b4e94e --- /dev/null +++ b/crates/buzz-db/src/store/user_deletion/profile_batches/postgres_tests.rs @@ -0,0 +1,431 @@ +use super::*; +use nostr::{Event, EventBuilder, Keys, Kind, Tag, Timestamp}; +use sqlx::PgPool; +use std::collections::BTreeMap; + +struct Fixture { + pool: PgPool, + store: UserDeletionStore, + community: Uuid, + elsewhere: Uuid, + human: Keys, + agent: Keys, + other: Keys, + relay: Keys, +} +impl Fixture { + async fn new() -> Self { + let pool = PgPool::connect(&crate::test_support::database_url()) + .await + .unwrap(); + let store = crate::Db::from_pool(pool.clone()).user_deletion_store(); + let f = Self { + pool, + store, + community: Uuid::new_v4(), + elsewhere: Uuid::new_v4(), + human: Keys::generate(), + agent: Keys::generate(), + other: Keys::generate(), + relay: Keys::generate(), + }; + for c in [f.community, f.elsewhere] { + sqlx::query("INSERT INTO communities(id,host) VALUES($1,$2)") + .bind(c) + .bind(format!("{c}.example.org")) + .execute(&f.pool) + .await + .unwrap(); + for k in [&f.human, &f.agent, &f.other] { + sqlx::query("INSERT INTO users(community_id,pubkey,display_name) VALUES($1,$2,'profile fixture')").bind(c).bind(k.public_key().to_bytes().as_slice()).execute(&f.pool).await.unwrap(); + } + sqlx::query( + "UPDATE users SET agent_owner_pubkey=$2 WHERE community_id=$1 AND pubkey=$3", + ) + .bind(c) + .bind(f.human.public_key().to_bytes().as_slice()) + .bind(f.agent.public_key().to_bytes().as_slice()) + .execute(&f.pool) + .await + .unwrap(); + } + f + } + fn options(&self, batch_size: u16) -> ProfileBatchOptions { + ProfileBatchOptions { + community: self.community, + pubkey: self.human.public_key().to_hex(), + agent_pubkeys: vec![self.agent.public_key().to_hex()], + relay_pubkeys: vec![self.relay.public_key().to_hex()], + batch_size, + max_items: 1000, + } + } + async fn event( + &self, + c: Uuid, + key: &Keys, + kind: u16, + tags: Vec>, + content: &str, + ) -> Event { + let event = EventBuilder::new(Kind::Custom(kind), content) + .tags(tags.into_iter().map(|v| Tag::parse(v).unwrap())) + .custom_created_at(Timestamp::now()) + .sign_with_keys(key) + .unwrap(); + sqlx::query("INSERT INTO events(community_id,id,pubkey,created_at,kind,tags,content,sig) VALUES($1,$2,$3,$4,$5,$6,$7,$8)") + .bind(c).bind(event.id.to_bytes().as_slice()).bind(event.pubkey.to_bytes().as_slice()) + .bind(chrono::DateTime::from_timestamp(event.created_at.as_secs() as i64,0).unwrap()) + .bind(i32::from(kind)).bind(serde_json::to_value(&event.tags).unwrap()).bind(&event.content).bind(event.sig.serialize().as_slice()) + .execute(&self.pool).await.unwrap(); + event + } + async fn profiles(&self) { + for c in [self.community, self.elsewhere] { + self.event(c, &self.human, 0, vec![], "human profile").await; + self.event(c, &self.agent, 10100, vec![], "agent profile") + .await; + self.event(c, &self.other, 0, vec![], "surviving profile") + .await; + self.event( + c, + &self.human, + 30177, + vec![vec!["d".into(), self.agent.public_key().to_hex()]], + "configuration", + ) + .await; + } + let subject = self.human.public_key().to_hex(); + let event = self + .event( + self.community, + &self.relay, + 30382, + vec![ + vec!["d".into(), subject.clone()], + vec!["p".into(), subject.clone()], + ], + "", + ) + .await; + sqlx::query("INSERT INTO nip_fi_profile_heads(community_id,pubkey,issuer,issued_at,event) VALUES($1,$2,'https://issuer.example.org',1,$3)") + .bind(self.community).bind(&subject).bind(serde_json::to_value(&event).unwrap()).execute(&self.pool).await.unwrap(); + sqlx::query("INSERT INTO event_mentions(community_id,pubkey_hex,event_id,event_created_at,event_kind) VALUES($1,$2,$3,now(),30382)") + .bind(self.community).bind(&subject).bind(event.id.to_bytes().as_slice()).execute(&self.pool).await.unwrap(); + for key in [&self.human, &self.other] { + sqlx::query("INSERT INTO archived_identities(community_id,pubkey,consent_path,actor,request_event_id) VALUES($1,$2,'self',$2,$3)") + .bind(self.community).bind(key.public_key().to_hex()).bind("a".repeat(64)).execute(&self.pool).await.unwrap(); + } + self.event( + self.community, + &self.relay, + 13535, + vec![ + vec!["-".into()], + vec!["p".into(), subject], + vec!["p".into(), self.other.public_key().to_hex()], + ], + "", + ) + .await; + } +} + +async fn export(pool: &PgPool) -> BTreeMap { + let tables: Vec = sqlx::query_scalar( + "SELECT tablename FROM pg_tables WHERE schemaname='public' ORDER BY tablename", + ) + .fetch_all(pool) + .await + .unwrap(); + let mut result = BTreeMap::new(); + for table in tables { + let sql=format!("SELECT COALESCE(jsonb_agg(to_jsonb(t) ORDER BY to_jsonb(t)::text),'[]'::jsonb) FROM public.\"{}\" t",table.replace('"',"\"\"")); + result.insert( + table, + sqlx::query_scalar(sqlx::AssertSqlSafe(sql)) + .fetch_one(pool) + .await + .unwrap(), + ); + } + result +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn preview_delete_retry_preserve_other_identities_and_communities() { + let f = Fixture::new().await; + f.profiles().await; + let before = export(&f.pool).await; + let mut preview = Vec::new(); + let opts = f.options(2); + let expected = f + .store + .run_profile_batches(&opts, false, None, &mut preview) + .await + .unwrap(); + assert_eq!(before, export(&f.pool).await, "preview changed database"); + assert!(expected.items > 2); + assert!(expected.batches > 1); + let output = String::from_utf8(preview).unwrap(); + assert!(output.contains("replace_archive_snapshot")); + assert!(!output.contains("configuration")); + assert!(!output.contains("human profile")); + let mut deletion = Vec::new(); + let actual = f + .store + .run_profile_batches( + &opts, + true, + Some(&f.relay.secret_key().to_secret_hex()), + &mut deletion, + ) + .await + .unwrap(); + assert_eq!(actual.items, expected.items); + let after = export(&f.pool).await; + for (table, rows) in &before { + if ![ + "events", + "users", + "nip_fi_profile_heads", + "archived_identities", + "event_mentions", + ] + .contains(&table.as_str()) + && !table.starts_with("events_") + { + assert_eq!(rows, &after[table], "unexpected change to {table}"); + } + } + let remaining: Vec> = + sqlx::query_scalar("SELECT pubkey FROM users WHERE community_id=$1") + .bind(f.community) + .fetch_all(&f.pool) + .await + .unwrap(); + assert_eq!(remaining, vec![f.other.public_key().to_bytes().to_vec()]); + for (table, old_rows) in &before { + for row in old_rows.as_array().unwrap() { + let key = row["pubkey"] + .as_str() + .unwrap_or("") + .trim_start_matches("\\x"); + if row["community_id"] == json!(f.elsewhere) || key == f.other.public_key().to_hex() { + assert!( + after[table].as_array().unwrap().contains(row), + "survivor changed in {table}" + ); + } + } + } + let other_count: i64 = sqlx::query_scalar("SELECT count(*) FROM users WHERE community_id=$1") + .bind(f.elsewhere) + .fetch_one(&f.pool) + .await + .unwrap(); + assert_eq!(other_count, 3); + let snapshot=sqlx::query("SELECT id,pubkey,extract(epoch FROM created_at)::bigint AS created_at,kind,tags,content,sig FROM events WHERE community_id=$1 AND kind=13535").bind(f.community).fetch_one(&f.pool).await.unwrap(); + use sqlx::Row; + let signed:Event=serde_json::from_value(json!({"id":hex::encode(snapshot.get::,_>("id")),"pubkey":hex::encode(snapshot.get::,_>("pubkey")),"created_at":snapshot.get::("created_at"),"kind":13535,"tags":snapshot.get::("tags"),"content":snapshot.get::("content"),"sig":hex::encode(snapshot.get::,_>("sig"))})).unwrap(); + signed.verify().unwrap(); + assert_eq!( + signed + .tags + .iter() + .filter(|t| t.as_slice().first().map(String::as_str) == Some("p")) + .count(), + 1 + ); + assert!(serde_json::to_string(&signed.tags) + .unwrap() + .contains(&f.other.public_key().to_hex())); + assert!(!serde_json::to_string(&signed.tags) + .unwrap() + .contains(&f.human.public_key().to_hex())); + let second = f + .store + .run_profile_batches(&opts, true, None, &mut Vec::new()) + .await + .unwrap(); + assert_eq!(second.items, 0); + assert_eq!(after, export(&f.pool).await); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn limits_dependencies_and_signer_fail_before_any_mutation() { + let f = Fixture::new().await; + f.profiles().await; + let before = export(&f.pool).await; + let mut opts = f.options(1); + opts.max_items = 1; + assert!(f + .store + .run_profile_batches(&opts, true, None, &mut Vec::new()) + .await + .is_err()); + opts.max_items = 1000; + for key in [None, Some(f.other.secret_key().to_secret_hex())] { + assert!(f + .store + .run_profile_batches(&opts, true, key.as_deref(), &mut Vec::new()) + .await + .is_err()); + assert_eq!(before, export(&f.pool).await); + } + opts.relay_pubkeys.clear(); + assert!(f + .store + .run_profile_batches(&opts, false, None, &mut Vec::new()) + .await + .is_err()); + assert_eq!(before, export(&f.pool).await); + opts = f.options(1); + f.event( + f.community, + &f.agent, + 1, + vec![], + "content must be cleaned first", + ) + .await; + let before = export(&f.pool).await; + let mut output = Vec::new(); + assert!(f + .store + .run_profile_batches( + &opts, + true, + Some(&f.relay.secret_key().to_secret_hex()), + &mut output + ) + .await + .is_err()); + assert!(String::from_utf8(output) + .unwrap() + .contains("content/account cleanup")); + assert_eq!(before, export(&f.pool).await); +} + +struct FailAfterCommit; +impl Write for FailAfterCommit { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + if String::from_utf8_lossy(bytes).contains("batch_committed") { + Err(std::io::Error::other("injected output loss")) + } else { + Ok(bytes.len()) + } + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} +#[tokio::test] +#[ignore = "requires Postgres"] +async fn commit_before_output_loss_resumes_from_same_target_scope() { + let f = Fixture::new().await; + f.profiles().await; + let opts = f.options(2); + assert!(f + .store + .run_profile_batches( + &opts, + true, + Some(&f.relay.secret_key().to_secret_hex()), + &mut FailAfterCommit + ) + .await + .is_err()); + let mut output = Vec::new(); + f.store + .run_profile_batches( + &opts, + true, + Some(&f.relay.secret_key().to_secret_hex()), + &mut output, + ) + .await + .unwrap(); + assert!(String::from_utf8(output) + .unwrap() + .contains("delete_complete")); + assert_eq!( + f.store + .run_profile_batches(&opts, true, None, &mut Vec::new()) + .await + .unwrap() + .items, + 0 + ); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn changed_source_rolls_back_batch_and_changed_owner_is_refused() { + let f = Fixture::new().await; + f.event(f.community, &f.human, 0, vec![], "initial").await; + let mut conn = f.pool.acquire().await.unwrap(); + let plan = plan::build(&mut conn, &f.options(100)).await.unwrap(); + sqlx::query("UPDATE events SET content='changed' WHERE community_id=$1") + .bind(f.community) + .execute(&f.pool) + .await + .unwrap(); + let mut raw = f.pool.begin().await.unwrap(); + lock(&mut raw, &plan.scope).await.unwrap(); + let mut tx = crate::AdmittedTx::admit( + raw, + &crate::deletion::DeletionStore::new(f.pool.clone()), + buzz_core::CommunityId::from_uuid(f.community), + ) + .await + .unwrap(); + assert!( + rows::apply(&mut tx, &plan.scope, &plan.ops[0], &Default::default()) + .await + .is_err() + ); + tx.rollback().await.unwrap(); + let before = export(&f.pool).await; + sqlx::query("UPDATE users SET agent_owner_pubkey=$2 WHERE community_id=$1 AND pubkey=$3") + .bind(f.community) + .bind(f.other.public_key().to_bytes().as_slice()) + .bind(f.agent.public_key().to_bytes().as_slice()) + .execute(&f.pool) + .await + .unwrap(); + assert!(f + .store + .run_profile_batches(&f.options(100), true, None, &mut Vec::new()) + .await + .is_err()); + assert_eq!(before["events"], export(&f.pool).await["events"]); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn mismatched_verified_subject_and_survivor_archive_actor_are_not_erased() { + let f = Fixture::new().await; + f.event( + f.community, + &f.relay, + 30382, + vec![ + vec!["p".into(), f.human.public_key().to_hex()], + vec!["d".into(), f.other.public_key().to_hex()], + ], + "", + ) + .await; + let before = export(&f.pool).await; + assert!(f + .store + .run_profile_batches(&f.options(100), true, None, &mut Vec::new()) + .await + .is_err()); + assert_eq!(before, export(&f.pool).await); +} diff --git a/crates/buzz-db/src/store/user_deletion/profile_batches/rows.rs b/crates/buzz-db/src/store/user_deletion/profile_batches/rows.rs new file mode 100644 index 00000000000..5d551cf0f33 --- /dev/null +++ b/crates/buzz-db/src/store/user_deletion/profile_batches/rows.rs @@ -0,0 +1,156 @@ +use super::*; +use sqlx::Row; +use std::collections::HashMap; + +pub(super) struct Table { + pub name: &'static str, + key: &'static str, + identity: &'static str, + pub selector: &'static str, +} + +pub(super) struct Operation { + pub table: &'static Table, + pub key: Value, + pub fingerprint: String, + pub snapshot: Option, +} +impl Operation { + pub fn cost(&self) -> usize { + if self.snapshot.is_some() { + 2 + } else { + 1 + } + } + pub fn description(&self) -> Value { + json!({"table":self.table.name,"key":self.key, + "action":if self.snapshot.is_some() {"replace_archive_snapshot"} else {"delete"}}) + } +} + +pub(super) const EVENTS: Table = Table { + name: "events", + key: "jsonb_build_object('id',t.id,'created_at',t.created_at)", + identity: "id=($2->>'id')::bytea AND created_at=($2->>'created_at')::timestamptz", + selector: "t.id=ANY($3::bytea[])", +}; +pub(super) const HEADS: Table = Table { + name: "nip_fi_profile_heads", + key: "jsonb_build_object('pubkey',t.pubkey)", + identity: "pubkey=$2->>'pubkey'", + selector: "t.pubkey=ANY(SELECT encode(k,'hex') FROM unnest($2::bytea[]) k)", +}; +pub(super) const ARCHIVES: Table = Table { + name: "archived_identities", + key: "jsonb_build_object('pubkey',t.pubkey)", + identity: "pubkey=$2->>'pubkey'", + selector: HEADS.selector, +}; +pub(super) const USERS: Table = Table { + name: "users", + key: "jsonb_build_object('pubkey',t.pubkey)", + identity: "pubkey=($2->>'pubkey')::bytea", + selector: "t.pubkey=ANY($2::bytea[])", +}; + +pub(super) const CHILDREN: &[Table] = &[ + Table { name:"event_mentions", key:"jsonb_build_object('pubkey_hex',t.pubkey_hex,'event_id',t.event_id)", + identity:"pubkey_hex=$2->>'pubkey_hex' AND event_id=($2->>'event_id')::bytea", selector:"t.event_id=ANY($3::bytea[])" }, + Table { name:"reactions", key:"jsonb_build_object('event_created_at',t.event_created_at,'event_id',t.event_id,'pubkey',t.pubkey,'emoji',t.emoji)", + identity:"event_created_at=($2->>'event_created_at')::timestamptz AND event_id=($2->>'event_id')::bytea AND pubkey=($2->>'pubkey')::bytea AND emoji=$2->>'emoji'", + selector:"t.event_id=ANY($3::bytea[]) OR t.reaction_event_id=ANY($3::bytea[])" }, + Table { name:"push_match_queue", key:"jsonb_build_object('event_id',t.event_id)", identity:"event_id=($2->>'event_id')::bytea", selector:"t.event_id=ANY($3::bytea[])" }, + Table { name:"push_wake_outbox", key:"jsonb_build_object('id',t.id)", identity:"id=($2->>'id')::uuid", selector:"t.event_id=ANY($3::bytea[])" }, + Table { name:"operator_listener_outbox", key:"jsonb_build_object('id',t.id)", identity:"id=($2->>'id')::uuid", selector:"t.event_id=ANY($3::bytea[])" }, + Table { name:"delivery_log", key:"jsonb_build_object('id',t.id,'delivered_at',t.delivered_at)", identity:"id=($2->>'id')::bigint AND delivered_at=($2->>'delivered_at')::timestamptz", selector:"t.event_id=ANY($3::bytea[])" }, +]; + +pub(super) async fn collect( + conn: &mut PgConnection, + plan: &mut Plan, + table: &'static Table, + ids: &[Vec], + max: u32, +) -> Result<()> { + let sql = format!("SELECT {} AS key, encode(sha256(convert_to(to_jsonb(t)::text,'UTF8')),'hex') AS fingerprint FROM {} t \ + WHERE community_id=$1 AND ({}) AND cardinality($2::bytea[])>=0 AND cardinality($3::bytea[])>=0 \ + ORDER BY {} LIMIT $4", table.key, table.name, table.selector, table.key); + let rows = sqlx::query(sqlx::AssertSqlSafe(sql)) + .bind(plan.scope.community) + .bind(&plan.scope.bytes) + .bind(ids) + .bind((i64::from(max).saturating_sub(plan.ops.len() as i64) + 1).min(65_537)) + .fetch_all(conn) + .await?; + for row in rows { + push( + plan, + Operation { + table, + key: row.try_get("key")?, + fingerprint: row.try_get("fingerprint")?, + snapshot: None, + }, + max, + )?; + } + Ok(()) +} + +pub(super) fn push(plan: &mut Plan, op: Operation, max: u32) -> Result<()> { + if plan.ops.len() >= 65_536 { + return Err(invalid( + "profile plan exceeds 65536-operation memory budget; no deletion performed", + )); + } + if plan.ops.len() >= max as usize { + return Err(invalid( + "profile plan exceeds max-items; no deletion performed", + )); + } + // Keys are bounded; the full source payload never enters the plan or output. + if serde_json::to_vec(&op.key)?.len() > 1024 { + return Err(invalid("oversized profile row key")); + } + plan.ops.push(op); + Ok(()) +} + +pub(super) async fn apply( + tx: &mut crate::AdmittedTx, + scope: &Scope, + op: &Operation, + replacements: &HashMap, +) -> Result<()> { + if op.table.name == "users" { + let blockers = plan::dependencies(tx.conn(), scope).await?; + if !blockers.is_empty() { + return Err(invalid(format!( + "identity removal blocked: {}", + blockers.join(", ") + ))); + } + } + let changed = if op.snapshot.is_some() { + events::replace_snapshot(tx, scope, op, replacements).await? + } else { + let sql = format!( + "DELETE FROM {} t WHERE community_id=$1 AND ({}) AND encode(sha256(convert_to(to_jsonb(t)::text,'UTF8')),'hex')=$3", + op.table.name, op.table.identity + ); + sqlx::query(sqlx::AssertSqlSafe(sql)) + .bind(scope.community) + .bind(&op.key) + .bind(&op.fingerprint) + .execute(tx.conn()) + .await? + .rows_affected() + }; + if changed != 1 { + return Err(invalid( + "selected profile row changed; current batch rolled back; re-preview", + )); + } + Ok(()) +} diff --git a/crates/buzz-deletion/src/user.rs b/crates/buzz-deletion/src/user.rs index 93d1766fdb3..3aed20c151e 100644 --- a/crates/buzz-deletion/src/user.rs +++ b/crates/buzz-deletion/src/user.rs @@ -7,6 +7,8 @@ use uuid::Uuid; /// Preview real memberships or prepare and execute synthetic deletion requests. #[derive(Debug, Subcommand)] pub enum Command { + /// Preview or delete profiles in one community; deletion requires stopped writers. + ProfileBatches(profile_batches::Args), /// Print real current memberships as JSON; does not save or execute a request. Inventory { /// Demo fixture (default), hex public key, or npub. Current memberships only. @@ -74,6 +76,10 @@ pub enum Command { /// Run inventory discovery or synthetic workflow commands against PostgreSQL. pub async fn run(command: Command) -> Result { + let command = match command { + Command::ProfileBatches(args) => return profile_batches::run(args).await, + other => other, + }; let db = if matches!(command, Command::Inventory { .. }) { buzz_db::Db::connect_cold_start( buzz_db::DbConfig { @@ -91,6 +97,7 @@ pub async fn run(command: Command) -> Result { }; let store = db.entity_deletion_store(); match command { + Command::ProfileBatches(_) => anyhow::bail!("profile command was not dispatched"), Command::Inventory { pubkey } => { crate::print_json(&inventory::generate(&db, &pubkey).await?)?; } @@ -154,6 +161,7 @@ mod handlers; mod inventory; /// Standalone delegation of an owned community to community deletion. pub mod owned_community; +mod profile_batches; /// Read-only summaries of locally saved request progress and external waits. pub mod summary; mod transition; diff --git a/crates/buzz-deletion/src/user/profile_batches.rs b/crates/buzz-deletion/src/user/profile_batches.rs new file mode 100644 index 00000000000..f392f30d524 --- /dev/null +++ b/crates/buzz-deletion/src/user/profile_batches.rs @@ -0,0 +1,120 @@ +//! Standalone profile command. No workflow stages are enabled here. +use anyhow::Result; +use buzz_db::user_deletion::profile_batches::ProfileBatchOptions; +use uuid::Uuid; + +/// Scope and limits for offline profile cleanup. +#[derive(Debug, clap::Args)] +pub struct Args { + /// Human public key (hex or npub); includes directly owned agents. + #[arg(long, value_parser = parse_key)] + pubkey: String, + /// One explicit surviving community, including former memberships. + #[arg(long)] + community: Uuid, + /// Saved agent key for retry after its identity row disappeared; repeatable. + #[arg(long, value_parser = parse_key)] + agent_pubkey: Vec, + /// Trusted relay signer for verified profiles and archive events; repeatable. + #[arg(long, value_parser = parse_key)] + relay_pubkey: Vec, + /// Print proposed rows without writing anything (the default). + #[arg(long, alias = "read-only", conflicts_with = "delete")] + print_only: bool, + /// Apply batches. Stop relay and external writers; finish content/account/media cleanup first. + #[arg(long, conflicts_with = "print_only")] + delete: bool, + /// Maximum row mutations per transaction, 1–100. + #[arg(long, default_value_t = 100, value_parser = clap::value_parser!(u16).range(1..=100))] + batch_size: u16, + /// Maximum planned row mutations; exceeding the limit fails before deletion. + #[arg(long, default_value_t = 100_000, value_parser = clap::value_parser!(u32).range(1..=1_000_000))] + max_items: u32, +} + +fn parse_key(value: &str) -> std::result::Result { + buzz_db::user_deletion::normalize_user_deletion_pubkey(value).map_err(|e| e.to_string()) +} + +pub(super) async fn run(args: Args) -> Result { + let db = buzz_db::Db::connect_cold_start( + buzz_db::DbConfig { + database_url: crate::required_env("DATABASE_URL")?, + max_connections: 1, + min_connections: 0, + default_transaction_read_only: !args.delete, + ..Default::default() + }, + "profile_batches", + ) + .await?; + // Never parse, require or print a private key during preview. + let secret = if args.delete { + std::env::var("BUZZ_RELAY_PRIVATE_KEY").ok() + } else { + None + }; + db.user_deletion_store() + .run_profile_batches( + &ProfileBatchOptions { + community: args.community, + pubkey: args.pubkey, + agent_pubkeys: args.agent_pubkey, + relay_pubkeys: args.relay_pubkey, + batch_size: args.batch_size, + max_items: args.max_items, + }, + args.delete, + secret.as_deref(), + &mut std::io::stdout(), + ) + .await?; + Ok(0) +} + +#[cfg(test)] +mod tests { + use super::*; + use clap::Parser; + #[derive(Parser)] + struct Cli { + #[command(flatten)] + args: Args, + } + + #[test] + fn preview_is_default_and_delete_is_explicit() { + let base = [ + "profile-batches", + "--pubkey", + "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", + "--community", + "00000000-0000-0000-0000-000000000001", + ]; + for flag in [None, Some("--print-only"), Some("--read-only")] { + assert!( + !Cli::try_parse_from(base.into_iter().chain(flag)) + .unwrap() + .args + .delete + ); + } + assert!( + Cli::try_parse_from(base.into_iter().chain(["--delete"])) + .unwrap() + .args + .delete + ); + for flag in ["--print-only", "--read-only"] { + assert!(Cli::try_parse_from(base.into_iter().chain([flag, "--delete"])).is_err()); + } + for extra in [ + ["--batch-size", "0"], + ["--batch-size", "101"], + ["--max-items", "0"], + ["--pubkey", "bad"], + ] { + assert!(Cli::try_parse_from(base.into_iter().chain(extra)).is_err()); + } + } +} diff --git a/docs/profile-cleanup.md b/docs/profile-cleanup.md new file mode 100644 index 00000000000..a1991c0790d --- /dev/null +++ b/docs/profile-cleanup.md @@ -0,0 +1,99 @@ +# Standalone profile cleanup + +`buzz-admin user-deletions profile-batches` previews or removes profile data in +one explicit community. This is the identity step after content, account and +media cleanup. It does not enable the user-deletion workflow or declare complete +account erasure. + +```sh +# DATABASE_URL selects the operator database. Preview is the default. +buzz-admin user-deletions profile-batches \ + --pubkey --community --print-only + +# --read-only is an alias for --print-only. +# Stop the relay and external writers and finish earlier cleanup first. +buzz-admin user-deletions profile-batches \ + --pubkey --community --delete +``` + +The human and directly owned agent keys are resolved through `users`, including +ownership found in other communities. Every mutation is limited to `--community`. +A local agent row owned by someone else, a changed owner, or an unselected child +agent blocks execution. The output prints the complete `target_pubkeys`. Save it; +repeat `--agent-pubkey ` for those agents on retries after identity rows have +been removed. Explicit agent keys are operator-supplied saved scope, not evidence +of authorization. This command requires privileged database access. + +The supported families are ordinary profiles (0/10100), owner-authored managed +agent records (30177/30179), verified profiles (30382), archive requests and +deltas (9035/9036/8002/8003), archive snapshots (13535), `nip_fi_profile_heads`, +`archived_identities`, and final `users` rows. Event-dependent mention, reaction +and delivery projections are removed before their source events. Agent identity +rows go before the human row. Reserved kind 30179 is cleaned only if stored; +this command does not enable its ingestion or decrypt its payload. + +Verified profiles are selected by their matching `d`/`p` subject, not the event +author. Supply `--relay-pubkey ` for each independently verified +relay signer. A missing or untrusted signer stops the operation. The same trust +rule applies to archive deltas and snapshots. Human-signed requests about another +identity and archive actor/replacement references on surviving identities need +an explicit shared-history disposition; the command reports them as blockers. + +Shared archive snapshots are rebuilt from the retained canonical archive rows. +The snapshot replacement is a fresh signed event; no old signature is reused. +Deletion requires `BUZZ_RELAY_PRIVATE_KEY` matching the affected snapshot signer. +Preview never requires or reads this key. Historical snapshots that require a +different signing key remain blocked pending reconciliation. Do not pass secrets +on the command line or include them in logs. + +Each JSON line describes the scope, proposed batch, committed batch, or final +summary. Batches default to 100 row mutations; `--batch-size` accepts 1–100. +Replacing a snapshot costs two mutations (delete and insert in one transaction), +so it requires a batch size of at least two. `--max-items` defaults to 100,000; +exceeding it fails before deletion. Additional memory limits cap a plan at 65,536 +operations and candidate tags at 32 MiB (64 KiB per event); archive snapshots +support up to 10,000 retained identities. Exceeding any limit is an error, never +a successful partial preview. SQL statements have a 30-second timeout and locks +a three-second timeout; large accounts can require a separately reviewed plan. + +Before mutations, the command rejects remaining credentials, memberships, +workflows, subscriptions, non-profile authored content and unresolved archive +references. It retains replay watermarks, deletion fences, requests, approvals, +history, repositories and media objects. Media cleanup must preserve its source +evidence before this command removes avatar/configuration references. + +Each committed batch survives interruption. Rerun with the saved target keys to +plan the remaining rows. Source fingerprints and ownership are rechecked inside +the batch transaction; a mismatch rolls back that batch. A failure after commit +but before output is an error and does not mean the batch rolled back. No success +marker is printed if prerequisites or final profile checks fail. The final +summary always has `account_erasure_complete: false`. + +The stopped-writer requirement includes pending login-triggered verified-profile +publication and external agent/config writers. This command does not add online +admission fencing or invalidate client caches. Restart/refresh the supported +serving processes and clients as part of the full deletion procedure. Retaining +replay records alone does not prove every writer is fenced. Ordinary verified +profiles remain historical records; explicit operator erasure is a separate +exception to normal refresh behavior. + +## Local verification + +Use a disposable database and relay, following `TESTING.md`; do not reuse a +Desktop database. Seed a human, two owned agents, a survivor, and a second +community. Include ordinary/verified profiles, managed configuration and a +shared archive snapshot. Complete content/account cleanup in the first community. + +1. Export every table and the object inventory. Run print-only with the known + relay public key. Compare every selected key with the expected inventory and + confirm all exports are unchanged. +2. Stop writers. Run delete with the same scope and relay signing key. Compare + proposed and committed keys and the surviving data, including the second + community. Verify the new shared snapshot signature and survivor list. +3. Rerun with the saved agent keys; expect zero operations. Interrupt a multi-batch + run and repeat to confirm recovery. Introduce an unresolved dependency or a + wrong signer and confirm no deletion occurs. +4. Restart the isolated relay and reload clients. Check profile-event queries, + directory/name search and NIP-05. Test old-event replay and fresh admission + under the full deletion procedure's write restrictions. Report any recreation; + the standalone database result does not certify online enforcement. From af5d8cadffe39368159a67bf4a047bfffe162b3c Mon Sep 17 00:00:00 2001 From: Ravneet Arora Date: Mon, 16 Nov 2026 16:34:50 -0500 Subject: [PATCH 2/5] fix(deletion): refresh profile agent ownership Discover direct agents within the selected community on each run and retry. Keep profile cleanup ahead of identity removal and retain original keys only for final inspection. Co-authored-by: maincourse <37ce551b493d4a998caf030929c47bce0b6a0e43f1178b3a63c4151d7c16b76e@buzz.block.builderlab.xyz> Signed-off-by: Ravneet Arora --- .../user_deletion/profile_batches/events.rs | 2 +- .../user_deletion/profile_batches/mod.rs | 44 +-- .../profile_batches/ownership.rs | 42 +++ .../user_deletion/profile_batches/plan.rs | 34 +-- .../profile_batches/postgres_tests.rs | 267 +++++++++++++++++- .../buzz-deletion/src/user/profile_batches.rs | 5 +- docs/profile-cleanup.md | 25 +- 7 files changed, 357 insertions(+), 62 deletions(-) create mode 100644 crates/buzz-db/src/store/user_deletion/profile_batches/ownership.rs diff --git a/crates/buzz-db/src/store/user_deletion/profile_batches/events.rs b/crates/buzz-db/src/store/user_deletion/profile_batches/events.rs index f4f8c90f9dc..9eeac1d1d9b 100644 --- a/crates/buzz-db/src/store/user_deletion/profile_batches/events.rs +++ b/crates/buzz-db/src/store/user_deletion/profile_batches/events.rs @@ -103,7 +103,7 @@ pub(super) async fn select( let agent = subject(&tags, "d")?; if authored && !scope.targets.contains(&agent) { return Err(invalid( - "managed definition names an unselected agent; save its inventory first", + "managed definition names an agent not currently owned in this community", )); } if scope.targets.contains(&agent) && author != scope.human { diff --git a/crates/buzz-db/src/store/user_deletion/profile_batches/mod.rs b/crates/buzz-db/src/store/user_deletion/profile_batches/mod.rs index b4b6c0220bf..72ca23d2ace 100644 --- a/crates/buzz-db/src/store/user_deletion/profile_batches/mod.rs +++ b/crates/buzz-db/src/store/user_deletion/profile_batches/mod.rs @@ -9,6 +9,7 @@ use std::io::Write; use uuid::Uuid; mod events; +mod ownership; mod plan; #[cfg(test)] mod postgres_tests; @@ -20,8 +21,6 @@ pub struct ProfileBatchOptions { pub community: Uuid, /// Human key as hex or npub. pub pubkey: String, - /// Additional previously inventoried agents, retained across retries. - pub agent_pubkeys: Vec, /// Explicitly trusted current/historical relay signing keys. pub relay_pubkeys: Vec, /// Row mutations per transaction, 1..=100. @@ -39,12 +38,13 @@ pub struct ProfileBatchSummary { pub items: usize, /// Proposed or committed transactions. pub batches: usize, - /// Frozen human/agent keys. Supply agent keys on retries after row removal. + /// Human and current community agents discovered for this invocation. pub target_pubkeys: Vec, /// Always false; the independent final verifier owns that claim. pub account_erasure_complete: bool, } +#[derive(Clone)] struct Scope { community: Uuid, human: String, @@ -147,6 +147,7 @@ impl UserDeletionStore { )); } let mut batches = 0; + let mut remaining_targets = plan.scope.targets.clone(); for (batch_index, batch) in groups.iter().enumerate() { line( writer, @@ -169,11 +170,24 @@ impl UserDeletionStore { buzz_core::CommunityId::from_uuid(plan.scope.community), ) .await?; - plan::validate_ownership(tx.conn(), &plan.scope).await?; + ownership::recheck(tx.conn(), &plan.scope, &remaining_targets).await?; for op in *batch { rows::apply(&mut tx, &plan.scope, op, &replacements).await?; } tx.commit().await?; + for op in *batch { + if op.table.name == "users" { + let key = op.key["pubkey"] + .as_str() + .ok_or_else(|| invalid("invalid identity key"))?; + let key = key + .strip_prefix("\\x") + .ok_or_else(|| invalid("invalid identity key"))?; + if key != plan.scope.human { + remaining_targets.retain(|p| p != key); + } + } + } line( writer, &json!({"record":"batch_committed","number":batch_index+1,"items":batch.iter().map(rows::Operation::cost).sum::()}), @@ -187,27 +201,15 @@ impl UserDeletionStore { )); } if delete { - // Replan using the saved targets: identity deletion must not shrink verification scope. - let check = ProfileBatchOptions { - community: options.community, - pubkey: plan.scope.human.clone(), - agent_pubkeys: plan - .scope - .targets - .iter() - .filter(|p| *p != &plan.scope.human) - .cloned() - .collect(), - relay_pubkeys: plan.scope.relays.clone(), - batch_size: options.batch_size, - max_items: options.max_items, - }; + // Original proven keys are inspection-only: removed identities must not shrink + // final verification or become imported authority for a later invocation. let mut tx = conn.begin().await?; lock(&mut tx, &plan.scope).await?; - let remaining = plan::build(&mut tx, &check).await?; + ownership::recheck(&mut tx, &plan.scope, &remaining_targets).await?; + let remaining = plan::inspect(&mut tx, plan.scope.clone(), options.max_items).await?; if !remaining.ops.is_empty() || !remaining.blockers.is_empty() { return Err(invalid( - "profile rows or dependencies remain; rerun with the printed target keys", + "profile rows or dependencies remain; cleanup did not complete", )); } tx.commit().await?; diff --git a/crates/buzz-db/src/store/user_deletion/profile_batches/ownership.rs b/crates/buzz-db/src/store/user_deletion/profile_batches/ownership.rs new file mode 100644 index 00000000000..9b2b63ce0db --- /dev/null +++ b/crates/buzz-db/src/store/user_deletion/profile_batches/ownership.rs @@ -0,0 +1,42 @@ +use super::*; +use std::collections::BTreeSet; + +pub(super) async fn targets( + conn: &mut PgConnection, + community: Uuid, + human: &str, + lock: bool, +) -> Result> { + let sql = if lock { + "SELECT pubkey FROM users WHERE community_id=$1 AND agent_owner_pubkey=decode($2,'hex') ORDER BY pubkey LIMIT 10001 FOR SHARE" + } else { + "SELECT pubkey FROM users WHERE community_id=$1 AND agent_owner_pubkey=decode($2,'hex') ORDER BY pubkey LIMIT 10001" + }; + let agents: Vec> = sqlx::query_scalar(sql) + .bind(community) + .bind(human) + .fetch_all(conn) + .await?; + let mut targets = BTreeSet::from([human.to_owned()]); + targets.extend(agents.iter().map(hex::encode)); + if targets.len() > 10_000 { + return Err(invalid("profile target limit exceeded (10000)")); + } + Ok(targets.into_iter().collect()) +} + +pub(super) async fn recheck( + conn: &mut PgConnection, + scope: &Scope, + remaining: &[String], +) -> Result<()> { + // Lock original identities too, so transfers away cannot race validation. + sqlx::query("SELECT pubkey FROM users WHERE community_id=$1 AND pubkey=ANY($2::bytea[]) ORDER BY pubkey FOR SHARE") + .bind(scope.community).bind(&scope.bytes).fetch_all(&mut *conn).await?; + if targets(conn, scope.community, &scope.human, true).await? != remaining { + return Err(invalid( + "community agent ownership changed; retry to discover current agents", + )); + } + plan::validate_ownership(conn, scope).await +} diff --git a/crates/buzz-db/src/store/user_deletion/profile_batches/plan.rs b/crates/buzz-db/src/store/user_deletion/profile_batches/plan.rs index 0925f9b9450..f3b65f35ebf 100644 --- a/crates/buzz-db/src/store/user_deletion/profile_batches/plan.rs +++ b/crates/buzz-db/src/store/user_deletion/profile_batches/plan.rs @@ -1,21 +1,9 @@ use super::*; use sqlx::Row; -use std::collections::BTreeSet; pub(super) async fn build(conn: &mut PgConnection, options: &ProfileBatchOptions) -> Result { let human = normalize_user_deletion_pubkey(&options.pubkey)?; - let mut targets = BTreeSet::from([human.clone()]); - for p in &options.agent_pubkeys { - targets.insert(normalize_user_deletion_pubkey(p)?); - } - // Match the content command's cross-community ownership discovery; mutation stays tenant-scoped. - let agents: Vec> = sqlx::query_scalar("SELECT DISTINCT pubkey FROM users WHERE agent_owner_pubkey=decode($1,'hex') ORDER BY pubkey LIMIT 10001") - .bind(&human).fetch_all(&mut *conn).await?; - targets.extend(agents.iter().map(hex::encode)); - if targets.len() > 10_000 { - return Err(invalid("profile target limit exceeded (10000)")); - } - let targets: Vec = targets.into_iter().collect(); + let targets = ownership::targets(conn, options.community, &human, false).await?; let relays: Vec = options .relay_pubkeys .iter() @@ -43,13 +31,19 @@ pub(super) async fn build(conn: &mut PgConnection, options: &ProfileBatchOptions )); } validate_ownership(conn, &scope).await?; + inspect(conn, scope, options.max_items).await +} + +// Only callers with a scope freshly discovered by this invocation may inspect it. +// This never executes mutations; final inspection may include identities we removed. +pub(super) async fn inspect(conn: &mut PgConnection, scope: Scope, max_items: u32) -> Result { let blockers = dependencies(conn, &scope).await?; let mut plan = Plan { scope, ops: Vec::new(), blockers, }; - let selected = events::select(conn, &plan.scope, options.max_items).await?; + let selected = events::select(conn, &plan.scope, max_items).await?; let ids: Vec> = selected.iter().map(|e| e.id.clone()).collect(); // Threaded/channel-bearing data belongs to content cleanup; never break a surviving discussion. let threaded: bool = sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM thread_metadata WHERE community_id=$1 AND (event_id=ANY($2::bytea[]) OR parent_event_id=ANY($2::bytea[]) OR root_event_id=ANY($2::bytea[])))") @@ -59,7 +53,7 @@ pub(super) async fn build(conn: &mut PgConnection, options: &ProfileBatchOptions .push("selected profiles have thread dependencies; content cleanup required".into()); } for table in rows::CHILDREN { - rows::collect(conn, &mut plan, table, &ids, options.max_items).await?; + rows::collect(conn, &mut plan, table, &ids, max_items).await?; } let mut snapshots = Vec::new(); for event in selected { @@ -72,17 +66,17 @@ pub(super) async fn build(conn: &mut PgConnection, options: &ProfileBatchOptions if op.snapshot.is_some() { snapshots.push(op); } else { - rows::push(&mut plan, op, options.max_items)?; + rows::push(&mut plan, op, max_items)?; } } - rows::collect(conn, &mut plan, &rows::HEADS, &[], options.max_items).await?; - rows::collect(conn, &mut plan, &rows::ARCHIVES, &[], options.max_items).await?; + rows::collect(conn, &mut plan, &rows::HEADS, &[], max_items).await?; + rows::collect(conn, &mut plan, &rows::ARCHIVES, &[], max_items).await?; // Archive rows go first, then snapshots; retries can find stale snapshots while identities remain. for op in snapshots { - rows::push(&mut plan, op, options.max_items)?; + rows::push(&mut plan, op, max_items)?; } let before_users = plan.ops.len(); - rows::collect(conn, &mut plan, &rows::USERS, &[], options.max_items).await?; + rows::collect(conn, &mut plan, &rows::USERS, &[], max_items).await?; let human_bytea = format!("\\x{}", plan.scope.human); plan.ops[before_users..].sort_by_key(|op| op.key["pubkey"].as_str() == Some(&human_bytea)); Ok(plan) diff --git a/crates/buzz-db/src/store/user_deletion/profile_batches/postgres_tests.rs b/crates/buzz-db/src/store/user_deletion/profile_batches/postgres_tests.rs index 9f314b4e94e..383fa107e45 100644 --- a/crates/buzz-db/src/store/user_deletion/profile_batches/postgres_tests.rs +++ b/crates/buzz-db/src/store/user_deletion/profile_batches/postgres_tests.rs @@ -55,7 +55,6 @@ impl Fixture { ProfileBatchOptions { community: self.community, pubkey: self.human.public_key().to_hex(), - agent_pubkeys: vec![self.agent.public_key().to_hex()], relay_pubkeys: vec![self.relay.public_key().to_hex()], batch_size, max_items: 1000, @@ -398,12 +397,30 @@ async fn changed_source_rolls_back_batch_and_changed_owner_is_refused() { .execute(&f.pool) .await .unwrap(); - assert!(f + let mut tx = f.pool.begin().await.unwrap(); + assert!( + ownership::recheck(&mut tx, &plan.scope, &plan.scope.targets) + .await + .is_err() + ); + tx.rollback().await.unwrap(); + assert_eq!(before["events"], export(&f.pool).await["events"]); + // A new invocation excludes the transferred agent instead of trusting the old plan. + let result = f .store .run_profile_batches(&f.options(100), true, None, &mut Vec::new()) .await - .is_err()); - assert_eq!(before["events"], export(&f.pool).await["events"]); + .unwrap(); + assert_eq!(result.target_pubkeys, vec![f.human.public_key().to_hex()]); + let owner: Vec = sqlx::query_scalar( + "SELECT agent_owner_pubkey FROM users WHERE community_id=$1 AND pubkey=$2", + ) + .bind(f.community) + .bind(f.agent.public_key().to_bytes().as_slice()) + .fetch_one(&f.pool) + .await + .unwrap(); + assert_eq!(owner, f.other.public_key().to_bytes()); } #[tokio::test] @@ -429,3 +446,245 @@ async fn mismatched_verified_subject_and_survivor_archive_actor_are_not_erased() .is_err()); assert_eq!(before, export(&f.pool).await); } + +// Hooks run at the public handler's output boundary, exercising the real batch path. +struct RecordHook(F); +impl std::io::Result<()>> Write for RecordHook { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + if let Ok(record) = serde_json::from_slice(bytes) { + (self.0)(record)?; + } + Ok(bytes.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn community_ownership_and_retry_after_identity_removal() { + // Ownership elsewhere is neither conflicting local ownership nor missing local evidence. + for missing in [false, true] { + let f = Fixture::new().await; + f.event(f.community, &f.human, 0, vec![], "human").await; + f.event(f.community, &f.agent, 10100, vec![], "retain agent") + .await; + if missing { + sqlx::query("DELETE FROM users WHERE community_id=$1 AND pubkey=$2") + .bind(f.community) + .bind(f.agent.public_key().to_bytes().as_slice()) + .execute(&f.pool) + .await + .unwrap(); + } else { + sqlx::query( + "UPDATE users SET agent_owner_pubkey=$3 WHERE community_id=$1 AND pubkey=$2", + ) + .bind(f.community) + .bind(f.agent.public_key().to_bytes().as_slice()) + .bind(f.other.public_key().to_bytes().as_slice()) + .execute(&f.pool) + .await + .unwrap(); + } + let before = export(&f.pool).await; + let preview = f + .store + .run_profile_batches(&f.options(1), false, None, &mut Vec::new()) + .await + .unwrap(); + assert_eq!(preview.target_pubkeys, vec![f.human.public_key().to_hex()]); + assert_eq!(before, export(&f.pool).await); + f.store + .run_profile_batches(&f.options(1), true, None, &mut Vec::new()) + .await + .unwrap(); + let after = export(&f.pool).await; + for (table, rows) in &before { + for row in rows.as_array().unwrap() { + if row["community_id"] == json!(f.elsewhere) + || row["pubkey"] == format!("\\x{}", f.agent.public_key()) + { + assert!( + after[table].as_array().unwrap().contains(row), + "survivor changed in {table}" + ); + } + } + } + } + let f = Fixture::new().await; + f.event(f.community, &f.human, 0, vec![], "human").await; + f.event(f.community, &f.agent, 10100, vec![], "agent").await; + let mut removing_agent = false; + let mut output = RecordHook(|record: Value| { + if record["record"] == "proposed_batch" { + removing_agent = record["items"][0]["table"] == "users" + && record["items"][0]["key"]["pubkey"] == format!("\\x{}", f.agent.public_key()); + } + if record["record"] == "batch_committed" && removing_agent { + return Err(std::io::Error::other( + "lost output after agent identity commit", + )); + } + Ok(()) + }); + assert!(f + .store + .run_profile_batches(&f.options(1), true, None, &mut output) + .await + .is_err()); + let remaining: Vec> = + sqlx::query_scalar("SELECT pubkey FROM users WHERE community_id=$1") + .bind(f.community) + .fetch_all(&f.pool) + .await + .unwrap(); + assert!(!remaining.contains(&f.agent.public_key().to_bytes().to_vec())); + assert!(remaining.contains(&f.human.public_key().to_bytes().to_vec())); + let agent_events: i64 = + sqlx::query_scalar("SELECT count(*) FROM events WHERE community_id=$1 AND pubkey=$2") + .bind(f.community) + .bind(f.agent.public_key().to_bytes().as_slice()) + .fetch_one(&f.pool) + .await + .unwrap(); + assert_eq!( + agent_events, 0, + "identity removal stranded undiscoverable profile data" + ); + + let retry = f + .store + .run_profile_batches(&f.options(1), true, None, &mut Vec::new()) + .await + .unwrap(); + assert_eq!(retry.target_pubkeys, vec![f.human.public_key().to_hex()]); + assert_eq!(retry.items, 1); + assert_eq!( + f.store + .run_profile_batches(&f.options(1), true, None, &mut Vec::new()) + .await + .unwrap() + .items, + 0 + ); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[ignore = "requires Postgres"] +async fn ownership_changes_before_write_are_refused_and_retry_rediscovers() { + for change in ["transfer", "missing", "new"] { + let f = Fixture::new().await; + f.event(f.community, &f.human, 0, vec![], "human").await; + f.event(f.community, &f.agent, 10100, vec![], "agent").await; + let mut changed = false; + let mut output = RecordHook(|record: Value| { + if record["record"] == "proposed_batch" && !changed { + changed = true; + tokio::task::block_in_place(|| { + tokio::runtime::Handle::current().block_on(async { + let sql = match change { + "transfer" => "UPDATE users SET agent_owner_pubkey=$3 WHERE community_id=$1 AND pubkey=$2", + "missing" => "UPDATE users SET agent_owner_pubkey=NULL WHERE community_id=$1 AND pubkey=$2 AND $3::bytea IS NOT NULL", + _ => "UPDATE users SET agent_owner_pubkey=$2 WHERE community_id=$1 AND pubkey=$3", + }; + let key = if change == "new" { &f.human } else { &f.agent }; + sqlx::query(sql).bind(f.community).bind(key.public_key().to_bytes().as_slice()) + .bind(f.other.public_key().to_bytes().as_slice()).execute(&f.pool).await.unwrap(); + }) + }); + } + Ok(()) + }); + let before = export(&f.pool).await; + let error = f + .store + .run_profile_batches(&f.options(1), true, None, &mut output) + .await + .unwrap_err(); + assert!(error.to_string().contains("ownership changed"), "{error}"); + assert!(changed); + assert_eq!(before["events"], export(&f.pool).await["events"]); + let retry = f + .store + .run_profile_batches(&f.options(1), true, None, &mut Vec::new()) + .await + .unwrap(); + assert_eq!( + retry.target_pubkeys.len(), + if change == "new" { 3 } else { 1 } + ); + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[ignore = "requires Postgres"] +async fn final_check_keeps_removed_agent_scope_and_locks_ownership() { + let f = Fixture::new().await; + f.event(f.community, &f.agent, 10100, vec![], "initial") + .await; + let mut conn = f.pool.acquire().await.unwrap(); + let plan = plan::build(&mut conn, &f.options(1)).await.unwrap(); + let mut checked = f.pool.begin().await.unwrap(); + ownership::recheck(&mut checked, &plan.scope, &plan.scope.targets) + .await + .unwrap(); + let mut transfer = f.pool.begin().await.unwrap(); + sqlx::query("SET LOCAL lock_timeout='100ms'") + .execute(&mut *transfer) + .await + .unwrap(); + let error = + sqlx::query("UPDATE users SET agent_owner_pubkey=$3 WHERE community_id=$1 AND pubkey=$2") + .bind(f.community) + .bind(f.agent.public_key().to_bytes().as_slice()) + .bind(f.other.public_key().to_bytes().as_slice()) + .execute(&mut *transfer) + .await + .unwrap_err(); + assert_eq!( + error.as_database_error().unwrap().code().as_deref(), + Some("55P03") + ); + transfer.rollback().await.unwrap(); + checked.rollback().await.unwrap(); + drop(conn); + + let mut removing_human = false; + let mut inserted = false; + let mut output = RecordHook(|record: Value| { + if record["record"] == "proposed_batch" { + removing_human = record["items"][0]["table"] == "users" + && record["items"][0]["key"]["pubkey"] == format!("\\x{}", f.human.public_key()); + } + if record["record"] == "batch_committed" && removing_human { + // Simulate an out-of-contract writer: final verification must still see + // the erased agent's residual data after ownership discovery shrinks. + tokio::task::block_in_place(|| { + tokio::runtime::Handle::current().block_on(f.event( + f.community, + &f.agent, + 10100, + vec![], + "late residual profile", + )) + }); + inserted = true; + } + Ok(()) + }); + let error = f + .store + .run_profile_batches(&f.options(1), true, None, &mut output) + .await + .unwrap_err(); + assert!(inserted); + assert!( + error + .to_string() + .contains("profile rows or dependencies remain"), + "{error}" + ); +} diff --git a/crates/buzz-deletion/src/user/profile_batches.rs b/crates/buzz-deletion/src/user/profile_batches.rs index f392f30d524..3e83a890810 100644 --- a/crates/buzz-deletion/src/user/profile_batches.rs +++ b/crates/buzz-deletion/src/user/profile_batches.rs @@ -12,9 +12,6 @@ pub struct Args { /// One explicit surviving community, including former memberships. #[arg(long)] community: Uuid, - /// Saved agent key for retry after its identity row disappeared; repeatable. - #[arg(long, value_parser = parse_key)] - agent_pubkey: Vec, /// Trusted relay signer for verified profiles and archive events; repeatable. #[arg(long, value_parser = parse_key)] relay_pubkey: Vec, @@ -59,7 +56,6 @@ pub(super) async fn run(args: Args) -> Result { &ProfileBatchOptions { community: args.community, pubkey: args.pubkey, - agent_pubkeys: args.agent_pubkey, relay_pubkeys: args.relay_pubkey, batch_size: args.batch_size, max_items: args.max_items, @@ -113,6 +109,7 @@ mod tests { ["--batch-size", "101"], ["--max-items", "0"], ["--pubkey", "bad"], + ["--agent-pubkey", base[2]], ] { assert!(Cli::try_parse_from(base.into_iter().chain(extra)).is_err()); } diff --git a/docs/profile-cleanup.md b/docs/profile-cleanup.md index a1991c0790d..d77b36eb2eb 100644 --- a/docs/profile-cleanup.md +++ b/docs/profile-cleanup.md @@ -16,13 +16,12 @@ buzz-admin user-deletions profile-batches \ --pubkey --community --delete ``` -The human and directly owned agent keys are resolved through `users`, including -ownership found in other communities. Every mutation is limited to `--community`. -A local agent row owned by someone else, a changed owner, or an unselected child -agent blocks execution. The output prints the complete `target_pubkeys`. Save it; -repeat `--agent-pubkey ` for those agents on retries after identity rows have -been removed. Explicit agent keys are operator-supplied saved scope, not evidence -of authorization. This command requires privileged database access. +The human and directly owned agents are discovered afresh from `users` in the +selected community on every preview, delete and retry. Ownership in another +community never authorizes cleanup here. A changed ownership set or unselected +child agent blocks a write batch. The output prints the discovered `target_pubkeys` +for inspection; saved agent keys are not accepted as deletion authority. +This command requires privileged database access. The supported families are ordinary profiles (0/10100), owner-authored managed agent records (30177/30179), verified profiles (30382), archive requests and @@ -62,9 +61,11 @@ references. It retains replay watermarks, deletion fences, requests, approvals, history, repositories and media objects. Media cleanup must preserve its source evidence before this command removes avatar/configuration references. -Each committed batch survives interruption. Rerun with the saved target keys to -plan the remaining rows. Source fingerprints and ownership are rechecked inside -the batch transaction; a mismatch rolls back that batch. A failure after commit +Each committed batch survives interruption. Rerun with the same human and community +to discover the remaining agents. All profile data is removed before any identity +row, so interruption during identity removal leaves no unfinished profile data +for an agent that can no longer be discovered. Source fingerprints and the full +current ownership set are rechecked inside the batch transaction; a mismatch rolls back that batch. A failure after commit but before output is an error and does not mean the batch rolled back. No success marker is printed if prerequisites or final profile checks fail. The final summary always has `account_erasure_complete: false`. @@ -90,8 +91,8 @@ shared archive snapshot. Complete content/account cleanup in the first community 2. Stop writers. Run delete with the same scope and relay signing key. Compare proposed and committed keys and the surviving data, including the second community. Verify the new shared snapshot signature and survivor list. -3. Rerun with the saved agent keys; expect zero operations. Interrupt a multi-batch - run and repeat to confirm recovery. Introduce an unresolved dependency or a +3. Rerun with the same human and community; expect zero operations. Interrupt a + multi-batch run and repeat to confirm recovery. Introduce an unresolved dependency or a wrong signer and confirm no deletion occurs. 4. Restart the isolated relay and reload clients. Check profile-event queries, directory/name search and NIP-05. Test old-event replay and fresh admission From 92aa9c216d7b958e8921d38d7bd801b803a626e9 Mon Sep 17 00:00:00 2001 From: Ravneet Arora Date: Tue, 17 Nov 2026 10:24:45 -0500 Subject: [PATCH 3/5] Block cleanup on historical archive references Select archive replacement references even after unarchive. Refuse historical requests concerning surviving identities before any mutation. Co-authored-by: maincourse <37ce551b493d4a998caf030929c47bce0b6a0e43f1178b3a63c4151d7c16b76e@buzz.block.builderlab.xyz> Signed-off-by: Ravneet Arora --- .../user_deletion/profile_batches/events.rs | 8 +- .../profile_batches/postgres_tests.rs | 90 +++++++++++++++++++ docs/profile-cleanup.md | 4 +- 3 files changed, 98 insertions(+), 4 deletions(-) diff --git a/crates/buzz-db/src/store/user_deletion/profile_batches/events.rs b/crates/buzz-db/src/store/user_deletion/profile_batches/events.rs index 9eeac1d1d9b..f31a51bcbbc 100644 --- a/crates/buzz-db/src/store/user_deletion/profile_batches/events.rs +++ b/crates/buzz-db/src/store/user_deletion/profile_batches/events.rs @@ -46,13 +46,15 @@ pub(super) async fn select( max: u32, ) -> Result> { // Scope before payload inspection. Case-insensitive subject comparison covers historical hex. + // Historical replacement references survive unarchive removing the canonical row. // The statement budget bounds the fallback tag scan; no new schema is required. let candidate_sql="SELECT id,created_at,kind,encode(pubkey,'hex') AS author,channel_id, CASE WHEN pg_column_size(tags)<=65536 THEN tags END AS tags, jsonb_build_object('id',id,'created_at',created_at) AS key,encode(sha256(convert_to(to_jsonb(e)::text,'UTF8')),'hex') AS fingerprint FROM events e WHERE community_id=$1 AND kind IN (0,10100,30177,30179,30382,9035,9036,8002,8003,13535) AND (pubkey=ANY($2::bytea[]) OR EXISTS(SELECT 1 FROM jsonb_array_elements(CASE WHEN jsonb_typeof(tags)='array' THEN tags ELSE '[]'::jsonb END) tag - WHERE (tag->>0 IN ('p','d') AND lower(tag->>1)=ANY($3::text[])) OR (tag->>0='consent' AND lower(tag->>2)=ANY($3::text[])))) + WHERE (tag->>0 IN ('p','d') AND lower(tag->>1)=ANY($3::text[])) OR (tag->>0='consent' AND lower(tag->>2)=ANY($3::text[])) + OR (kind IN (9035,9036,8002,8003) AND tag->>0='replaced-by' AND lower(tag->>1)=ANY($3::text[])))) ORDER BY created_at,id LIMIT $4"; // Bound payload memory before materializing candidate tags. The query remains read-only. let budget_sql = format!("SELECT count(*) AS count, COALESCE(sum(pg_column_size(tags)),0)::bigint AS bytes FROM ({candidate_sql}) candidates"); @@ -125,7 +127,7 @@ pub(super) async fn select( } 9035 | 9036 => { let target = subject(&tags, "p")?; - if authored && !scope.targets.contains(&target) { + if !scope.targets.contains(&target) { return Err(invalid("archive request concerns a surviving identity; shared-history disposition required")); } scope.targets.contains(&target) @@ -136,7 +138,7 @@ pub(super) async fn select( trusted(scope, &author)?; true } else { - return Err(invalid("archive delta names a target actor on a surviving identity; shared-history disposition required")); + return Err(invalid("archive delta references a target actor or replacement on a surviving identity; shared-history disposition required")); } } 13535 => { diff --git a/crates/buzz-db/src/store/user_deletion/profile_batches/postgres_tests.rs b/crates/buzz-db/src/store/user_deletion/profile_batches/postgres_tests.rs index 383fa107e45..78ce2b13ac8 100644 --- a/crates/buzz-db/src/store/user_deletion/profile_batches/postgres_tests.rs +++ b/crates/buzz-db/src/store/user_deletion/profile_batches/postgres_tests.rs @@ -688,3 +688,93 @@ async fn final_check_keeps_removed_agent_scope_and_locks_ownership() { "{error}" ); } + +async fn historical_replacement_blocks_cleanup_after_unarchive(kind: u16) { + for agent in [false, true] { + let f = Fixture::new().await; + let replacement = if agent { &f.agent } else { &f.human }; + let subject = f.other.public_key().to_hex(); + let replacement = replacement.public_key().to_hex(); + let signer = if kind == 9035 { &f.other } else { &f.relay }; + let mut tags = vec![ + vec!["-".into()], + vec!["p".into(), subject.clone()], + vec!["replaced-by".into(), replacement.clone()], + ]; + if kind == 8002 { + tags.push(vec!["consent".into(), "relay".into()]); + } + let event = f.event(f.community, signer, kind, tags, "").await; + event.verify().unwrap(); + let community = buzz_core::CommunityId::from_uuid(f.community); + assert!(crate::archived_identities::archive( + &f.pool, + community, + &subject, + "self", + &subject, + None, + Some(&replacement), + &event.id.to_hex(), + ) + .await + .unwrap()); + assert!( + crate::archived_identities::unarchive(&f.pool, community, &subject) + .await + .unwrap() + ); + assert!( + !crate::archived_identities::is_archived(&f.pool, community, &subject) + .await + .unwrap() + ); + let before = export(&f.pool).await; + for delete in [false, true] { + let mut output = Vec::new(); + let result = f + .store + .run_profile_batches(&f.options(1), delete, None, &mut output) + .await; + assert!(result.is_err(), "kind {kind}, agent {agent}, delete {delete}: unresolved historical replacement was accepted"); + assert!(result + .unwrap_err() + .to_string() + .contains("shared-history disposition required")); + assert!(!String::from_utf8(output) + .unwrap() + .contains("delete_complete")); + assert_eq!( + before, + export(&f.pool).await, + "blocked cleanup mutated database" + ); + } + // The same historical reference in another community does not block cleanup here. + sqlx::query("UPDATE events SET community_id=$2 WHERE community_id=$1 AND id=$3") + .bind(f.community) + .bind(f.elsewhere) + .bind(event.id.to_bytes().as_slice()) + .execute(&f.pool) + .await + .unwrap(); + let foreign = export(&f.pool).await; + f.store + .run_profile_batches(&f.options(1), true, None, &mut Vec::new()) + .await + .unwrap(); + assert_eq!(foreign["events"], export(&f.pool).await["events"]); + } +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn historical_archive_request_replacement_blocks_after_unarchive() { + historical_replacement_blocks_cleanup_after_unarchive(9035).await; +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn historical_archive_delta_replacement_blocks_after_unarchive() { + historical_replacement_blocks_cleanup_after_unarchive(8002).await; +} diff --git a/docs/profile-cleanup.md b/docs/profile-cleanup.md index d77b36eb2eb..e1bd0778c45 100644 --- a/docs/profile-cleanup.md +++ b/docs/profile-cleanup.md @@ -36,7 +36,9 @@ author. Supply `--relay-pubkey ` for each independently verified relay signer. A missing or untrusted signer stops the operation. The same trust rule applies to archive deltas and snapshots. Human-signed requests about another identity and archive actor/replacement references on surviving identities need -an explicit shared-history disposition; the command reports them as blockers. +an explicit shared-history disposition; the command reports them as blockers. Historical `replaced-by` references in +archive requests and deltas remain blockers even after unarchive removes the +canonical archive row. Shared archive snapshots are rebuilt from the retained canonical archive rows. The snapshot replacement is a fresh signed event; no old signature is reused. From ff6689386e28c968706d3a9f524185055affdbc1 Mon Sep 17 00:00:00 2001 From: Ravneet Arora Date: Tue, 17 Nov 2026 10:41:43 -0500 Subject: [PATCH 4/5] Preserve self-archive subjects in test fixtures The event builder drops self p tags by default. Keep the NIP-IA subject and print unexpected errors in the regression assertion. Co-authored-by: maincourse <37ce551b493d4a998caf030929c47bce0b6a0e43f1178b3a63c4151d7c16b76e@buzz.block.builderlab.xyz> Signed-off-by: Ravneet Arora --- .../user_deletion/profile_batches/postgres_tests.rs | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/crates/buzz-db/src/store/user_deletion/profile_batches/postgres_tests.rs b/crates/buzz-db/src/store/user_deletion/profile_batches/postgres_tests.rs index 78ce2b13ac8..07dd0bcc463 100644 --- a/crates/buzz-db/src/store/user_deletion/profile_batches/postgres_tests.rs +++ b/crates/buzz-db/src/store/user_deletion/profile_batches/postgres_tests.rs @@ -68,7 +68,9 @@ impl Fixture { tags: Vec>, content: &str, ) -> Event { + // Self-archive requests must retain the author as their explicit p subject. let event = EventBuilder::new(Kind::Custom(kind), content) + .allow_self_tagging() .tags(tags.into_iter().map(|v| Tag::parse(v).unwrap())) .custom_created_at(Timestamp::now()) .sign_with_keys(key) @@ -737,10 +739,13 @@ async fn historical_replacement_blocks_cleanup_after_unarchive(kind: u16) { .run_profile_batches(&f.options(1), delete, None, &mut output) .await; assert!(result.is_err(), "kind {kind}, agent {agent}, delete {delete}: unresolved historical replacement was accepted"); - assert!(result - .unwrap_err() - .to_string() - .contains("shared-history disposition required")); + let error = result.unwrap_err(); + assert!( + error + .to_string() + .contains("shared-history disposition required"), + "{error}" + ); assert!(!String::from_utf8(output) .unwrap() .contains("delete_complete")); From 3f32129ae66846ca7fe52340b99a3f1b91535cb3 Mon Sep 17 00:00:00 2001 From: Ravneet Arora Date: Tue, 17 Nov 2026 15:19:14 -0500 Subject: [PATCH 5/5] Preserve repositories during profile cleanup Allow retained repository announcements and state through profile prerequisites, with a content-to-profile cleanup regression. Run deletion safety-default unit tests in CI and its fallback, and clarify archive planning errors. Co-authored-by: maincourse <37ce551b493d4a998caf030929c47bce0b6a0e43f1178b3a63c4151d7c16b76e@buzz.block.builderlab.xyz> Signed-off-by: Ravneet Arora --- Justfile | 3 + .../user_deletion/profile_batches/plan.rs | 4 +- .../profile_batches/postgres_tests.rs | 121 ++++++++++++++++++ docs/profile-cleanup.md | 12 +- scripts/run-tests.sh | 4 + 5 files changed, 139 insertions(+), 5 deletions(-) diff --git a/Justfile b/Justfile index 7281f69788a..71a0e8f13ab 100644 --- a/Justfile +++ b/Justfile @@ -472,6 +472,9 @@ test-unit: # audit outcome contract, NIP-FI policy/backfill, and user-deletion intake. cargo nextest run -p buzz-admin \ -E 'test(storage_snapshot) + test(/^communities::tests::/) + test(/^tests::communities_/) + test(=tests::partition_audit_outcomes_keep_their_json_names_and_exit_codes) + test(/^nip_fi::tests::/) + test(/^nip_fi_policy::tests::/) + test(/^user_deletions::tests::/)' + # Deletion command safety defaults and planning logic are infra-free; + # ignored PostgreSQL tests run separately. Keep the fallback in step. + cargo nextest run -p buzz-deletion --lib # Multi-tenant conformance gate (buzz-conformance): the independent # replay checker + golden fixtures. No infra — pure in-process trace # replay — so it belongs in the unit job. Run all targets (lib + the diff --git a/crates/buzz-db/src/store/user_deletion/profile_batches/plan.rs b/crates/buzz-db/src/store/user_deletion/profile_batches/plan.rs index f3b65f35ebf..6255115b9ed 100644 --- a/crates/buzz-db/src/store/user_deletion/profile_batches/plan.rs +++ b/crates/buzz-db/src/store/user_deletion/profile_batches/plan.rs @@ -98,13 +98,15 @@ pub(super) async fn validate_ownership(conn: &mut PgConnection, scope: &Scope) - pub(super) async fn dependencies(conn: &mut PgConnection, scope: &Scope) -> Result> { let mut blockers = Vec::new(); // Static fragments only. These checks also run immediately before final user removal. + // Repository announcements/state (30617/30618) survive content and profile cleanup. + // Keep this exemption narrow: other authored content still requires disposition. for (table, selector) in [ ("api_tokens","owner_pubkey=ANY($2::bytea[])"), ("workflows","owner_pubkey=ANY($2::bytea[])"), ("subscriptions","owner_pubkey=ANY($2::bytea[])"), ("channel_members","pubkey=ANY($2::bytea[])"), ("relay_members","pubkey=ANY(SELECT encode(k,'hex') FROM unnest($2::bytea[]) k)"), - ("events","pubkey=ANY($2::bytea[]) AND kind NOT IN (0,10100,30177,30179,9035,9036)"), + ("events","pubkey=ANY($2::bytea[]) AND kind NOT IN (0,10100,30177,30179,9035,9036,30617,30618)"), ("archived_identities","NOT(pubkey=ANY(SELECT encode(k,'hex') FROM unnest($2::bytea[]) k)) AND (actor=ANY(SELECT encode(k,'hex') FROM unnest($2::bytea[]) k) OR replaced_by=ANY(SELECT encode(k,'hex') FROM unnest($2::bytea[]) k))"), ] { let sql=format!("SELECT EXISTS(SELECT 1 FROM {table} WHERE community_id=$1 AND ({selector}))"); diff --git a/crates/buzz-db/src/store/user_deletion/profile_batches/postgres_tests.rs b/crates/buzz-db/src/store/user_deletion/profile_batches/postgres_tests.rs index 07dd0bcc463..21537e389f6 100644 --- a/crates/buzz-db/src/store/user_deletion/profile_batches/postgres_tests.rs +++ b/crates/buzz-db/src/store/user_deletion/profile_batches/postgres_tests.rs @@ -312,6 +312,127 @@ async fn limits_dependencies_and_signer_fail_before_any_mutation() { assert_eq!(before, export(&f.pool).await); } +#[tokio::test] +#[ignore = "requires Postgres"] +async fn content_then_profile_cleanup_retains_human_and_agent_repositories() { + use crate::user_deletion::{content_batches::ContentBatchOptions, ExecutionMode}; + + let f = Fixture::new().await; + f.profiles().await; + let mut repository_ids = Vec::new(); + for community in [f.community, f.elsewhere] { + for owner in [&f.human, &f.agent, &f.other] { + let repo = format!("repo-{}", owner.public_key()); + for kind in [30617, 30618] { + let event = f + .event( + community, + owner, + kind, + vec![vec!["d".into(), repo.clone()]], + "retained repository metadata", + ) + .await; + repository_ids.push(json!(format!("\\x{}", event.id))); + sqlx::query("INSERT INTO event_mentions(community_id,pubkey_hex,event_id,event_created_at,event_kind) VALUES($1,$2,$3,now(),$4)") + .bind(community).bind(f.other.public_key().to_hex()) + .bind(event.id.to_bytes().as_slice()).bind(i32::from(kind)) + .execute(&f.pool).await.unwrap(); + } + sqlx::query( + "INSERT INTO git_repo_names(community_id,repo_id,owner_pubkey) VALUES($1,$2,$3)", + ) + .bind(community) + .bind(repo) + .bind(owner.public_key().to_hex()) + .execute(&f.pool) + .await + .unwrap(); + } + } + // Retaining repositories must not exempt ordinary human or agent content. + for owner in [&f.human, &f.agent] { + f.event(f.community, owner, 1, vec![], "remove content first") + .await; + } + let before = export(&f.pool).await; + let opts = f.options(2); + let secret = f.relay.secret_key().to_secret_hex(); + let mut blocked = Vec::new(); + assert!(f + .store + .run_profile_batches(&opts, true, Some(&secret), &mut blocked) + .await + .is_err()); + assert!(String::from_utf8(blocked) + .unwrap() + .contains("events: content/account cleanup")); + assert_eq!(before, export(&f.pool).await); + f.store + .run_message_batches( + &ContentBatchOptions { + community: f.community, + pubkey: f.human.public_key().to_hex(), + relay_pubkey: Some(f.relay.public_key().to_hex()), + batch_size: 2, + max_items: 1000, + }, + ExecutionMode::Delete, + None, + &mut Vec::new(), + ) + .await + .unwrap(); + let after_content = export(&f.pool).await; + let mut preview = Vec::new(); + let proposed = f + .store + .run_profile_batches(&opts, false, None, &mut preview) + .await + .unwrap(); + let start: Value = + serde_json::from_slice(preview.split(|b| *b == b'\n').next().unwrap()).unwrap(); + assert_eq!(start["blockers"], json!([])); + assert_eq!(after_content, export(&f.pool).await); + let deleted = f + .store + .run_profile_batches(&opts, true, Some(&secret), &mut Vec::new()) + .await + .unwrap(); + assert_eq!(proposed.items, deleted.items); + let after = export(&f.pool).await; + assert_eq!(before["git_repo_names"], after["git_repo_names"]); + for (table, rows) in &before { + for row in rows.as_array().unwrap() { + if row["community_id"] == json!(f.elsewhere) + || (table == "events" && repository_ids.contains(&row["id"])) + || (table == "event_mentions" && repository_ids.contains(&row["event_id"])) + { + assert!( + after[table].as_array().unwrap().contains(row), + "retained row changed in {table}" + ); + } + } + } + let remaining: Vec> = + sqlx::query_scalar("SELECT pubkey FROM users WHERE community_id=$1") + .bind(f.community) + .fetch_all(&f.pool) + .await + .unwrap(); + assert_eq!(remaining, vec![f.other.public_key().to_bytes().to_vec()]); + assert_eq!( + f.store + .run_profile_batches(&opts, true, None, &mut Vec::new()) + .await + .unwrap() + .items, + 0 + ); + assert_eq!(after, export(&f.pool).await); +} + struct FailAfterCommit; impl Write for FailAfterCommit { fn write(&mut self, bytes: &[u8]) -> std::io::Result { diff --git a/docs/profile-cleanup.md b/docs/profile-cleanup.md index e1bd0778c45..11d33ddf713 100644 --- a/docs/profile-cleanup.md +++ b/docs/profile-cleanup.md @@ -36,8 +36,10 @@ author. Supply `--relay-pubkey ` for each independently verified relay signer. A missing or untrusted signer stops the operation. The same trust rule applies to archive deltas and snapshots. Human-signed requests about another identity and archive actor/replacement references on surviving identities need -an explicit shared-history disposition; the command reports them as blockers. Historical `replaced-by` references in -archive requests and deltas remain blockers even after unarchive removes the +an explicit shared-history disposition. Selected archive events with these +references stop planning with an error before `profile_batches_start` is printed; +they are not included in its blocker list. Historical `replaced-by` references in +archive requests and deltas still stop planning after unarchive removes the canonical archive row. Shared archive snapshots are rebuilt from the retained canonical archive rows. @@ -58,8 +60,10 @@ a successful partial preview. SQL statements have a 30-second timeout and locks a three-second timeout; large accounts can require a separately reviewed plan. Before mutations, the command rejects remaining credentials, memberships, -workflows, subscriptions, non-profile authored content and unresolved archive -references. It retains replay watermarks, deletion fences, requests, approvals, +workflows, subscriptions, non-profile authored content other than repository +announcements/state (30617/30618), and unresolved archive references. Repository +events and name mappings remain intact and do not block identity removal. +It retains replay watermarks, deletion fences, requests, approvals, history, repositories and media objects. Media cleanup must preserve its source evidence before this command removes avatar/configuration references. diff --git a/scripts/run-tests.sh b/scripts/run-tests.sh index 659ff9cf3e4..d68a2f460c3 100755 --- a/scripts/run-tests.sh +++ b/scripts/run-tests.sh @@ -183,6 +183,10 @@ run_unit_tests() { run_test_step "buzz-admin user-deletion intake command tests" \ cargo test -p buzz-admin user_deletions::tests -- --nocapture + # Deletion command safety defaults; mirrors the nextest unit lane. + run_test_step "buzz-deletion unit tests" \ + cargo test -p buzz-deletion --lib -- --nocapture + # Multi-tenant conformance gate: independent replay checker + golden # fixtures (buzz-conformance). Pure in-process trace replay, no infra. run_test_step "buzz-conformance tests" \