From 76777f3b95637f6cf83a2cf6801f0056cb998bd7 Mon Sep 17 00:00:00 2001 From: Ravneet Arora Date: Mon, 16 Nov 2026 16:35:07 -0500 Subject: [PATCH 1/5] fix: scope media cleanup to current agent owners Keep agent ownership scoped to each community through upload evidence and cleanup. Refresh ownership on retries and refuse a changed set before mutations. Co-authored-by: dessert <7d616e7e143e5d408159614dccff1371350a1c1bd36c8de838a45ece5aca0aca@buzz.block.builderlab.xyz> Signed-off-by: Ravneet Arora --- .../buzz-db/src/store/user_deletion/media.rs | 141 +++++++++++++----- .../media_ownership_postgres_tests.rs | 121 +++++++++++++++ .../media_query_plan_postgres_tests.rs | 11 +- crates/buzz-db/src/store/user_deletion/mod.rs | 1 + crates/buzz-deletion/src/user/media.rs | 96 +++++++----- .../src/user/media/tests/ownership.rs | 108 ++++++++++++++ crates/buzz-deletion/src/user/media_report.rs | 11 +- .../user/worker_postgres_tests/media_retry.rs | 76 ++++++++++ docs/operator-user-deletion-executor.md | 16 +- 9 files changed, 502 insertions(+), 79 deletions(-) create mode 100644 crates/buzz-db/src/store/user_deletion/media_ownership_postgres_tests.rs create mode 100644 crates/buzz-deletion/src/user/media/tests/ownership.rs diff --git a/crates/buzz-db/src/store/user_deletion/media.rs b/crates/buzz-db/src/store/user_deletion/media.rs index e21ef9f96cf..98bd2db0deb 100644 --- a/crates/buzz-db/src/store/user_deletion/media.rs +++ b/crates/buzz-db/src/store/user_deletion/media.rs @@ -1,60 +1,111 @@ //! Bounded upload evidence queries for user media cleanup. use crate::{Db, DbError, Result}; +use uuid::Uuid; + +/// Fresh human ownership and direct agents, retaining each agent’s community. +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)] +pub struct UserMediaTargets { + /// The human remains the global discovery root. + pub human: String, + /// Agent authority applies only in the recorded community. + pub agents: Vec<(Uuid, String)>, +} + +impl UserMediaTargets { + /// Whether an upload claim belongs to this deletion scope. + pub fn contains(&self, community: Uuid, pubkey: &str) -> bool { + pubkey == self.human + || self + .agents + .iter() + .any(|(c, key)| *c == community && key == pubkey) + } + + /// Unique public keys for indexed candidate discovery and display only. + pub fn pubkeys(&self) -> Vec { + let mut keys = vec![self.human.clone()]; + keys.extend(self.agents.iter().map(|(_, key)| key.clone())); + keys.sort(); + keys.dedup(); + keys + } + + fn communities(&self) -> Vec { + self.agents + .iter() + .map(|(community, _)| *community) + .collect() + } + + fn agent_keys(&self) -> Result>> { + self.agents.iter().map(|(_, key)| decode_key(key)).collect() + } +} + +fn decode_key(key: &str) -> Result> { + hex::decode(super::normalize_user_deletion_pubkey(key)?) + .map_err(|error| DbError::InvalidData(error.to_string())) +} const MAX_MEDIA_TARGETS: usize = 10_000; const CANDIDATES_SQL: &str = r#"WITH candidates AS MATERIALIZED (SELECT sha256 FROM ( SELECT sha256 COLLATE "C" AS sha256 FROM media_uploaders - WHERE pubkey = ANY($1::bytea[]) AND sha256 COLLATE "C" > $2 + WHERE pubkey = ANY($1::bytea[]) + AND (pubkey = $4 OR (community_id, pubkey) IN (SELECT * FROM unnest($5::uuid[], $6::bytea[]))) + AND sha256 COLLATE "C" > $2 UNION SELECT object_id COLLATE "C" AS sha256 FROM audit_log WHERE action = 'media_uploaded' AND actor_pubkey = ANY($1::bytea[]) + AND (actor_pubkey = $4 OR (community_id, actor_pubkey) IN (SELECT * FROM unnest($5::uuid[], $6::bytea[]))) AND object_id COLLATE "C" > $2 ) uploads ORDER BY sha256 COLLATE "C" LIMIT $3) SELECT sha256, EXISTS ( SELECT 1 FROM media_uploaders m - WHERE m.sha256 = candidates.sha256 COLLATE "default" AND m.pubkey <> ALL($1::bytea[]) + WHERE m.sha256 = candidates.sha256 COLLATE "default" AND NOT (m.pubkey = $4 OR (m.community_id, m.pubkey) IN (SELECT * FROM unnest($5::uuid[], $6::bytea[]))) ) OR EXISTS ( SELECT 1 FROM audit_log a WHERE a.action = 'media_uploaded' AND a.object_id = candidates.sha256 COLLATE "default" - AND a.actor_pubkey <> ALL($1::bytea[]) + AND NOT (a.actor_pubkey = $4 OR (a.community_id, a.actor_pubkey) IN (SELECT * FROM unnest($5::uuid[], $6::bytea[]))) ) AS shared FROM candidates ORDER BY sha256 COLLATE "C""#; impl Db { - /// Resolve the human and their directly owned agents once across communities. - /// Every returned key is a global media target, including its uploads elsewhere. - pub async fn user_media_targets(&self, pubkey: &str) -> Result> { - let pubkey = super::normalize_user_deletion_pubkey(pubkey)?; + /// Fetch direct agent ownership per community on every invocation and retry. + pub async fn user_media_targets(&self, pubkey: &str) -> Result { + let human = super::normalize_user_deletion_pubkey(pubkey)?; let mut tx = self.pool().begin().await?; sqlx::query("SET LOCAL statement_timeout = '120s'") .execute(&mut *tx) .await?; - let keys: Vec = sqlx::query_scalar( - "SELECT key FROM ( - SELECT $1::text AS key - UNION - SELECT encode(pubkey, 'hex') FROM users - WHERE agent_owner_pubkey = decode($1, 'hex') - ) targets ORDER BY key LIMIT $2", + let agents: Vec<(Uuid, String)> = sqlx::query_as( + "SELECT community_id, encode(pubkey, 'hex') FROM users + WHERE agent_owner_pubkey = decode($1, 'hex') AND pubkey <> decode($1, 'hex') + ORDER BY community_id, pubkey LIMIT $2", ) - .bind(pubkey) + .bind(&human) .bind((MAX_MEDIA_TARGETS + 1) as i64) .fetch_all(&mut *tx) .await?; - validate_keys(&keys)?; + if agents.len() > MAX_MEDIA_TARGETS { + return Err(DbError::InvalidData( + "media agent scope exceeds 10000 entries".into(), + )); + } + let targets = UserMediaTargets { human, agents }; + validate_keys(&targets.pubkeys())?; tx.commit().await?; - Ok(keys) + Ok(targets) } /// Page through target upload hashes and classify sharing across all communities. /// An empty cursor starts the scan. Storage-only claims are discovered separately. pub async fn user_media_candidates( &self, - pubkeys: &[String], + targets: &UserMediaTargets, after: &str, limit: u16, ) -> Result> { - let keys = validate_keys(pubkeys)?; + let keys = validate_keys(&targets.pubkeys())?; if !(1..=500).contains(&limit) { return Err(DbError::InvalidData( "media page size must be 1..=500".into(), @@ -71,6 +122,9 @@ impl Db { .bind(keys) .bind(after) .bind(i64::from(limit)) + .bind(decode_key(&targets.human)?) + .bind(targets.communities()) + .bind(targets.agent_keys()?) .fetch_all(&mut *tx) .await?; for (hash, _) in &hashes { @@ -84,10 +138,10 @@ impl Db { /// Call this for storage-discovered candidates too, before deleting anything. pub async fn user_media_shared_hashes( &self, - pubkeys: &[String], + targets: &UserMediaTargets, hashes: &[String], ) -> Result> { - let keys = validate_keys(pubkeys)?; + validate_keys(&targets.pubkeys())?; if hashes.len() > 500 { return Err(DbError::InvalidData( "media evidence batch exceeds 500 hashes".into(), @@ -104,15 +158,17 @@ impl Db { r#"SELECT candidate FROM unnest($2::text[]) AS candidates(candidate) WHERE EXISTS ( SELECT 1 FROM media_uploaders - WHERE sha256 = candidate AND pubkey <> ALL($1::bytea[]) + WHERE sha256 = candidate AND NOT (pubkey = $1 OR (community_id, pubkey) IN (SELECT * FROM unnest($3::uuid[], $4::bytea[]))) ) OR EXISTS ( SELECT 1 FROM audit_log WHERE action = 'media_uploaded' AND object_id = candidate - AND actor_pubkey <> ALL($1::bytea[]) + AND NOT (actor_pubkey = $1 OR (community_id, actor_pubkey) IN (SELECT * FROM unnest($3::uuid[], $4::bytea[]))) ) ORDER BY candidate COLLATE "C""#, ) - .bind(keys) + .bind(decode_key(&targets.human)?) .bind(hashes) + .bind(targets.communities()) + .bind(targets.agent_keys()?) .fetch_all(&mut *tx) .await?; tx.commit().await?; @@ -121,14 +177,21 @@ impl Db { /// Remove the target set's ownership rows only after storage cleanup succeeds. /// Audit history and publication moderation records are retained. - pub async fn remove_user_media_uploader(&self, pubkeys: &[String], hash: &str) -> Result { - let keys = validate_keys(pubkeys)?; + pub async fn remove_user_media_uploader( + &self, + targets: &UserMediaTargets, + hash: &str, + ) -> Result { + validate_keys(&targets.pubkeys())?; validate_hash(hash)?; Ok(sqlx::query( - "DELETE FROM media_uploaders WHERE pubkey = ANY($1::bytea[]) AND sha256 = $2", + "DELETE FROM media_uploaders WHERE sha256 = $2 + AND (pubkey = $1 OR (community_id, pubkey) IN (SELECT * FROM unnest($3::uuid[], $4::bytea[])))", ) - .bind(keys) + .bind(decode_key(&targets.human)?) .bind(hash) + .bind(targets.communities()) + .bind(targets.agent_keys()?) .execute(self.pool()) .await? .rows_affected()) @@ -215,7 +278,7 @@ mod postgres_tests { sqlx::query("INSERT INTO media_uploaders(community_id, sha256, pubkey) VALUES ($1, $2, decode($3, 'hex'))") .bind(community).bind(format!("{:064x}", 502)).bind(&bob) .execute(&pool).await.unwrap(); - let keys = vec![alice.clone()]; + let keys = db.user_media_targets(&alice).await.unwrap(); let first = db.user_media_candidates(&keys, "", 500).await.unwrap(); assert_eq!(first.len(), 500); assert_eq!(first[0], (format!("{:064x}", 1), false)); @@ -257,7 +320,7 @@ mod postgres_tests { #[tokio::test] #[ignore = "requires Postgres"] - async fn owned_agents_form_one_global_media_target_set() { + async fn direct_agents_retain_community_scope_and_upload_history() { use nostr::nips::nip19::ToBech32; let pool = sqlx::PgPool::connect(&crate::test_support::database_url()) .await @@ -305,9 +368,10 @@ mod postgres_tests { .unwrap(); let mut expected = vec![alice.clone(), agent.clone()]; expected.sort(); - assert_eq!(keys, expected); // Duplicate/deactivated profiles still yield one agent key. + assert_eq!(keys.pubkeys(), expected); + assert_eq!(keys.agents.len(), 2); // Deactivated profiles retain ownership for retries. assert_eq!( - db.user_media_targets(&agent).await.unwrap(), + db.user_media_targets(&agent).await.unwrap().pubkeys(), vec![agent.clone()] ); let hashes: Vec<_> = (1..=5).map(|n| format!("{n:064x}")).collect(); @@ -397,9 +461,14 @@ mod postgres_tests { .await .unwrap() .contains(&(hashes[0].clone(), false))); - assert!(db.user_media_candidates(&[], "", 500).await.is_err()); assert!(db - .remove_user_media_uploader(&["invalid".into()], &hashes[0]) + .remove_user_media_uploader( + &UserMediaTargets { + human: "invalid".into(), + agents: vec![] + }, + &hashes[0] + ) .await .is_err()); } @@ -408,3 +477,7 @@ mod postgres_tests { #[cfg(test)] #[path = "media_query_plan_postgres_tests.rs"] mod query_plan_postgres_tests; + +#[cfg(test)] +#[path = "media_ownership_postgres_tests.rs"] +mod ownership_postgres_tests; diff --git a/crates/buzz-db/src/store/user_deletion/media_ownership_postgres_tests.rs b/crates/buzz-db/src/store/user_deletion/media_ownership_postgres_tests.rs new file mode 100644 index 00000000000..d9e8235d340 --- /dev/null +++ b/crates/buzz-db/src/store/user_deletion/media_ownership_postgres_tests.rs @@ -0,0 +1,121 @@ +//! Same agent identity has independent ownership in each community. +use super::*; + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn community_ownership_controls_candidates_sharing_removal_and_fresh_retry() { + let pool = sqlx::PgPool::connect(&crate::test_support::database_url()) + .await + .unwrap(); + let db = Db::from_pool(pool.clone()); + let alice = nostr::Keys::generate().public_key().to_hex(); + let bob = nostr::Keys::generate().public_key().to_hex(); + let agent = nostr::Keys::generate().public_key().to_hex(); + let nested_agent = nostr::Keys::generate().public_key().to_hex(); + let communities = [Uuid::new_v4(), Uuid::new_v4(), Uuid::new_v4()]; + for community in communities { + sqlx::query("INSERT INTO communities(id, host) VALUES ($1, $2)") + .bind(community) + .bind(format!("{community}.example.org")) + .execute(&pool) + .await + .unwrap(); + } + for community in communities { + for key in [&alice, &bob] { + sqlx::query("INSERT INTO users(community_id, pubkey) VALUES ($1, decode($2, 'hex'))") + .bind(community) + .bind(key) + .execute(&pool) + .await + .unwrap(); + } + } + for (community, key, owner) in [ + (communities[0], &agent, &alice), + (communities[1], &agent, &bob), + (communities[0], &nested_agent, &agent), + ] { + sqlx::query("INSERT INTO users(community_id, pubkey, agent_owner_pubkey) VALUES ($1, decode($2, 'hex'), decode($3, 'hex'))") + .bind(community).bind(key).bind(owner).execute(&pool).await.unwrap(); + } + let hashes: Vec<_> = (1..=7).map(|n| format!("{n:064x}")).collect(); + for (community, index, key) in [ + (0, 0, &agent), + (1, 0, &agent), // Conflicting community protects shared blob. + (0, 1, &agent), + (2, 1, &agent), // Missing profile also protects shared blob. + (1, 2, &agent), // Outside-only upload is not a candidate. + (0, 3, &agent), // Exclusive owned upload is selected. + (0, 4, &nested_agent), // Direct ownership only; no recursive expansion. + (0, 5, &alice), // Outside audit evidence protects this human upload. + ] { + sqlx::query("INSERT INTO media_uploaders(community_id, sha256, pubkey) VALUES ($1, $2, decode($3, 'hex'))") + .bind(communities[community]).bind(&hashes[index]).bind(key).execute(&pool).await.unwrap(); + } + for (seq, community, index) in [(1_i64, 0, 6), (2, 1, 5), (3, 1, 2), (4, 2, 1)] { + sqlx::query( + "INSERT INTO audit_log(community_id, seq, hash, action, actor_pubkey, object_id) + VALUES ($1, $2, decode($3, 'hex'), 'media_uploaded', decode($4, 'hex'), $5)", + ) + .bind(communities[community]) + .bind(seq) + .bind(format!("{seq:064x}")) + .bind(&agent) + .bind(&hashes[index]) + .execute(&pool) + .await + .unwrap(); + } + let targets = db.user_media_targets(&alice).await.unwrap(); + assert_eq!(targets.agents, vec![(communities[0], agent.clone())]); + assert_eq!( + db.user_media_candidates(&targets, "", 500).await.unwrap(), + [0, 1, 3, 5, 6].map(|i| (hashes[i].clone(), [0, 1, 5].contains(&i))) + ); + assert_eq!( + db.user_media_shared_hashes(&targets, &hashes) + .await + .unwrap(), + [0, 1, 2, 4, 5].map(|i| hashes[i].clone()) + ); + for index in [0, 1] { + assert_eq!( + db.remove_user_media_uploader(&targets, &hashes[index]) + .await + .unwrap(), + 1 + ); + let remaining: Vec = + sqlx::query_scalar("SELECT community_id FROM media_uploaders WHERE sha256 = $1") + .bind(&hashes[index]) + .fetch_all(&pool) + .await + .unwrap(); + assert_eq!(remaining, vec![communities[index + 1]]); + } + // Ownership transfers between runs; the same pubkey list must not hide the changed community. + sqlx::query("UPDATE users SET agent_owner_pubkey = CASE WHEN community_id = $1 THEN decode($2, 'hex') ELSE decode($3, 'hex') END WHERE pubkey = decode($4, 'hex')") + .bind(communities[0]).bind(&bob).bind(&alice).bind(&agent).execute(&pool).await.unwrap(); + let retry = db.user_media_targets(&alice).await.unwrap(); + assert_eq!(retry.pubkeys(), targets.pubkeys()); + assert_eq!(retry.agents, vec![(communities[1], agent.clone())]); + let candidates = db.user_media_candidates(&retry, "", 500).await.unwrap(); + assert!(candidates.iter().any(|(hash, _)| hash == &hashes[2])); + assert!(!candidates + .iter() + .any(|(hash, _)| hash == &hashes[3] || hash == &hashes[6])); + // Removing ownership evidence excludes the agent on the next invocation. + sqlx::query("DELETE FROM users WHERE pubkey IN (decode($1, 'hex'), decode($2, 'hex'))") + .bind(&agent) + .bind(&nested_agent) + .execute(&pool) + .await + .unwrap(); + assert!(db + .user_media_targets(&alice) + .await + .unwrap() + .agents + .is_empty()); +} diff --git a/crates/buzz-db/src/store/user_deletion/media_query_plan_postgres_tests.rs b/crates/buzz-db/src/store/user_deletion/media_query_plan_postgres_tests.rs index cf62ad8fa6b..1f05c5cc863 100644 --- a/crates/buzz-db/src/store/user_deletion/media_query_plan_postgres_tests.rs +++ b/crates/buzz-db/src/store/user_deletion/media_query_plan_postgres_tests.rs @@ -63,10 +63,8 @@ async fn media_discovery_and_sharing_use_indexes_without_current_membership() { .await .unwrap(); let db = Db::from_pool(pool.clone()); - let actual = db - .user_media_candidates(std::slice::from_ref(&alice), "", 500) - .await - .unwrap(); + let targets = db.user_media_targets(&alice).await.unwrap(); + let actual = db.user_media_candidates(&targets, "", 500).await.unwrap(); assert_eq!( actual, [1, 20001, 40001, 40002].map(|n| (format!("{n:064x}"), n < 40000)) @@ -74,9 +72,12 @@ async fn media_discovery_and_sharing_use_indexes_without_current_membership() { // Only a fixed EXPLAIN prefix and the production SQL constant are concatenated. let explain = format!("EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) {CANDIDATES_SQL}"); let plan: Value = sqlx::query_scalar(sqlx::AssertSqlSafe(explain.as_str())) - .bind(validate_keys(&[alice]).unwrap()) + .bind(validate_keys(&targets.pubkeys()).unwrap()) .bind("") .bind(500_i64) + .bind(decode_key(&targets.human).unwrap()) + .bind(targets.communities()) + .bind(targets.agent_keys().unwrap()) .fetch_one(&pool) .await .unwrap(); diff --git a/crates/buzz-db/src/store/user_deletion/mod.rs b/crates/buzz-db/src/store/user_deletion/mod.rs index b519293f049..108e92bdb0c 100644 --- a/crates/buzz-db/src/store/user_deletion/mod.rs +++ b/crates/buzz-db/src/store/user_deletion/mod.rs @@ -10,6 +10,7 @@ mod inventory; mod media; /// Standalone, offline profile cleanup with read-only preview. pub mod profile_batches; +pub use media::UserMediaTargets; mod requests; pub use discovery::normalize_user_deletion_pubkey; pub use inventory::UserDeletionInventory; diff --git a/crates/buzz-deletion/src/user/media.rs b/crates/buzz-deletion/src/user/media.rs index 8b1e507bee9..505abcd1e6e 100644 --- a/crates/buzz-deletion/src/user/media.rs +++ b/crates/buzz-deletion/src/user/media.rs @@ -1,12 +1,11 @@ //! User media cleanup. Both modes use the same upload-only inventory. use anyhow::{bail, Context, Result}; -use buzz_db::{Db, DbConfig}; +use buzz_db::{user_deletion::UserMediaTargets, Db, DbConfig}; use buzz_media::{ classify_key, KeyClass, MediaStorage, ObjectVersionEntry, ObjectVersionKind, ObjectVersionRef, ObjectVersionsPage, UploadRecord, UPLOAD_RECORD_VERSION, }; use serde_json::Value; -use std::collections::HashSet; use std::io::{BufWriter, Write}; #[path = "media_inventory.rs"] mod inventory; @@ -19,7 +18,7 @@ const MAX_STORAGE_PAGES: usize = 100_000; /// Direct media-handler arguments; no workflow request is needed. #[derive(Debug, clap::Args)] pub struct Args { - /// Human public key (hex or npub). Includes owned agents across all communities. + /// Human public key (hex or npub). Includes agents only where currently owned. #[arg(long, value_parser = buzz_db::user_deletion::normalize_user_deletion_pubkey)] pub pubkey: String, /// Print selected files without changing the database or storage (default). @@ -71,24 +70,32 @@ pub(super) async fn handle_with_storage( // Fakes replace only external DB/storage boundaries; the tests run the same // candidate collection, prefix scans, bounded inventory and deletion loop. trait Database { - async fn targets(&self, pubkey: &str) -> Result>; - async fn candidates(&self, pubkeys: &[String], after: &str) -> Result>; - async fn shared(&self, pubkeys: &[String], hashes: &[String]) -> Result>; - async fn remove(&self, pubkeys: &[String], hash: &str) -> Result; + async fn targets(&self, pubkey: &str) -> Result; + async fn candidates( + &self, + pubkeys: &UserMediaTargets, + after: &str, + ) -> Result>; + async fn shared(&self, pubkeys: &UserMediaTargets, hashes: &[String]) -> Result>; + async fn remove(&self, pubkeys: &UserMediaTargets, hash: &str) -> Result; } impl Database for Db { - async fn targets(&self, pubkey: &str) -> Result> { + async fn targets(&self, pubkey: &str) -> Result { Ok(self.user_media_targets(pubkey).await?) } - async fn candidates(&self, pubkeys: &[String], after: &str) -> Result> { + async fn candidates( + &self, + pubkeys: &UserMediaTargets, + after: &str, + ) -> Result> { Ok(self .user_media_candidates(pubkeys, after, PAGE_SIZE) .await?) } - async fn shared(&self, pubkeys: &[String], hashes: &[String]) -> Result> { + async fn shared(&self, pubkeys: &UserMediaTargets, hashes: &[String]) -> Result> { Ok(self.user_media_shared_hashes(pubkeys, hashes).await?) } - async fn remove(&self, pubkeys: &[String], hash: &str) -> Result { + async fn remove(&self, pubkeys: &UserMediaTargets, hash: &str) -> Result { Ok(self.remove_user_media_uploader(pubkeys, hash).await?) } } @@ -151,7 +158,6 @@ async fn run_handler_with_inventory( mut inventory: Inventory, ) -> Result { let keys = db.targets(pubkey).await?; - let keys_set: HashSet<_> = keys.iter().cloned().collect(); let mut after = String::new(); loop { let page = db.candidates(&keys, &after).await?; @@ -166,7 +172,7 @@ async fn run_handler_with_inventory( } // Finish discovery before classifying storage-only candidates. Historical // upload claims may precede the target's claim in the listing. - scan_storage(media, &keys_set, &mut inventory, "_uploads/", true).await?; + scan_storage(media, &keys, &mut inventory, "_uploads/", true).await?; after.clear(); loop { let hashes = inventory.unchecked_candidates(&after).await?; @@ -181,8 +187,8 @@ async fn run_handler_with_inventory( if !inventory.candidates("").await?.is_empty() { // These community-first namespaces cannot be looked up by hash alone. // Keep complete historical coverage, including removed communities. - scan_storage(media, &keys_set, &mut inventory, "_uploads/", false).await?; - scan_storage(media, &keys_set, &mut inventory, "_meta/", false).await?; + scan_storage(media, &keys, &mut inventory, "_uploads/", false).await?; + scan_storage(media, &keys, &mut inventory, "_meta/", false).await?; } after.clear(); loop { @@ -194,7 +200,7 @@ async fn run_handler_with_inventory( for (hash, _) in page { // The dot excludes other hash families while covering all blob // extensions, thumbnails, historical versions and delete markers. - scan_storage(media, &keys_set, &mut inventory, &format!("{hash}."), false).await?; + scan_storage(media, &keys, &mut inventory, &format!("{hash}."), false).await?; } } inventory.require_immutable_versions().await?; @@ -203,9 +209,16 @@ async fn run_handler_with_inventory( Ok(result) } +async fn require_current_targets(db: &impl Database, targets: &UserMediaTargets) -> Result<()> { + if db.targets(&targets.human).await? != *targets { + bail!("media agent ownership changed; retry to discover current community ownership"); + } + Ok(()) +} + async fn scan_storage( media: &impl Storage, - keys_set: &HashSet, + targets: &UserMediaTargets, inventory: &mut Inventory, prefix: &str, candidates_only: bool, @@ -260,10 +273,10 @@ async fn scan_storage( let owner = buzz_db::user_deletion::normalize_user_deletion_pubkey( &record.uploader_id, )?; - if candidates_only && keys_set.contains(&owner) { + if candidates_only && targets.contains(*community, &owner) { candidates.push(hash.clone()); } - if !candidates_only && !keys_set.contains(&owner) { + if !candidates_only && !targets.contains(*community, &owner) { shared.push(hash.clone()); } } @@ -334,6 +347,7 @@ pub(super) fn configured_storage() -> Result { mod tests { mod capacity; mod claim_versions; + mod ownership; mod s3; use super::*; use clap::Parser; @@ -373,25 +387,34 @@ mod tests { #[derive(Default)] struct FakeDb { - targets: Vec, + targets: Vec<(uuid::Uuid, String)>, target_calls: RefCell, + changed_targets: Option<(usize, Vec<(uuid::Uuid, String)>)>, candidates: Vec, shared: Vec, checked: RefCell>, removed: RefCell>, } impl Database for FakeDb { - async fn targets(&self, pubkey: &str) -> Result> { + async fn targets(&self, pubkey: &str) -> Result { *self.target_calls.borrow_mut() += 1; - Ok(if self.targets.is_empty() { - vec![pubkey.to_owned()] - } else { - self.targets.clone() + Ok(UserMediaTargets { + human: pubkey.to_owned(), + agents: match &self.changed_targets { + Some((after, targets)) if *self.target_calls.borrow() > *after => { + targets.clone() + } + _ => self.targets.clone(), + }, }) } - async fn candidates(&self, keys: &[String], after: &str) -> Result> { + async fn candidates( + &self, + keys: &UserMediaTargets, + after: &str, + ) -> Result> { if !self.targets.is_empty() { - assert_eq!(keys, self.targets); + assert_eq!(keys.agents, self.targets); } Ok(self .candidates @@ -401,9 +424,9 @@ mod tests { .map(|hash| (hash.clone(), self.shared.contains(hash))) .collect()) } - async fn shared(&self, keys: &[String], hashes: &[String]) -> Result> { + async fn shared(&self, keys: &UserMediaTargets, hashes: &[String]) -> Result> { if !self.targets.is_empty() { - assert_eq!(keys, self.targets); + assert_eq!(keys.agents, self.targets); } self.checked.borrow_mut().extend_from_slice(hashes); Ok(hashes @@ -412,9 +435,9 @@ mod tests { .cloned() .collect()) } - async fn remove(&self, keys: &[String], hash: &str) -> Result { + async fn remove(&self, keys: &UserMediaTargets, hash: &str) -> Result { if !self.targets.is_empty() { - assert_eq!(keys, self.targets); + assert_eq!(keys.agents, self.targets); } self.removed.borrow_mut().push(hash.into()); Ok(1) @@ -656,7 +679,10 @@ mod tests { async fn combined_targets_share_one_inventory_and_preserve_outside_uploaders() { let hashes: Vec<_> = (1..=5).map(|n| format!("{n:064x}")).collect(); let db = FakeDb { - targets: vec![ALICE.into(), AGENT.into()], + targets: vec![ + (uuid::Uuid::from_u128(1), AGENT.into()), + (uuid::Uuid::from_u128(2), AGENT.into()), + ], candidates: vec![hashes[0].clone()], shared: vec![hashes[3].clone()], // Outside uploader found only in DB. ..Default::default() @@ -677,7 +703,7 @@ mod tests { .await .unwrap(); let report: Value = serde_json::from_slice(&output).unwrap(); - assert_eq!(report["target_pubkeys"], json!([ALICE, AGENT])); + assert_eq!(report["target_pubkeys"], json!([AGENT, ALICE])); assert_eq!(report["summary"], preview); let files = report["files"].as_array().unwrap(); assert_eq!(files.len(), 4); @@ -705,7 +731,7 @@ mod tests { assert_eq!(preview["selected_files"], 4); assert_eq!(preview["kept_files"], 2); assert_eq!(preview["deleted_versions"], 0); - assert_eq!(*db.target_calls.borrow(), 1); + assert!(*db.target_calls.borrow() >= 1); let expected_passes: Vec = ["_uploads/".into(), "_uploads/".into(), "_meta/".into()] .into_iter() @@ -727,7 +753,7 @@ mod tests { assert_eq!(result["selected_files"], 4); assert_eq!(result["kept_files"], 2); assert_eq!(result["deleted_versions"], 5); - assert_eq!(*db.target_calls.borrow(), 2); + assert!(*db.target_calls.borrow() > 2); assert_eq!( *media.passes.borrow(), expected_passes diff --git a/crates/buzz-deletion/src/user/media/tests/ownership.rs b/crates/buzz-deletion/src/user/media/tests/ownership.rs new file mode 100644 index 00000000000..18ed36127c5 --- /dev/null +++ b/crates/buzz-deletion/src/user/media/tests/ownership.rs @@ -0,0 +1,108 @@ +//! Ownership changes and community boundaries through the real media handler. +use super::*; + +#[tokio::test] +async fn agent_claims_in_other_communities_protect_blobs_and_are_not_selected() { + let hashes: Vec<_> = (1..=4).map(|n| format!("{n:064x}")).collect(); + let db = FakeDb { + targets: vec![(uuid::Uuid::from_u128(1), AGENT.into())], + ..Default::default() + }; + let mut media = FakeStorage::default(); + media.upload(&hashes[0], AGENT, 1); // Owned here: delete. + media.upload(&hashes[1], AGENT, 2); // Owned elsewhere or missing evidence: untouched. + media.upload(&hashes[2], ALICE, 1); + media.upload(&hashes[2], AGENT, 2); // Same key outside scope protects shared bytes. + media.upload(&hashes[3], AGENT, 1); + media.upload(&hashes[3], AGENT, 2); // Sharing across communities protects agent's bytes too. + for hash in &hashes { + media.object(format!("{hash}.png"), ObjectVersionKind::Object); + } + let before = media.entries.borrow().clone(); + let preview = run_handler(&db, &media, ALICE, false, &mut Vec::new()) + .await + .unwrap(); + assert_eq!(preview["selected_files"], 3); + assert_eq!(preview["kept_files"], 2); + assert_eq!(*media.entries.borrow(), before); + assert!(db.removed.borrow().is_empty()); + let result = run_handler(&db, &media, ALICE, true, &mut Vec::new()) + .await + .unwrap(); + assert_eq!(result["deleted_versions"], 2); + assert!(media + .deleted + .borrow() + .iter() + .all(|entry| entry.key.contains(&hashes[0]))); + assert_eq!( + *db.removed.borrow(), + vec![hashes[0].clone(), hashes[2].clone(), hashes[3].clone()] + ); +} + +#[tokio::test] +async fn changed_ownership_aborts_before_mutation_and_retry_rediscovers() { + let community = uuid::Uuid::from_u128(1); + // Transfer away/missing row, new ownership, and same-key transfer between communities. + for changed_after in [1, 2] { + for changed in [ + vec![], + vec![(community, AGENT.into()), (community, BOB.into())], + vec![(uuid::Uuid::from_u128(2), AGENT.into())], + ] { + let mut db = FakeDb { + targets: vec![(community, AGENT.into())], + changed_targets: Some((changed_after, changed.clone())), + ..Default::default() + }; + let hash = "a".repeat(64); + let mut media = FakeStorage::default(); + media.upload(&hash, AGENT, 1); + media.object(format!("{hash}.png"), ObjectVersionKind::Object); + let before = media.entries.borrow().clone(); + let error = run_handler(&db, &media, ALICE, true, &mut Vec::new()) + .await + .unwrap_err(); + assert!(error.to_string().contains("ownership changed")); + assert_eq!(media.deleted.borrow().len(), changed_after - 1); + if changed_after == 1 { + assert_eq!(*media.entries.borrow(), before); + } + assert!(media + .entries + .borrow() + .iter() + .any(|entry| entry.key.starts_with("_uploads/"))); + assert!(db.removed.borrow().is_empty()); + db.targets = changed; + db.changed_targets = None; + let result = run_handler(&db, &media, ALICE, true, &mut Vec::new()) + .await + .unwrap(); + assert_eq!( + result["selected_files"], + if db.targets.contains(&(community, AGENT.into())) { + 1 + } else { + 0 + } + ); + } + } +} + +#[tokio::test] +async fn empty_inventory_rechecks_new_agents_before_reporting_success() { + let db = FakeDb { + changed_targets: Some((1, vec![(uuid::Uuid::from_u128(1), AGENT.into())])), + ..Default::default() + }; + let media = FakeStorage::default(); + let error = run_handler(&db, &media, ALICE, true, &mut Vec::new()) + .await + .unwrap_err(); + assert!(error.to_string().contains("ownership changed")); + assert!(db.removed.borrow().is_empty()); + assert!(media.deleted.borrow().is_empty()); +} diff --git a/crates/buzz-deletion/src/user/media_report.rs b/crates/buzz-deletion/src/user/media_report.rs index 2221650df76..a2ea10ac7e3 100644 --- a/crates/buzz-deletion/src/user/media_report.rs +++ b/crates/buzz-deletion/src/user/media_report.rs @@ -1,5 +1,5 @@ //! One JSON document, streamed from bounded inventory pages even for large files. -use super::{Database, Inventory, Storage}; +use super::{require_current_targets, Database, Inventory, Storage, UserMediaTargets}; use anyhow::Result; use serde_json::{json, Value}; use std::io::Write; @@ -7,7 +7,7 @@ use std::io::Write; pub(super) async fn execute( db: &impl Database, media: &impl Storage, - pubkeys: &[String], + pubkeys: &UserMediaTargets, delete: bool, inventory: &mut Inventory, output: &mut impl Write, @@ -17,7 +17,9 @@ pub(super) async fn execute( output, "{{\n \"mode\": \"{mode}\",\n \"target_pubkeys\": " )?; - serde_json::to_writer(&mut *output, pubkeys)?; + serde_json::to_writer(&mut *output, &pubkeys.pubkeys())?; + write!(output, ",\n \"agent_communities\": ")?; + serde_json::to_writer(&mut *output, &pubkeys.agents)?; write!(output, ",\n \"files\": [")?; let (mut selected, mut kept, mut deleted_versions) = (0usize, 0usize, 0usize); let mut after = String::new(); @@ -64,6 +66,7 @@ pub(super) async fn execute( serde_json::to_writer(&mut *output, &version)?; first_version = false; if delete && !shared { + require_current_targets(db, pubkeys).await?; media.delete(&version).await?; handled += 1; } @@ -71,6 +74,7 @@ pub(super) async fn execute( } } let removed = if delete { + require_current_targets(db, pubkeys).await?; db.remove(pubkeys, &hash).await? } else { 0 @@ -80,6 +84,7 @@ pub(super) async fn execute( after = hash; } } + require_current_targets(db, pubkeys).await?; let summary = json!({"mode": mode, "selected_files": selected, "kept_files": kept, "deleted_versions": deleted_versions, "account_erasure_complete": false}); diff --git a/crates/buzz-deletion/src/user/worker_postgres_tests/media_retry.rs b/crates/buzz-deletion/src/user/worker_postgres_tests/media_retry.rs index cc56626fd2b..1886a58b7c0 100644 --- a/crates/buzz-deletion/src/user/worker_postgres_tests/media_retry.rs +++ b/crates/buzz-deletion/src/user/worker_postgres_tests/media_retry.rs @@ -108,3 +108,79 @@ async fn gate_then_media_requires_delete_and_retries_storage_failure_before_comm assert_eq!(fixture.requests.load(Ordering::SeqCst), calls); store.release(&lease).await.unwrap(); } + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn workflow_media_retry_refetches_agent_ownership_before_deleting() { + let fixture = fixture().await; + let human: String = + sqlx::query_scalar("SELECT encode(pubkey, 'hex') FROM media_uploaders WHERE sha256 = $1") + .bind("a".repeat(64)) + .fetch_one(&fixture.pool) + .await + .unwrap(); + let agent = nostr::Keys::generate().public_key().to_hex(); + let bob = nostr::Keys::generate().public_key().to_hex(); + for key in [&human, &bob] { + sqlx::query("INSERT INTO users(community_id, pubkey) VALUES ($1, decode($2, 'hex'))") + .bind(Uuid::from_u128(11)) + .bind(key) + .execute(&fixture.pool) + .await + .unwrap(); + } + sqlx::query("INSERT INTO users(community_id, pubkey, agent_owner_pubkey) VALUES ($1, decode($2, 'hex'), decode($3, 'hex'))") + .bind(Uuid::from_u128(11)).bind(&agent).bind(&human).execute(&fixture.pool).await.unwrap(); + sqlx::query("UPDATE media_uploaders SET pubkey = decode($1, 'hex') WHERE sha256 = $2") + .bind(&agent) + .bind("a".repeat(64)) + .execute(&fixture.pool) + .await + .unwrap(); + fixture.fail_listing.store(true, Ordering::SeqCst); + run( + &fixture.store, + fixture.id, + "worker-a", + &fixture.options(), + &CancellationToken::new(), + ) + .await + .unwrap_err(); + let failed = fixture.store.inspect(fixture.id).await.unwrap(); + assert_eq!(failed.stage_history[1].status, "failed"); + assert!(!fixture.deleted.load(Ordering::SeqCst)); + sqlx::query( + "UPDATE users SET agent_owner_pubkey = decode($1, 'hex') WHERE pubkey = decode($2, 'hex')", + ) + .bind(&bob) + .bind(&agent) + .execute(&fixture.pool) + .await + .unwrap(); + sqlx::query("UPDATE entity_deletion_requests SET next_attempt_at = clock_timestamp() - interval '1 second' WHERE id = $1") + .bind(fixture.id).execute(&fixture.pool).await.unwrap(); + fixture.fail_listing.store(false, Ordering::SeqCst); + run( + &fixture.store, + fixture.id, + "worker-b", + &RunOptions { + next_step: true, + ..fixture.options() + }, + &CancellationToken::new(), + ) + .await + .unwrap(); + let after = fixture.store.inspect(fixture.id).await.unwrap(); + assert_eq!(after.stage_history[1].id, failed.stage_history[1].id); + assert_eq!(after.stage_history[1].status, "completed"); + assert_eq!( + after.stage_history[1].metadata_json["result"]["selected_files"], + 0 + ); + assert_eq!(after.stage_history[2].stage, "purge_db"); + assert!(!fixture.deleted.load(Ordering::SeqCst)); + assert_eq!(fixture.uploader_count().await, 1); +} diff --git a/docs/operator-user-deletion-executor.md b/docs/operator-user-deletion-executor.md index ce9cf44f003..9b9990a4bb2 100644 --- a/docs/operator-user-deletion-executor.md +++ b/docs/operator-user-deletion-executor.md @@ -250,7 +250,12 @@ Ctrl-C releases the worker lease; after an abrupt kill wait for lease expiry. ## Media discovery and remaining limits -The target set is the human and directly owned agents across communities. +Every invocation and retry fetches the human's current directly owned agents +from `users`, retaining each `(community_id, agent_pubkey)` pair. The human's +own uploads are global targets; an agent's uploads are targets only in communities +where that human currently owns it. A missing profile or a different owner in +another community does not authorize cleanup there. Ownership rows must remain +until media and other dependent handlers finish. Candidate hashes come from `media_uploaders`, `media_uploaded` audit entries, and storage upload claims. A bounded database query combines candidate discovery with outside-uploader classification. Storage-only candidates receive the same @@ -259,7 +264,9 @@ history filter: relay membership rows can be deleted on departure. Sharing checks span all communities for the selected hashes. Any outside uploader in either database source or an upload-record version protects the -file. No per-file owner-list query is made. +file, including the same agent's uploads in an unowned community. No per-file +owner-list query is made. The report includes `agent_communities` alongside the +deduplicated `target_pubkeys`; the latter alone is not deletion authority. Storage discovery scans `_uploads/` for target claims, then reads candidate claims in a second `_uploads/` listing to protect outside claims encountered @@ -280,6 +287,11 @@ pages and database/HTTP clients allocate separately. It replaces the former 1 GiB disk inventory, so large jobs may reach capacity sooner. Exhausting a limit aborts before mutation, with a capacity error; no partial inventory is used for deletion. Retries rebuild discovery from PostgreSQL and storage. +The handler re-fetches the full ownership set before each storage delete and +uploader-row removal, and before returning success. Any change aborts for a +fresh retry. These checks do not serialize a remote storage write with ownership +updates: the existing requirement to stop all writers during deletion still +applies. Unversioned exclusive objects also abort. Upload claim objects are deleted last, and the target's database uploader rows are removed only after that file's storage processing succeeds, so a partial failure can be retried. From 1436b417858ace9efb09a43bb1693e4ecc4bef7b Mon Sep 17 00:00:00 2001 From: Ravneet Arora Date: Wed, 18 Nov 2026 12:44:37 -0500 Subject: [PATCH 2/5] fix: share agent discovery across deletion handlers Keep current direct ownership scoped to communities in every handler. Preserve batch row locks and retry discovery, including profile cleanup of its remaining identities. Co-authored-by: dessert <7d616e7e143e5d408159614dccff1371350a1c1bd36c8de838a45ece5aca0aca@buzz.block.builderlab.xyz> Signed-off-by: Ravneet Arora --- .../account_batches/ownership.rs | 25 +- .../user_deletion/account_batches/scope.rs | 11 +- .../store/user_deletion/agent_ownership.rs | 81 +++++++ .../agent_ownership_postgres_tests.rs | 217 ++++++++++++++++++ .../user_deletion/content_batches/mod.rs | 2 +- .../content_batches/ownership.rs | 24 +- .../buzz-db/src/store/user_deletion/media.rs | 60 +---- .../media_query_plan_postgres_tests.rs | 12 +- crates/buzz-db/src/store/user_deletion/mod.rs | 3 +- .../profile_batches/ownership.rs | 22 +- crates/buzz-deletion/src/user/media.rs | 41 ++-- .../src/user/media/tests/ownership.rs | 26 +++ crates/buzz-deletion/src/user/media_report.rs | 4 +- docs/operator-user-deletion-executor.md | 21 ++ 14 files changed, 418 insertions(+), 131 deletions(-) create mode 100644 crates/buzz-db/src/store/user_deletion/agent_ownership.rs create mode 100644 crates/buzz-db/src/store/user_deletion/agent_ownership_postgres_tests.rs diff --git a/crates/buzz-db/src/store/user_deletion/account_batches/ownership.rs b/crates/buzz-db/src/store/user_deletion/account_batches/ownership.rs index df84e2ed435..5e529cfbb17 100644 --- a/crates/buzz-db/src/store/user_deletion/account_batches/ownership.rs +++ b/crates/buzz-db/src/store/user_deletion/account_batches/ownership.rs @@ -1,8 +1,6 @@ //! Direct ownership is rediscovered per handler and checked in each batch. use super::*; -const MAX_AGENTS: i64 = 10_000; - impl UserDeletionStore { /// Fetch the target's current directly owned agents in this community, then /// print or apply bounded account batches. Retries repeat discovery. @@ -76,21 +74,14 @@ pub(super) async fn agents( target: &str, lock: bool, ) -> Result> { - let sql = if lock { - "SELECT encode(pubkey,'hex') FROM users WHERE community_id=$1 AND agent_owner_pubkey=decode($2,'hex') AND pubkey<>decode($2,'hex') ORDER BY pubkey LIMIT $3 FOR SHARE" - } else { - "SELECT encode(pubkey,'hex') FROM users WHERE community_id=$1 AND agent_owner_pubkey=decode($2,'hex') AND pubkey<>decode($2,'hex') ORDER BY pubkey LIMIT $3" - }; - let keys: Vec = sqlx::query_scalar(sql) - .bind(community) - .bind(target) - .bind(MAX_AGENTS + 1) - .fetch_all(conn) - .await?; - if keys.len() > MAX_AGENTS as usize { - return Err(invalid("account handler exceeds agent limit")); - } - Ok(keys) + Ok( + super::super::agent_ownership::discover(conn, target, Some(community), lock) + .await? + .agents + .into_iter() + .map(|(_, key)| key) + .collect(), + ) } pub(super) async fn recheck(conn: &mut PgConnection, options: &Options, lock: bool) -> Result<()> { diff --git a/crates/buzz-db/src/store/user_deletion/account_batches/scope.rs b/crates/buzz-db/src/store/user_deletion/account_batches/scope.rs index bf4fc2fbb54..af93abd0ad4 100644 --- a/crates/buzz-db/src/store/user_deletion/account_batches/scope.rs +++ b/crates/buzz-db/src/store/user_deletion/account_batches/scope.rs @@ -3,7 +3,7 @@ use super::*; use serde::Deserialize; use std::collections::BTreeSet; -const MAX_TARGETS: usize = 10_000; +use super::super::agent_ownership::{self, MAX_TARGETS}; /// Saved account cleanup inputs. Agent keys are a discovery snapshot only; /// each handler fetches current ownership. Keep ownership rows until cleanup ends. @@ -87,12 +87,9 @@ impl UserDeletionStore { if communities.len() > super::super::MAX_COMMUNITIES { return Err(invalid("account scope exceeds community limit")); } - let agents: Vec<(Uuid, String)> = sqlx::query_as( - "SELECT community_id,encode(pubkey,'hex') FROM users WHERE agent_owner_pubkey=decode($1,'hex') AND pubkey<>decode($1,'hex') ORDER BY community_id,pubkey LIMIT $2") - .bind(&target).bind((MAX_TARGETS + 1) as i64).fetch_all(&mut *tx).await?; - if agents.len() > MAX_TARGETS { - return Err(invalid("account scope exceeds target limit")); - } + let agents = agent_ownership::discover(&mut tx, &target, None, false) + .await? + .agents; let scope = AccountScope { version: 1, target: target.clone(), diff --git a/crates/buzz-db/src/store/user_deletion/agent_ownership.rs b/crates/buzz-db/src/store/user_deletion/agent_ownership.rs new file mode 100644 index 00000000000..25af2487f15 --- /dev/null +++ b/crates/buzz-db/src/store/user_deletion/agent_ownership.rs @@ -0,0 +1,81 @@ +//! One ownership rule for every user-deletion handler, independent of membership. +use super::normalize_user_deletion_pubkey; +use crate::{DbError, Result}; +use sqlx::{PgConnection, Postgres, QueryBuilder}; +use uuid::Uuid; + +pub(super) const MAX_TARGETS: usize = 10_000; + +/// Fresh human and direct-agent identities, retaining each agent's community. +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)] +pub struct UserDeletionTargets { + /// The human remains the global discovery root. + pub human: String, + /// Agent authority applies only in the recorded community. + pub agents: Vec<(Uuid, String)>, +} + +impl UserDeletionTargets { + /// Whether an upload claim belongs to this deletion scope. + pub fn contains(&self, community: Uuid, pubkey: &str) -> bool { + pubkey == self.human + || self + .agents + .iter() + .any(|(c, key)| *c == community && key == pubkey) + } + + /// Sorted distinct identities. Global callers must retain community pairs + /// when authorizing deletion; this flattened list alone grants no authority. + pub fn pubkeys(&self) -> Vec { + let mut keys = vec![self.human.clone()]; + keys.extend(self.agents.iter().map(|(_, key)| key.clone())); + keys.sort(); + keys.dedup(); + keys + } +} + +/// Read current direct ownership in the caller's transaction. No membership or +/// active-profile filter: deactivated profiles remain evidence until cleanup ends. +/// Missing profiles grant no agent authority, and agent ownership is not recursive. +/// `lock` retains FOR SHARE locks until the caller ends its transaction; callers +/// still own write admission and the offline/stopped-writer operating contract. +pub(super) async fn discover( + conn: &mut PgConnection, + human: &str, + community: Option, + lock: bool, +) -> Result { + let human = normalize_user_deletion_pubkey(human)?; + let mut query = QueryBuilder::::new( + "SELECT community_id, encode(pubkey,'hex') FROM users WHERE agent_owner_pubkey=decode(", + ); + query + .push_bind(human.clone()) + .push(", 'hex') AND pubkey<>decode(") + .push_bind(human.clone()) + .push(", 'hex')"); + if let Some(community) = community { + query.push(" AND community_id=").push_bind(community); + } + query + .push(" ORDER BY community_id, pubkey LIMIT ") + .push_bind((MAX_TARGETS + 1) as i64); + if lock { + query.push(" FOR SHARE"); + } + let agents = query.build_query_as().fetch_all(conn).await?; + let targets = UserDeletionTargets { human, agents }; + if targets.agents.len() > MAX_TARGETS || targets.pubkeys().len() > MAX_TARGETS { + return Err(DbError::DeletionSafety( + "user deletion ownership exceeds target limit (10000); no partial scope returned" + .into(), + )); + } + Ok(targets) +} + +#[cfg(test)] +#[path = "agent_ownership_postgres_tests.rs"] +mod postgres_tests; diff --git a/crates/buzz-db/src/store/user_deletion/agent_ownership_postgres_tests.rs b/crates/buzz-db/src/store/user_deletion/agent_ownership_postgres_tests.rs new file mode 100644 index 00000000000..9212a2111cc --- /dev/null +++ b/crates/buzz-db/src/store/user_deletion/agent_ownership_postgres_tests.rs @@ -0,0 +1,217 @@ +//! Shared ownership contract exercised through all four production handlers. +use super::*; +use crate::user_deletion::{ + account_batches::AccountBatchOptions, content_batches::ContentBatchOptions, + profile_batches::ProfileBatchOptions, ExecutionMode, +}; +use nostr::ToBech32; +use serde_json::Value; + +struct Fixture { + db: crate::Db, + communities: [Uuid; 3], + human: String, + other: String, + agent: String, +} + +impl Fixture { + async fn new() -> Self { + let pool = sqlx::PgPool::connect(&crate::test_support::database_url()) + .await + .unwrap(); + let f = Self { + db: crate::Db::from_pool(pool), + communities: std::array::from_fn(|_| Uuid::new_v4()), + human: nostr::Keys::generate().public_key().to_hex(), + other: nostr::Keys::generate().public_key().to_hex(), + agent: nostr::Keys::generate().public_key().to_hex(), + }; + for community in f.communities { + sqlx::query("INSERT INTO communities(id,host) VALUES ($1,$2)") + .bind(community) + .bind(format!("{community}.example.org")) + .execute(f.db.pool()) + .await + .unwrap(); + for key in [&f.human, &f.other] { + sqlx::query("INSERT INTO users(community_id,pubkey) VALUES ($1,decode($2,'hex'))") + .bind(community) + .bind(key) + .execute(f.db.pool()) + .await + .unwrap(); + } + } + for (community, owner) in [(f.communities[0], &f.human), (f.communities[1], &f.other)] { + // Neither membership nor activation determines ownership. + sqlx::query("INSERT INTO users(community_id,pubkey,agent_owner_pubkey,deactivated_at) VALUES ($1,decode($2,'hex'),decode($3,'hex'),now())") + .bind(community).bind(&f.agent).bind(owner).execute(f.db.pool()).await.unwrap(); + } + f + } + + async fn assert_handlers(&self, owned: Option) { + let store = self.db.user_deletion_store(); + let media = self.db.user_media_targets(&self.human).await.unwrap(); + assert_eq!( + media.agents, + owned + .map(|c| (c, self.agent.clone())) + .into_iter() + .collect::>() + ); + let scope = store.generate_account_scope(&self.human).await.unwrap(); + for community in self.communities { + let mut expected = vec![self.human.clone()]; + if Some(community) == owned { + expected.push(self.agent.clone()); + } + expected.sort(); + let mut saved = scope + .communities + .iter() + .find(|c| c.community == community) + .unwrap() + .pubkeys + .clone(); + saved.sort(); + assert_eq!(saved, expected); + let mut output = Vec::new(); + store + .run_message_batches( + &ContentBatchOptions { + community, + pubkey: self.human.clone(), + relay_pubkey: None, + batch_size: 100, + max_items: 100, + }, + ExecutionMode::ReadOnly, + None, + &mut output, + ) + .await + .unwrap(); + assert_eq!( + records(&output)[0]["target_pubkeys"], + serde_json::json!(expected) + ); + output.clear(); + store + .run_account_batches( + &AccountBatchOptions { + community, + pubkey: self.human.clone(), + batch_size: 100, + max_items: 100, + }, + ExecutionMode::ReadOnly, + &mut output, + None, + ) + .await + .unwrap(); + let mut account: Vec = records(&output) + .into_iter() + .filter(|r| r["record"] == "account_batches_start") + .map(|r| r["pubkey"].as_str().unwrap().to_owned()) + .collect(); + account.sort(); + assert_eq!(account, expected); + let profile = store + .run_profile_batches( + &ProfileBatchOptions { + community, + pubkey: self.human.clone(), + relay_pubkeys: vec![], + batch_size: 100, + max_items: 100, + }, + false, + None, + &mut Vec::new(), + ) + .await + .unwrap(); + assert_eq!(profile.target_pubkeys, expected); + } + } +} + +fn records(output: &[u8]) -> Vec { + std::str::from_utf8(output) + .unwrap() + .lines() + .map(|line| serde_json::from_str(line).unwrap()) + .collect() +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn every_handler_discovers_the_same_current_community_agents_on_retry() { + let f = Fixture::new().await; + f.assert_handlers(Some(f.communities[0])).await; + sqlx::query("UPDATE users SET agent_owner_pubkey=CASE WHEN community_id=$1 THEN decode($2,'hex') ELSE decode($3,'hex') END WHERE pubkey=decode($4,'hex')") + .bind(f.communities[0]).bind(&f.other).bind(&f.human).bind(&f.agent) + .execute(f.db.pool()).await.unwrap(); + f.assert_handlers(Some(f.communities[1])).await; + sqlx::query("DELETE FROM users WHERE pubkey=decode($1,'hex')") + .bind(&f.agent) + .execute(f.db.pool()) + .await + .unwrap(); + f.assert_handlers(None).await; +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn discovery_is_direct_normalized_and_holds_the_callers_row_locks() { + let f = Fixture::new().await; + let nested = nostr::Keys::generate().public_key().to_hex(); + sqlx::query("INSERT INTO users(community_id,pubkey,agent_owner_pubkey) VALUES ($1,decode($2,'hex'),decode($3,'hex'))") + .bind(f.communities[0]).bind(&nested).bind(&f.agent).execute(f.db.pool()).await.unwrap(); + let npub = nostr::PublicKey::parse(&f.human) + .unwrap() + .to_bech32() + .unwrap(); + let mut tx = f.db.pool().begin().await.unwrap(); + let targets = discover(&mut tx, &npub, Some(f.communities[0]), true) + .await + .unwrap(); + assert_eq!(targets.human, f.human); + assert_eq!(targets.agents, vec![(f.communities[0], f.agent.clone())]); + assert!(!targets.contains(f.communities[1], &f.agent)); + assert!(!targets.contains(f.communities[0], &nested)); + assert!(targets.contains(f.communities[2], &f.human)); + let mut transfer = f.db.pool().begin().await.unwrap(); + sqlx::query("SET LOCAL lock_timeout='50ms'") + .execute(&mut *transfer) + .await + .unwrap(); + let error = sqlx::query("UPDATE users SET agent_owner_pubkey=decode($1,'hex') WHERE community_id=$2 AND pubkey=decode($3,'hex')") + .bind(&f.other).bind(f.communities[0]).bind(&f.agent).execute(&mut *transfer).await.unwrap_err(); + assert_eq!( + error.as_database_error().unwrap().code().as_deref(), + Some("55P03") + ); + transfer.rollback().await.unwrap(); + tx.rollback().await.unwrap(); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn discovery_rejects_oversized_ownership_without_returning_a_partial_scope() { + let f = Fixture::new().await; + sqlx::query("INSERT INTO users(community_id,pubkey,agent_owner_pubkey) SELECT $1,decode(lpad(to_hex(n),64,'0'),'hex'),decode($2,'hex') FROM generate_series(1,10000) n") + .bind(f.communities[0]).bind(&f.human).execute(f.db.pool()).await.unwrap(); + for community in [None, Some(f.communities[0])] { + let mut tx = f.db.pool().begin().await.unwrap(); + assert!(discover(&mut tx, &f.human, community, false) + .await + .unwrap_err() + .to_string() + .contains("no partial scope")); + tx.rollback().await.unwrap(); + } +} diff --git a/crates/buzz-db/src/store/user_deletion/content_batches/mod.rs b/crates/buzz-db/src/store/user_deletion/content_batches/mod.rs index f685d96f0c3..88201b96f49 100644 --- a/crates/buzz-db/src/store/user_deletion/content_batches/mod.rs +++ b/crates/buzz-db/src/store/user_deletion/content_batches/mod.rs @@ -30,7 +30,7 @@ const KINDS: &[i32] = &[ 30175, 30176, 30178, 30030, 30180, 30621, ]; const PAGE_SIZE: i64 = 100; -const MAX_TARGETS: usize = 10_000; +use super::agent_ownership::MAX_TARGETS; const EVENT_COLUMNS: &str = "e.id,e.created_at,e.channel_id,e.kind,e.tags"; /// Scope and bounds for standalone preview or explicitly requested deletion. diff --git a/crates/buzz-db/src/store/user_deletion/content_batches/ownership.rs b/crates/buzz-db/src/store/user_deletion/content_batches/ownership.rs index 38e394ad935..a0461479073 100644 --- a/crates/buzz-db/src/store/user_deletion/content_batches/ownership.rs +++ b/crates/buzz-db/src/store/user_deletion/content_batches/ownership.rs @@ -7,24 +7,12 @@ pub(super) async fn targets( subject: &str, lock: bool, ) -> Result>> { - let query = if lock { - "SELECT pubkey FROM users WHERE community_id=$1 AND agent_owner_pubkey=decode($2,'hex') ORDER BY pubkey LIMIT $3 FOR SHARE" - } else { - "SELECT pubkey FROM users WHERE community_id=$1 AND agent_owner_pubkey=decode($2,'hex') ORDER BY pubkey LIMIT $3" - }; - let mut keys: Vec> = sqlx::query_scalar(query) - .bind(community) - .bind(subject) - .bind((MAX_TARGETS + 1) as i64) - .fetch_all(conn) - .await?; - keys.push(hex::decode(subject).map_err(|_| invalid("invalid target key"))?); - keys.sort(); - keys.dedup(); - if keys.len() > MAX_TARGETS { - return Err(invalid("content target key limit exceeded (10,000)")); - } - Ok(keys) + super::super::agent_ownership::discover(conn, subject, Some(community), lock) + .await? + .pubkeys() + .iter() + .map(|key| hex::decode(key).map_err(|_| invalid("invalid target key"))) + .collect() } pub(super) async fn excluded( diff --git a/crates/buzz-db/src/store/user_deletion/media.rs b/crates/buzz-db/src/store/user_deletion/media.rs index 98bd2db0deb..b76574d7c4b 100644 --- a/crates/buzz-db/src/store/user_deletion/media.rs +++ b/crates/buzz-db/src/store/user_deletion/media.rs @@ -2,34 +2,9 @@ use crate::{Db, DbError, Result}; use uuid::Uuid; -/// Fresh human ownership and direct agents, retaining each agent’s community. -#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)] -pub struct UserMediaTargets { - /// The human remains the global discovery root. - pub human: String, - /// Agent authority applies only in the recorded community. - pub agents: Vec<(Uuid, String)>, -} - -impl UserMediaTargets { - /// Whether an upload claim belongs to this deletion scope. - pub fn contains(&self, community: Uuid, pubkey: &str) -> bool { - pubkey == self.human - || self - .agents - .iter() - .any(|(c, key)| *c == community && key == pubkey) - } - - /// Unique public keys for indexed candidate discovery and display only. - pub fn pubkeys(&self) -> Vec { - let mut keys = vec![self.human.clone()]; - keys.extend(self.agents.iter().map(|(_, key)| key.clone())); - keys.sort(); - keys.dedup(); - keys - } +use super::agent_ownership::{self, UserDeletionTargets, MAX_TARGETS}; +impl UserDeletionTargets { fn communities(&self) -> Vec { self.agents .iter() @@ -47,8 +22,6 @@ fn decode_key(key: &str) -> Result> { .map_err(|error| DbError::InvalidData(error.to_string())) } -const MAX_MEDIA_TARGETS: usize = 10_000; - const CANDIDATES_SQL: &str = r#"WITH candidates AS MATERIALIZED (SELECT sha256 FROM ( SELECT sha256 COLLATE "C" AS sha256 FROM media_uploaders WHERE pubkey = ANY($1::bytea[]) @@ -71,28 +44,13 @@ const CANDIDATES_SQL: &str = r#"WITH candidates AS MATERIALIZED (SELECT sha256 F impl Db { /// Fetch direct agent ownership per community on every invocation and retry. - pub async fn user_media_targets(&self, pubkey: &str) -> Result { + pub async fn user_media_targets(&self, pubkey: &str) -> Result { let human = super::normalize_user_deletion_pubkey(pubkey)?; let mut tx = self.pool().begin().await?; sqlx::query("SET LOCAL statement_timeout = '120s'") .execute(&mut *tx) .await?; - let agents: Vec<(Uuid, String)> = sqlx::query_as( - "SELECT community_id, encode(pubkey, 'hex') FROM users - WHERE agent_owner_pubkey = decode($1, 'hex') AND pubkey <> decode($1, 'hex') - ORDER BY community_id, pubkey LIMIT $2", - ) - .bind(&human) - .bind((MAX_MEDIA_TARGETS + 1) as i64) - .fetch_all(&mut *tx) - .await?; - if agents.len() > MAX_MEDIA_TARGETS { - return Err(DbError::InvalidData( - "media agent scope exceeds 10000 entries".into(), - )); - } - let targets = UserMediaTargets { human, agents }; - validate_keys(&targets.pubkeys())?; + let targets = agent_ownership::discover(&mut tx, &human, None, false).await?; tx.commit().await?; Ok(targets) } @@ -101,7 +59,7 @@ impl Db { /// An empty cursor starts the scan. Storage-only claims are discovered separately. pub async fn user_media_candidates( &self, - targets: &UserMediaTargets, + targets: &UserDeletionTargets, after: &str, limit: u16, ) -> Result> { @@ -138,7 +96,7 @@ impl Db { /// Call this for storage-discovered candidates too, before deleting anything. pub async fn user_media_shared_hashes( &self, - targets: &UserMediaTargets, + targets: &UserDeletionTargets, hashes: &[String], ) -> Result> { validate_keys(&targets.pubkeys())?; @@ -179,7 +137,7 @@ impl Db { /// Audit history and publication moderation records are retained. pub async fn remove_user_media_uploader( &self, - targets: &UserMediaTargets, + targets: &UserDeletionTargets, hash: &str, ) -> Result { validate_keys(&targets.pubkeys())?; @@ -199,7 +157,7 @@ impl Db { } fn validate_keys(pubkeys: &[String]) -> Result>> { - if pubkeys.is_empty() || pubkeys.len() > MAX_MEDIA_TARGETS { + if pubkeys.is_empty() || pubkeys.len() > MAX_TARGETS { return Err(DbError::InvalidData( "media target set must contain 1..=10000 keys".into(), )); @@ -463,7 +421,7 @@ mod postgres_tests { .contains(&(hashes[0].clone(), false))); assert!(db .remove_user_media_uploader( - &UserMediaTargets { + &UserDeletionTargets { human: "invalid".into(), agents: vec![] }, diff --git a/crates/buzz-db/src/store/user_deletion/media_query_plan_postgres_tests.rs b/crates/buzz-db/src/store/user_deletion/media_query_plan_postgres_tests.rs index 1f05c5cc863..1608f9d4694 100644 --- a/crates/buzz-db/src/store/user_deletion/media_query_plan_postgres_tests.rs +++ b/crates/buzz-db/src/store/user_deletion/media_query_plan_postgres_tests.rs @@ -17,6 +17,15 @@ async fn media_discovery_and_sharing_use_indexes_without_current_membership() { .unwrap(); let alice = nostr::Keys::generate().public_key().to_hex(); let bob = nostr::Keys::generate().public_key().to_hex(); + let agent = nostr::Keys::generate().public_key().to_hex(); + sqlx::query("INSERT INTO users(community_id,pubkey) VALUES ($1,decode($2,'hex'))") + .bind(community) + .bind(&alice) + .execute(&pool) + .await + .unwrap(); + sqlx::query("INSERT INTO users(community_id,pubkey,agent_owner_pubkey) VALUES ($1,decode($2,'hex'),decode($3,'hex'))") + .bind(community).bind(&agent).bind(&alice).execute(&pool).await.unwrap(); // Membership was removed; retained attribution is still authoritative. sqlx::query("INSERT INTO relay_members(community_id, pubkey, role) VALUES ($1, $2, 'member')") .bind(community) @@ -54,7 +63,7 @@ async fn media_discovery_and_sharing_use_indexes_without_current_membership() { ) .bind(community) .bind(format!("{:064x}", 40002)) - .bind(&alice) + .bind(&agent) .execute(&pool) .await .unwrap(); @@ -64,6 +73,7 @@ async fn media_discovery_and_sharing_use_indexes_without_current_membership() { .unwrap(); let db = Db::from_pool(pool.clone()); let targets = db.user_media_targets(&alice).await.unwrap(); + assert_eq!(targets.agents, vec![(community, agent)]); let actual = db.user_media_candidates(&targets, "", 500).await.unwrap(); assert_eq!( actual, diff --git a/crates/buzz-db/src/store/user_deletion/mod.rs b/crates/buzz-db/src/store/user_deletion/mod.rs index 108e92bdb0c..e4a50a06d8e 100644 --- a/crates/buzz-db/src/store/user_deletion/mod.rs +++ b/crates/buzz-db/src/store/user_deletion/mod.rs @@ -3,6 +3,7 @@ use crate::Db; use sqlx::PgPool; /// Bounded cleanup of one human's community account records. pub mod account_batches; +mod agent_ownership; /// Ordered user and owned-agent content cleanup in read-only and delete modes. pub mod content_batches; mod discovery; @@ -10,7 +11,7 @@ mod inventory; mod media; /// Standalone, offline profile cleanup with read-only preview. pub mod profile_batches; -pub use media::UserMediaTargets; +pub use agent_ownership::UserDeletionTargets; 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/ownership.rs b/crates/buzz-db/src/store/user_deletion/profile_batches/ownership.rs index 9b2b63ce0db..877b42699e4 100644 --- a/crates/buzz-db/src/store/user_deletion/profile_batches/ownership.rs +++ b/crates/buzz-db/src/store/user_deletion/profile_batches/ownership.rs @@ -1,5 +1,4 @@ use super::*; -use std::collections::BTreeSet; pub(super) async fn targets( conn: &mut PgConnection, @@ -7,22 +6,11 @@ pub(super) async fn targets( 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()) + Ok( + super::super::agent_ownership::discover(conn, human, Some(community), lock) + .await? + .pubkeys(), + ) } pub(super) async fn recheck( diff --git a/crates/buzz-deletion/src/user/media.rs b/crates/buzz-deletion/src/user/media.rs index 505abcd1e6e..c8ea3124cbf 100644 --- a/crates/buzz-deletion/src/user/media.rs +++ b/crates/buzz-deletion/src/user/media.rs @@ -1,6 +1,6 @@ //! User media cleanup. Both modes use the same upload-only inventory. use anyhow::{bail, Context, Result}; -use buzz_db::{user_deletion::UserMediaTargets, Db, DbConfig}; +use buzz_db::{user_deletion::UserDeletionTargets, Db, DbConfig}; use buzz_media::{ classify_key, KeyClass, MediaStorage, ObjectVersionEntry, ObjectVersionKind, ObjectVersionRef, ObjectVersionsPage, UploadRecord, UPLOAD_RECORD_VERSION, @@ -70,32 +70,37 @@ pub(super) async fn handle_with_storage( // Fakes replace only external DB/storage boundaries; the tests run the same // candidate collection, prefix scans, bounded inventory and deletion loop. trait Database { - async fn targets(&self, pubkey: &str) -> Result; + async fn targets(&self, pubkey: &str) -> Result; async fn candidates( &self, - pubkeys: &UserMediaTargets, + pubkeys: &UserDeletionTargets, after: &str, ) -> Result>; - async fn shared(&self, pubkeys: &UserMediaTargets, hashes: &[String]) -> Result>; - async fn remove(&self, pubkeys: &UserMediaTargets, hash: &str) -> Result; + async fn shared(&self, pubkeys: &UserDeletionTargets, hashes: &[String]) + -> Result>; + async fn remove(&self, pubkeys: &UserDeletionTargets, hash: &str) -> Result; } impl Database for Db { - async fn targets(&self, pubkey: &str) -> Result { + async fn targets(&self, pubkey: &str) -> Result { Ok(self.user_media_targets(pubkey).await?) } async fn candidates( &self, - pubkeys: &UserMediaTargets, + pubkeys: &UserDeletionTargets, after: &str, ) -> Result> { Ok(self .user_media_candidates(pubkeys, after, PAGE_SIZE) .await?) } - async fn shared(&self, pubkeys: &UserMediaTargets, hashes: &[String]) -> Result> { + async fn shared( + &self, + pubkeys: &UserDeletionTargets, + hashes: &[String], + ) -> Result> { Ok(self.user_media_shared_hashes(pubkeys, hashes).await?) } - async fn remove(&self, pubkeys: &UserMediaTargets, hash: &str) -> Result { + async fn remove(&self, pubkeys: &UserDeletionTargets, hash: &str) -> Result { Ok(self.remove_user_media_uploader(pubkeys, hash).await?) } } @@ -209,7 +214,7 @@ async fn run_handler_with_inventory( Ok(result) } -async fn require_current_targets(db: &impl Database, targets: &UserMediaTargets) -> Result<()> { +async fn require_current_targets(db: &impl Database, targets: &UserDeletionTargets) -> Result<()> { if db.targets(&targets.human).await? != *targets { bail!("media agent ownership changed; retry to discover current community ownership"); } @@ -218,7 +223,7 @@ async fn require_current_targets(db: &impl Database, targets: &UserMediaTargets) async fn scan_storage( media: &impl Storage, - targets: &UserMediaTargets, + targets: &UserDeletionTargets, inventory: &mut Inventory, prefix: &str, candidates_only: bool, @@ -396,9 +401,9 @@ mod tests { removed: RefCell>, } impl Database for FakeDb { - async fn targets(&self, pubkey: &str) -> Result { + async fn targets(&self, pubkey: &str) -> Result { *self.target_calls.borrow_mut() += 1; - Ok(UserMediaTargets { + Ok(UserDeletionTargets { human: pubkey.to_owned(), agents: match &self.changed_targets { Some((after, targets)) if *self.target_calls.borrow() > *after => { @@ -410,7 +415,7 @@ mod tests { } async fn candidates( &self, - keys: &UserMediaTargets, + keys: &UserDeletionTargets, after: &str, ) -> Result> { if !self.targets.is_empty() { @@ -424,7 +429,11 @@ mod tests { .map(|hash| (hash.clone(), self.shared.contains(hash))) .collect()) } - async fn shared(&self, keys: &UserMediaTargets, hashes: &[String]) -> Result> { + async fn shared( + &self, + keys: &UserDeletionTargets, + hashes: &[String], + ) -> Result> { if !self.targets.is_empty() { assert_eq!(keys.agents, self.targets); } @@ -435,7 +444,7 @@ mod tests { .cloned() .collect()) } - async fn remove(&self, keys: &UserMediaTargets, hash: &str) -> Result { + async fn remove(&self, keys: &UserDeletionTargets, hash: &str) -> Result { if !self.targets.is_empty() { assert_eq!(keys.agents, self.targets); } diff --git a/crates/buzz-deletion/src/user/media/tests/ownership.rs b/crates/buzz-deletion/src/user/media/tests/ownership.rs index 18ed36127c5..ffd61f6eb2c 100644 --- a/crates/buzz-deletion/src/user/media/tests/ownership.rs +++ b/crates/buzz-deletion/src/user/media/tests/ownership.rs @@ -92,6 +92,32 @@ async fn changed_ownership_aborts_before_mutation_and_retry_rediscovers() { } } +#[tokio::test] +async fn changed_ownership_aborts_at_uploader_removal_with_or_without_storage_deletes() { + for shared in [false, true] { + let hash = "a".repeat(64); + let db = FakeDb { + targets: vec![(uuid::Uuid::from_u128(1), AGENT.into())], + changed_targets: Some((if shared { 1 } else { 3 }, vec![])), + shared: if shared { vec![hash.clone()] } else { vec![] }, + ..Default::default() + }; + let mut media = FakeStorage::default(); + media.upload(&hash, AGENT, 1); + media.object(format!("{hash}.png"), ObjectVersionKind::Object); + let before = media.entries.borrow().clone(); + let error = run_handler(&db, &media, ALICE, true, &mut Vec::new()) + .await + .unwrap_err(); + assert!(error.to_string().contains("ownership changed")); + assert!(db.removed.borrow().is_empty()); + assert_eq!(media.deleted.borrow().len(), if shared { 0 } else { 2 }); + if shared { + assert_eq!(*media.entries.borrow(), before); + } + } +} + #[tokio::test] async fn empty_inventory_rechecks_new_agents_before_reporting_success() { let db = FakeDb { diff --git a/crates/buzz-deletion/src/user/media_report.rs b/crates/buzz-deletion/src/user/media_report.rs index a2ea10ac7e3..8349beb3cdb 100644 --- a/crates/buzz-deletion/src/user/media_report.rs +++ b/crates/buzz-deletion/src/user/media_report.rs @@ -1,5 +1,5 @@ //! One JSON document, streamed from bounded inventory pages even for large files. -use super::{require_current_targets, Database, Inventory, Storage, UserMediaTargets}; +use super::{require_current_targets, Database, Inventory, Storage, UserDeletionTargets}; use anyhow::Result; use serde_json::{json, Value}; use std::io::Write; @@ -7,7 +7,7 @@ use std::io::Write; pub(super) async fn execute( db: &impl Database, media: &impl Storage, - pubkeys: &UserMediaTargets, + pubkeys: &UserDeletionTargets, delete: bool, inventory: &mut Inventory, output: &mut impl Write, diff --git a/docs/operator-user-deletion-executor.md b/docs/operator-user-deletion-executor.md index 9b9990a4bb2..7b377c6b089 100644 --- a/docs/operator-user-deletion-executor.md +++ b/docs/operator-user-deletion-executor.md @@ -248,6 +248,27 @@ placeholder failures and branching only. Demo media success is synthetic; real r An injected community failure preserves the same retry semantics as before. Ctrl-C releases the worker lease; after an abrupt kill wait for lease expiry. +## Shared agent discovery + +Media, content, account, and profile cleanup use the same discovery utility in +`buzz-db/src/store/user_deletion/agent_ownership.rs`, including account scope +capture. It normalizes the human key, reads current direct ownership from +`users`, and retains `(community_id, agent_pubkey)` pairs. It does not infer +ownership from membership, recurse through agents, or exclude deactivated +profiles. A missing profile grants no agent cleanup authority. + +Every invocation and retry discovers again. Content, account, and profile +handlers use the utility inside their existing batch transactions with row +locks when rechecking ownership. Profile cleanup compares against the identities +that remain after its own committed batches. Media rechecks before each storage +mutation, uploader-row removal, and successful completion. These checks do not +replace the requirement to stop writers, or make PostgreSQL and storage atomic. + +Discovery rejects more than 10,000 ownership pairs or distinct target keys +(including the human), rather than returning a partial set. Individual handlers +retain their additional operation and output limits. Ownership profiles must +remain until all dependent cleanup completes; profile removal goes last. + ## Media discovery and remaining limits Every invocation and retry fetches the human's current directly owned agents From 4b038e5554a2874e973151597db69489eaf90e09 Mon Sep 17 00:00:00 2001 From: Ravneet Arora Date: Wed, 18 Nov 2026 13:09:18 -0500 Subject: [PATCH 3/5] test: align deletion assertions with shared discovery Co-authored-by: dessert <7d616e7e143e5d408159614dccff1371350a1c1bd36c8de838a45ece5aca0aca@buzz.block.builderlab.xyz> Signed-off-by: Ravneet Arora --- .../user_deletion/content_batches/agents_postgres_tests.rs | 2 +- .../buzz-deletion/src/user/worker_postgres_tests/media_retry.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/buzz-db/src/store/user_deletion/content_batches/agents_postgres_tests.rs b/crates/buzz-db/src/store/user_deletion/content_batches/agents_postgres_tests.rs index 5a4589993f6..8e494ab279d 100644 --- a/crates/buzz-db/src/store/user_deletion/content_batches/agents_postgres_tests.rs +++ b/crates/buzz-db/src/store/user_deletion/content_batches/agents_postgres_tests.rs @@ -441,7 +441,7 @@ async fn target_discovery_handles_no_agents_and_rejects_overflow_without_output( .run_message_batches(&options, mode, None, &mut output) .await .unwrap_err(); - assert!(error.to_string().contains("target key limit")); + assert!(error.to_string().contains("ownership exceeds target limit")); assert!(output.is_empty()); } assert_eq!(snapshot_rows(&pool, community, "users").await.len(), 10001); diff --git a/crates/buzz-deletion/src/user/worker_postgres_tests/media_retry.rs b/crates/buzz-deletion/src/user/worker_postgres_tests/media_retry.rs index 1886a58b7c0..7469ac6d472 100644 --- a/crates/buzz-deletion/src/user/worker_postgres_tests/media_retry.rs +++ b/crates/buzz-deletion/src/user/worker_postgres_tests/media_retry.rs @@ -180,7 +180,7 @@ async fn workflow_media_retry_refetches_agent_ownership_before_deleting() { after.stage_history[1].metadata_json["result"]["selected_files"], 0 ); - assert_eq!(after.stage_history[2].stage, "purge_db"); + assert_eq!(after.stage_history[2].stage, "purge_content"); assert!(!fixture.deleted.load(Ordering::SeqCst)); assert_eq!(fixture.uploader_count().await, 1); } From fa90c88a985aceb6615081dffadf4d4f7ba7e43b Mon Sep 17 00:00:00 2001 From: dessert <7d616e7e143e5d408159614dccff1371350a1c1bd36c8de838a45ece5aca0aca@buzz.block.builderlab.xyz> Date: Wed, 18 Nov 2026 17:04:07 -0500 Subject: [PATCH 4/5] fix(deletion): remove redundant media discovery Preserve original caller limits and media report shape. Match storage claims with a community-key hash set and retain ownership in another community in the retry regression. Signed-off-by: dessert <7d616e7e143e5d408159614dccff1371350a1c1bd36c8de838a45ece5aca0aca@buzz.block.builderlab.xyz> --- .../account_batches/ownership.rs | 18 +-- .../user_deletion/account_batches/scope.rs | 12 +- .../store/user_deletion/agent_ownership.rs | 54 ++++++--- .../agent_ownership_postgres_tests.rs | 112 +++++++++++++++--- .../content_batches/ownership.rs | 18 ++- .../buzz-db/src/store/user_deletion/media.rs | 9 +- .../profile_batches/ownership.rs | 12 +- crates/buzz-deletion/src/user/media.rs | 70 +++++++---- .../src/user/media/tests/ownership.rs | 94 +-------------- crates/buzz-deletion/src/user/media_report.rs | 7 +- .../user/worker_postgres_tests/media_retry.rs | 13 +- docs/operator-user-deletion-executor.md | 24 ++-- 12 files changed, 251 insertions(+), 192 deletions(-) diff --git a/crates/buzz-db/src/store/user_deletion/account_batches/ownership.rs b/crates/buzz-db/src/store/user_deletion/account_batches/ownership.rs index 5e529cfbb17..2bfc94edbcd 100644 --- a/crates/buzz-db/src/store/user_deletion/account_batches/ownership.rs +++ b/crates/buzz-db/src/store/user_deletion/account_batches/ownership.rs @@ -74,14 +74,18 @@ pub(super) async fn agents( target: &str, lock: bool, ) -> Result> { - Ok( - super::super::agent_ownership::discover(conn, target, Some(community), lock) - .await? - .agents - .into_iter() - .map(|(_, key)| key) - .collect(), + Ok(super::super::agent_ownership::discover( + conn, + target, + Some(community), + lock, + super::super::agent_ownership::DiscoveryLimit::AgentRows, ) + .await? + .agents + .into_iter() + .map(|(_, key)| key) + .collect()) } pub(super) async fn recheck(conn: &mut PgConnection, options: &Options, lock: bool) -> Result<()> { diff --git a/crates/buzz-db/src/store/user_deletion/account_batches/scope.rs b/crates/buzz-db/src/store/user_deletion/account_batches/scope.rs index af93abd0ad4..bf9e3195b9c 100644 --- a/crates/buzz-db/src/store/user_deletion/account_batches/scope.rs +++ b/crates/buzz-db/src/store/user_deletion/account_batches/scope.rs @@ -87,9 +87,15 @@ impl UserDeletionStore { if communities.len() > super::super::MAX_COMMUNITIES { return Err(invalid("account scope exceeds community limit")); } - let agents = agent_ownership::discover(&mut tx, &target, None, false) - .await? - .agents; + let agents = agent_ownership::discover( + &mut tx, + &target, + None, + false, + agent_ownership::DiscoveryLimit::AgentRows, + ) + .await? + .agents; let scope = AccountScope { version: 1, target: target.clone(), diff --git a/crates/buzz-db/src/store/user_deletion/agent_ownership.rs b/crates/buzz-db/src/store/user_deletion/agent_ownership.rs index 25af2487f15..ef5d35c3826 100644 --- a/crates/buzz-db/src/store/user_deletion/agent_ownership.rs +++ b/crates/buzz-db/src/store/user_deletion/agent_ownership.rs @@ -6,6 +6,13 @@ use uuid::Uuid; pub(super) const MAX_TARGETS: usize = 10_000; +/// Preserve the caller's existing bound: agent rows, or identities including the human. +#[derive(Clone, Copy, PartialEq, Eq)] +pub(super) enum DiscoveryLimit { + AgentRows, + TargetKeys, +} + /// Fresh human and direct-agent identities, retaining each agent's community. #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)] pub struct UserDeletionTargets { @@ -16,15 +23,6 @@ pub struct UserDeletionTargets { } impl UserDeletionTargets { - /// Whether an upload claim belongs to this deletion scope. - pub fn contains(&self, community: Uuid, pubkey: &str) -> bool { - pubkey == self.human - || self - .agents - .iter() - .any(|(c, key)| *c == community && key == pubkey) - } - /// Sorted distinct identities. Global callers must retain community pairs /// when authorizing deletion; this flattened list alone grants no authority. pub fn pubkeys(&self) -> Vec { @@ -46,11 +44,17 @@ pub(super) async fn discover( human: &str, community: Option, lock: bool, + limit: DiscoveryLimit, ) -> Result { let human = normalize_user_deletion_pubkey(human)?; - let mut query = QueryBuilder::::new( - "SELECT community_id, encode(pubkey,'hex') FROM users WHERE agent_owner_pubkey=decode(", - ); + // Media historically limits distinct identities, not community profiles. + // Group those profiles before LIMIT so an agent's communities are never truncated. + let grouped = community.is_none() && limit == DiscoveryLimit::TargetKeys; + let mut query = QueryBuilder::::new(if grouped { + "SELECT array_agg(community_id ORDER BY community_id), encode(pubkey,'hex') FROM users WHERE agent_owner_pubkey=decode(" + } else { + "SELECT ARRAY[community_id], encode(pubkey,'hex') FROM users WHERE agent_owner_pubkey=decode(" + }); query .push_bind(human.clone()) .push(", 'hex') AND pubkey<>decode(") @@ -59,21 +63,33 @@ pub(super) async fn discover( if let Some(community) = community { query.push(" AND community_id=").push_bind(community); } - query - .push(" ORDER BY community_id, pubkey LIMIT ") - .push_bind((MAX_TARGETS + 1) as i64); + if grouped { + query.push(" GROUP BY pubkey ORDER BY pubkey"); + } else { + query.push(" ORDER BY community_id, pubkey"); + } + query.push(" LIMIT ").push_bind((MAX_TARGETS + 1) as i64); if lock { query.push(" FOR SHARE"); } - let agents = query.build_query_as().fetch_all(conn).await?; - let targets = UserDeletionTargets { human, agents }; - if targets.agents.len() > MAX_TARGETS || targets.pubkeys().len() > MAX_TARGETS { + let rows: Vec<(Vec, String)> = query.build_query_as().fetch_all(conn).await?; + let count = rows.len() + usize::from(limit == DiscoveryLimit::TargetKeys); + if count > MAX_TARGETS { return Err(DbError::DeletionSafety( "user deletion ownership exceeds target limit (10000); no partial scope returned" .into(), )); } - Ok(targets) + let mut agents: Vec<_> = rows + .into_iter() + .flat_map(|(communities, key)| { + communities + .into_iter() + .map(move |community| (community, key.clone())) + }) + .collect(); + agents.sort(); + Ok(UserDeletionTargets { human, agents }) } #[cfg(test)] diff --git a/crates/buzz-db/src/store/user_deletion/agent_ownership_postgres_tests.rs b/crates/buzz-db/src/store/user_deletion/agent_ownership_postgres_tests.rs index 9212a2111cc..c90cd66e69b 100644 --- a/crates/buzz-db/src/store/user_deletion/agent_ownership_postgres_tests.rs +++ b/crates/buzz-db/src/store/user_deletion/agent_ownership_postgres_tests.rs @@ -176,14 +176,21 @@ async fn discovery_is_direct_normalized_and_holds_the_callers_row_locks() { .to_bech32() .unwrap(); let mut tx = f.db.pool().begin().await.unwrap(); - let targets = discover(&mut tx, &npub, Some(f.communities[0]), true) - .await - .unwrap(); + let targets = discover( + &mut tx, + &npub, + Some(f.communities[0]), + true, + DiscoveryLimit::TargetKeys, + ) + .await + .unwrap(); assert_eq!(targets.human, f.human); assert_eq!(targets.agents, vec![(f.communities[0], f.agent.clone())]); - assert!(!targets.contains(f.communities[1], &f.agent)); - assert!(!targets.contains(f.communities[0], &nested)); - assert!(targets.contains(f.communities[2], &f.human)); + assert!(!targets + .agents + .contains(&(f.communities[1], f.agent.clone()))); + assert!(!targets.agents.contains(&(f.communities[0], nested.clone()))); let mut transfer = f.db.pool().begin().await.unwrap(); sqlx::query("SET LOCAL lock_timeout='50ms'") .execute(&mut *transfer) @@ -201,17 +208,92 @@ async fn discovery_is_direct_normalized_and_holds_the_callers_row_locks() { #[tokio::test] #[ignore = "requires Postgres"] -async fn discovery_rejects_oversized_ownership_without_returning_a_partial_scope() { +async fn discovery_preserves_each_callers_original_limit_without_truncating_communities() { let f = Fixture::new().await; - sqlx::query("INSERT INTO users(community_id,pubkey,agent_owner_pubkey) SELECT $1,decode(lpad(to_hex(n),64,'0'),'hex'),decode($2,'hex') FROM generate_series(1,10000) n") + sqlx::query("INSERT INTO users(community_id,pubkey,agent_owner_pubkey) SELECT c,decode(lpad(to_hex(n),64,'0'),'hex'),decode($3,'hex') FROM unnest(ARRAY[$1::uuid,$2::uuid]) c CROSS JOIN generate_series(1,5000) n") + .bind(f.communities[0]).bind(f.communities[1]).bind(&f.human) + .execute(f.db.pool()).await.unwrap(); + let media = f.db.user_media_targets(&f.human).await.unwrap(); + assert_eq!(media.agents.len(), 10001); + assert_eq!(media.pubkeys().len(), 5002); + assert!(media + .agents + .contains(&(f.communities[1], format!("{:064x}", 5000)))); + sqlx::query("INSERT INTO users(community_id,pubkey,agent_owner_pubkey) SELECT $1,decode(lpad(to_hex(n),64,'0'),'hex'),decode($2,'hex') FROM generate_series(5001,9998) n") .bind(f.communities[0]).bind(&f.human).execute(f.db.pool()).await.unwrap(); - for community in [None, Some(f.communities[0])] { - let mut tx = f.db.pool().begin().await.unwrap(); - assert!(discover(&mut tx, &f.human, community, false) + assert_eq!( + f.db.user_media_targets(&f.human) .await - .unwrap_err() - .to_string() - .contains("no partial scope")); - tx.rollback().await.unwrap(); + .unwrap() + .pubkeys() + .len(), + MAX_TARGETS + ); + let mut tx = f.db.pool().begin().await.unwrap(); + assert_eq!( + discover( + &mut tx, + &f.human, + Some(f.communities[0]), + false, + DiscoveryLimit::TargetKeys + ) + .await + .unwrap() + .pubkeys() + .len(), + MAX_TARGETS + ); + tx.rollback().await.unwrap(); + sqlx::query("INSERT INTO users(community_id,pubkey,agent_owner_pubkey) VALUES ($1,decode($2,'hex'),decode($3,'hex'))") + .bind(f.communities[0]).bind(format!("{:064x}", 9999)).bind(&f.human) + .execute(f.db.pool()).await.unwrap(); + let mut tx = f.db.pool().begin().await.unwrap(); + assert_eq!( + discover( + &mut tx, + &f.human, + Some(f.communities[0]), + false, + DiscoveryLimit::AgentRows + ) + .await + .unwrap() + .agents + .len(), + MAX_TARGETS + ); + for community in [None, Some(f.communities[0])] { + assert!(discover( + &mut tx, + &f.human, + community, + false, + DiscoveryLimit::TargetKeys + ) + .await + .unwrap_err() + .to_string() + .contains("no partial scope")); } + assert!( + discover(&mut tx, &f.human, None, false, DiscoveryLimit::AgentRows) + .await + .is_err() + ); + tx.rollback().await.unwrap(); + sqlx::query("INSERT INTO users(community_id,pubkey,agent_owner_pubkey) VALUES ($1,decode($2,'hex'),decode($3,'hex'))") + .bind(f.communities[0]).bind(format!("{:064x}", 10000)).bind(&f.human) + .execute(f.db.pool()).await.unwrap(); + let mut tx = f.db.pool().begin().await.unwrap(); + assert!(discover( + &mut tx, + &f.human, + Some(f.communities[0]), + false, + DiscoveryLimit::AgentRows + ) + .await + .is_err()); + tx.rollback().await.unwrap(); } diff --git a/crates/buzz-db/src/store/user_deletion/content_batches/ownership.rs b/crates/buzz-db/src/store/user_deletion/content_batches/ownership.rs index a0461479073..7fddb521f6e 100644 --- a/crates/buzz-db/src/store/user_deletion/content_batches/ownership.rs +++ b/crates/buzz-db/src/store/user_deletion/content_batches/ownership.rs @@ -7,12 +7,18 @@ pub(super) async fn targets( subject: &str, lock: bool, ) -> Result>> { - super::super::agent_ownership::discover(conn, subject, Some(community), lock) - .await? - .pubkeys() - .iter() - .map(|key| hex::decode(key).map_err(|_| invalid("invalid target key"))) - .collect() + super::super::agent_ownership::discover( + conn, + subject, + Some(community), + lock, + super::super::agent_ownership::DiscoveryLimit::TargetKeys, + ) + .await? + .pubkeys() + .iter() + .map(|key| hex::decode(key).map_err(|_| invalid("invalid target key"))) + .collect() } pub(super) async fn excluded( diff --git a/crates/buzz-db/src/store/user_deletion/media.rs b/crates/buzz-db/src/store/user_deletion/media.rs index b76574d7c4b..f3f1f2b7955 100644 --- a/crates/buzz-db/src/store/user_deletion/media.rs +++ b/crates/buzz-db/src/store/user_deletion/media.rs @@ -50,7 +50,14 @@ impl Db { sqlx::query("SET LOCAL statement_timeout = '120s'") .execute(&mut *tx) .await?; - let targets = agent_ownership::discover(&mut tx, &human, None, false).await?; + let targets = agent_ownership::discover( + &mut tx, + &human, + None, + false, + agent_ownership::DiscoveryLimit::TargetKeys, + ) + .await?; tx.commit().await?; Ok(targets) } 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 index 877b42699e4..3418a2558ea 100644 --- a/crates/buzz-db/src/store/user_deletion/profile_batches/ownership.rs +++ b/crates/buzz-db/src/store/user_deletion/profile_batches/ownership.rs @@ -6,11 +6,15 @@ pub(super) async fn targets( human: &str, lock: bool, ) -> Result> { - Ok( - super::super::agent_ownership::discover(conn, human, Some(community), lock) - .await? - .pubkeys(), + Ok(super::super::agent_ownership::discover( + conn, + human, + Some(community), + lock, + super::super::agent_ownership::DiscoveryLimit::TargetKeys, ) + .await? + .pubkeys()) } pub(super) async fn recheck( diff --git a/crates/buzz-deletion/src/user/media.rs b/crates/buzz-deletion/src/user/media.rs index c8ea3124cbf..0bd4fc5a398 100644 --- a/crates/buzz-deletion/src/user/media.rs +++ b/crates/buzz-deletion/src/user/media.rs @@ -6,6 +6,7 @@ use buzz_media::{ ObjectVersionsPage, UploadRecord, UPLOAD_RECORD_VERSION, }; use serde_json::Value; +use std::collections::HashSet; use std::io::{BufWriter, Write}; #[path = "media_inventory.rs"] mod inventory; @@ -163,6 +164,7 @@ async fn run_handler_with_inventory( mut inventory: Inventory, ) -> Result { let keys = db.targets(pubkey).await?; + let keys_set: HashSet<_> = keys.agents.iter().cloned().collect(); let mut after = String::new(); loop { let page = db.candidates(&keys, &after).await?; @@ -177,7 +179,15 @@ async fn run_handler_with_inventory( } // Finish discovery before classifying storage-only candidates. Historical // upload claims may precede the target's claim in the listing. - scan_storage(media, &keys, &mut inventory, "_uploads/", true).await?; + scan_storage( + media, + &keys.human, + &keys_set, + &mut inventory, + "_uploads/", + true, + ) + .await?; after.clear(); loop { let hashes = inventory.unchecked_candidates(&after).await?; @@ -192,8 +202,24 @@ async fn run_handler_with_inventory( if !inventory.candidates("").await?.is_empty() { // These community-first namespaces cannot be looked up by hash alone. // Keep complete historical coverage, including removed communities. - scan_storage(media, &keys, &mut inventory, "_uploads/", false).await?; - scan_storage(media, &keys, &mut inventory, "_meta/", false).await?; + scan_storage( + media, + &keys.human, + &keys_set, + &mut inventory, + "_uploads/", + false, + ) + .await?; + scan_storage( + media, + &keys.human, + &keys_set, + &mut inventory, + "_meta/", + false, + ) + .await?; } after.clear(); loop { @@ -205,7 +231,15 @@ async fn run_handler_with_inventory( for (hash, _) in page { // The dot excludes other hash families while covering all blob // extensions, thumbnails, historical versions and delete markers. - scan_storage(media, &keys, &mut inventory, &format!("{hash}."), false).await?; + scan_storage( + media, + &keys.human, + &keys_set, + &mut inventory, + &format!("{hash}."), + false, + ) + .await?; } } inventory.require_immutable_versions().await?; @@ -214,16 +248,10 @@ async fn run_handler_with_inventory( Ok(result) } -async fn require_current_targets(db: &impl Database, targets: &UserDeletionTargets) -> Result<()> { - if db.targets(&targets.human).await? != *targets { - bail!("media agent ownership changed; retry to discover current community ownership"); - } - Ok(()) -} - async fn scan_storage( media: &impl Storage, - targets: &UserDeletionTargets, + human: &str, + keys_set: &HashSet<(uuid::Uuid, String)>, inventory: &mut Inventory, prefix: &str, candidates_only: bool, @@ -278,10 +306,11 @@ async fn scan_storage( let owner = buzz_db::user_deletion::normalize_user_deletion_pubkey( &record.uploader_id, )?; - if candidates_only && targets.contains(*community, &owner) { + let targeted = owner == human || keys_set.contains(&(*community, owner)); + if candidates_only && targeted { candidates.push(hash.clone()); } - if !candidates_only && !targets.contains(*community, &owner) { + if !candidates_only && !targeted { shared.push(hash.clone()); } } @@ -394,7 +423,6 @@ mod tests { struct FakeDb { targets: Vec<(uuid::Uuid, String)>, target_calls: RefCell, - changed_targets: Option<(usize, Vec<(uuid::Uuid, String)>)>, candidates: Vec, shared: Vec, checked: RefCell>, @@ -405,12 +433,7 @@ mod tests { *self.target_calls.borrow_mut() += 1; Ok(UserDeletionTargets { human: pubkey.to_owned(), - agents: match &self.changed_targets { - Some((after, targets)) if *self.target_calls.borrow() > *after => { - targets.clone() - } - _ => self.targets.clone(), - }, + agents: self.targets.clone(), }) } async fn candidates( @@ -714,6 +737,7 @@ mod tests { let report: Value = serde_json::from_slice(&output).unwrap(); assert_eq!(report["target_pubkeys"], json!([AGENT, ALICE])); assert_eq!(report["summary"], preview); + assert!(report.get("agent_communities").is_none()); let files = report["files"].as_array().unwrap(); assert_eq!(files.len(), 4); assert!(files.iter().all(|file| file.get("owners").is_none())); @@ -740,7 +764,7 @@ mod tests { assert_eq!(preview["selected_files"], 4); assert_eq!(preview["kept_files"], 2); assert_eq!(preview["deleted_versions"], 0); - assert!(*db.target_calls.borrow() >= 1); + assert_eq!(*db.target_calls.borrow(), 1); let expected_passes: Vec = ["_uploads/".into(), "_uploads/".into(), "_meta/".into()] .into_iter() @@ -762,7 +786,7 @@ mod tests { assert_eq!(result["selected_files"], 4); assert_eq!(result["kept_files"], 2); assert_eq!(result["deleted_versions"], 5); - assert!(*db.target_calls.borrow() > 2); + assert_eq!(*db.target_calls.borrow(), 2); assert_eq!( *media.passes.borrow(), expected_passes diff --git a/crates/buzz-deletion/src/user/media/tests/ownership.rs b/crates/buzz-deletion/src/user/media/tests/ownership.rs index ffd61f6eb2c..6d98aa3cb3d 100644 --- a/crates/buzz-deletion/src/user/media/tests/ownership.rs +++ b/crates/buzz-deletion/src/user/media/tests/ownership.rs @@ -1,4 +1,4 @@ -//! Ownership changes and community boundaries through the real media handler. +//! Community boundaries through the real media handler. use super::*; #[tokio::test] @@ -40,95 +40,3 @@ async fn agent_claims_in_other_communities_protect_blobs_and_are_not_selected() vec![hashes[0].clone(), hashes[2].clone(), hashes[3].clone()] ); } - -#[tokio::test] -async fn changed_ownership_aborts_before_mutation_and_retry_rediscovers() { - let community = uuid::Uuid::from_u128(1); - // Transfer away/missing row, new ownership, and same-key transfer between communities. - for changed_after in [1, 2] { - for changed in [ - vec![], - vec![(community, AGENT.into()), (community, BOB.into())], - vec![(uuid::Uuid::from_u128(2), AGENT.into())], - ] { - let mut db = FakeDb { - targets: vec![(community, AGENT.into())], - changed_targets: Some((changed_after, changed.clone())), - ..Default::default() - }; - let hash = "a".repeat(64); - let mut media = FakeStorage::default(); - media.upload(&hash, AGENT, 1); - media.object(format!("{hash}.png"), ObjectVersionKind::Object); - let before = media.entries.borrow().clone(); - let error = run_handler(&db, &media, ALICE, true, &mut Vec::new()) - .await - .unwrap_err(); - assert!(error.to_string().contains("ownership changed")); - assert_eq!(media.deleted.borrow().len(), changed_after - 1); - if changed_after == 1 { - assert_eq!(*media.entries.borrow(), before); - } - assert!(media - .entries - .borrow() - .iter() - .any(|entry| entry.key.starts_with("_uploads/"))); - assert!(db.removed.borrow().is_empty()); - db.targets = changed; - db.changed_targets = None; - let result = run_handler(&db, &media, ALICE, true, &mut Vec::new()) - .await - .unwrap(); - assert_eq!( - result["selected_files"], - if db.targets.contains(&(community, AGENT.into())) { - 1 - } else { - 0 - } - ); - } - } -} - -#[tokio::test] -async fn changed_ownership_aborts_at_uploader_removal_with_or_without_storage_deletes() { - for shared in [false, true] { - let hash = "a".repeat(64); - let db = FakeDb { - targets: vec![(uuid::Uuid::from_u128(1), AGENT.into())], - changed_targets: Some((if shared { 1 } else { 3 }, vec![])), - shared: if shared { vec![hash.clone()] } else { vec![] }, - ..Default::default() - }; - let mut media = FakeStorage::default(); - media.upload(&hash, AGENT, 1); - media.object(format!("{hash}.png"), ObjectVersionKind::Object); - let before = media.entries.borrow().clone(); - let error = run_handler(&db, &media, ALICE, true, &mut Vec::new()) - .await - .unwrap_err(); - assert!(error.to_string().contains("ownership changed")); - assert!(db.removed.borrow().is_empty()); - assert_eq!(media.deleted.borrow().len(), if shared { 0 } else { 2 }); - if shared { - assert_eq!(*media.entries.borrow(), before); - } - } -} - -#[tokio::test] -async fn empty_inventory_rechecks_new_agents_before_reporting_success() { - let db = FakeDb { - changed_targets: Some((1, vec![(uuid::Uuid::from_u128(1), AGENT.into())])), - ..Default::default() - }; - let media = FakeStorage::default(); - let error = run_handler(&db, &media, ALICE, true, &mut Vec::new()) - .await - .unwrap_err(); - assert!(error.to_string().contains("ownership changed")); - assert!(db.removed.borrow().is_empty()); - assert!(media.deleted.borrow().is_empty()); -} diff --git a/crates/buzz-deletion/src/user/media_report.rs b/crates/buzz-deletion/src/user/media_report.rs index 8349beb3cdb..a8fbfb880c5 100644 --- a/crates/buzz-deletion/src/user/media_report.rs +++ b/crates/buzz-deletion/src/user/media_report.rs @@ -1,5 +1,5 @@ //! One JSON document, streamed from bounded inventory pages even for large files. -use super::{require_current_targets, Database, Inventory, Storage, UserDeletionTargets}; +use super::{Database, Inventory, Storage, UserDeletionTargets}; use anyhow::Result; use serde_json::{json, Value}; use std::io::Write; @@ -18,8 +18,6 @@ pub(super) async fn execute( "{{\n \"mode\": \"{mode}\",\n \"target_pubkeys\": " )?; serde_json::to_writer(&mut *output, &pubkeys.pubkeys())?; - write!(output, ",\n \"agent_communities\": ")?; - serde_json::to_writer(&mut *output, &pubkeys.agents)?; write!(output, ",\n \"files\": [")?; let (mut selected, mut kept, mut deleted_versions) = (0usize, 0usize, 0usize); let mut after = String::new(); @@ -66,7 +64,6 @@ pub(super) async fn execute( serde_json::to_writer(&mut *output, &version)?; first_version = false; if delete && !shared { - require_current_targets(db, pubkeys).await?; media.delete(&version).await?; handled += 1; } @@ -74,7 +71,6 @@ pub(super) async fn execute( } } let removed = if delete { - require_current_targets(db, pubkeys).await?; db.remove(pubkeys, &hash).await? } else { 0 @@ -84,7 +80,6 @@ pub(super) async fn execute( after = hash; } } - require_current_targets(db, pubkeys).await?; let summary = json!({"mode": mode, "selected_files": selected, "kept_files": kept, "deleted_versions": deleted_versions, "account_erasure_complete": false}); diff --git a/crates/buzz-deletion/src/user/worker_postgres_tests/media_retry.rs b/crates/buzz-deletion/src/user/worker_postgres_tests/media_retry.rs index 7469ac6d472..f42027fc902 100644 --- a/crates/buzz-deletion/src/user/worker_postgres_tests/media_retry.rs +++ b/crates/buzz-deletion/src/user/worker_postgres_tests/media_retry.rs @@ -131,6 +131,16 @@ async fn workflow_media_retry_refetches_agent_ownership_before_deleting() { } sqlx::query("INSERT INTO users(community_id, pubkey, agent_owner_pubkey) VALUES ($1, decode($2, 'hex'), decode($3, 'hex'))") .bind(Uuid::from_u128(11)).bind(&agent).bind(&human).execute(&fixture.pool).await.unwrap(); + // Retain ownership elsewhere on retry: flattening agent keys would still + // select the upload in community 11 after that community changes owner. + sqlx::query("INSERT INTO users(community_id, pubkey) VALUES ($1, decode($2, 'hex'))") + .bind(Uuid::from_u128(12)) + .bind(&human) + .execute(&fixture.pool) + .await + .unwrap(); + sqlx::query("INSERT INTO users(community_id, pubkey, agent_owner_pubkey) VALUES ($1, decode($2, 'hex'), decode($3, 'hex'))") + .bind(Uuid::from_u128(12)).bind(&agent).bind(&human).execute(&fixture.pool).await.unwrap(); sqlx::query("UPDATE media_uploaders SET pubkey = decode($1, 'hex') WHERE sha256 = $2") .bind(&agent) .bind("a".repeat(64)) @@ -151,10 +161,11 @@ async fn workflow_media_retry_refetches_agent_ownership_before_deleting() { assert_eq!(failed.stage_history[1].status, "failed"); assert!(!fixture.deleted.load(Ordering::SeqCst)); sqlx::query( - "UPDATE users SET agent_owner_pubkey = decode($1, 'hex') WHERE pubkey = decode($2, 'hex')", + "UPDATE users SET agent_owner_pubkey = decode($1, 'hex') WHERE pubkey = decode($2, 'hex') AND community_id = $3", ) .bind(&bob) .bind(&agent) + .bind(Uuid::from_u128(11)) .execute(&fixture.pool) .await .unwrap(); diff --git a/docs/operator-user-deletion-executor.md b/docs/operator-user-deletion-executor.md index 7b377c6b089..77ec95808df 100644 --- a/docs/operator-user-deletion-executor.md +++ b/docs/operator-user-deletion-executor.md @@ -260,13 +260,14 @@ profiles. A missing profile grants no agent cleanup authority. Every invocation and retry discovers again. Content, account, and profile handlers use the utility inside their existing batch transactions with row locks when rechecking ownership. Profile cleanup compares against the identities -that remain after its own committed batches. Media rechecks before each storage -mutation, uploader-row removal, and successful completion. These checks do not -replace the requirement to stop writers, or make PostgreSQL and storage atomic. - -Discovery rejects more than 10,000 ownership pairs or distinct target keys -(including the human), rather than returning a partial set. Individual handlers -retain their additional operation and output limits. Ownership profiles must +that remain after its own committed batches. Media discovers once per invocation +and uses that snapshot through inventory and deletion. Writers must remain +stopped throughout the operation. + +Discovery preserves each caller's existing limits: media, content and profile +allow 10,000 distinct identities including the human; account discovery allows +10,000 agents. Account scope capture retains its existing total-key bound. +Media retains every owned community for each selected agent. Ownership profiles must remain until all dependent cleanup completes; profile removal goes last. ## Media discovery and remaining limits @@ -286,8 +287,8 @@ history filter: relay membership rows can be deleted on departure. Sharing checks span all communities for the selected hashes. Any outside uploader in either database source or an upload-record version protects the file, including the same agent's uploads in an unowned community. No per-file -owner-list query is made. The report includes `agent_communities` alongside the -deduplicated `target_pubkeys`; the latter alone is not deletion authority. +owner-list query is made. The report retains its deduplicated `target_pubkeys`; +community ownership is used internally for every media decision. Storage discovery scans `_uploads/` for target claims, then reads candidate claims in a second `_uploads/` listing to protect outside claims encountered @@ -308,11 +309,6 @@ pages and database/HTTP clients allocate separately. It replaces the former 1 GiB disk inventory, so large jobs may reach capacity sooner. Exhausting a limit aborts before mutation, with a capacity error; no partial inventory is used for deletion. Retries rebuild discovery from PostgreSQL and storage. -The handler re-fetches the full ownership set before each storage delete and -uploader-row removal, and before returning success. Any change aborts for a -fresh retry. These checks do not serialize a remote storage write with ownership -updates: the existing requirement to stop all writers during deletion still -applies. Unversioned exclusive objects also abort. Upload claim objects are deleted last, and the target's database uploader rows are removed only after that file's storage processing succeeds, so a partial failure can be retried. From 43afcf1494420c11255da7202ab9bee3f91290d2 Mon Sep 17 00:00:00 2001 From: dessert <7d616e7e143e5d408159614dccff1371350a1c1bd36c8de838a45ece5aca0aca@buzz.block.builderlab.xyz> Date: Thu, 19 Nov 2026 14:52:50 -0500 Subject: [PATCH 5/5] docs(deletion): clarify discovery constraints Signed-off-by: dessert <7d616e7e143e5d408159614dccff1371350a1c1bd36c8de838a45ece5aca0aca@buzz.block.builderlab.xyz> --- crates/buzz-db/src/store/user_deletion/agent_ownership.rs | 3 +++ docs/operator-user-deletion-executor.md | 7 +++++++ 2 files changed, 10 insertions(+) diff --git a/crates/buzz-db/src/store/user_deletion/agent_ownership.rs b/crates/buzz-db/src/store/user_deletion/agent_ownership.rs index ef5d35c3826..d85a3b3812f 100644 --- a/crates/buzz-db/src/store/user_deletion/agent_ownership.rs +++ b/crates/buzz-db/src/store/user_deletion/agent_ownership.rs @@ -39,6 +39,9 @@ impl UserDeletionTargets { /// Missing profiles grant no agent authority, and agent ownership is not recursive. /// `lock` retains FOR SHARE locks until the caller ends its transaction; callers /// still own write admission and the offline/stopped-writer operating contract. +/// With `community: None` and `DiscoveryLimit::TargetKeys`, callers must pass +/// `lock: false`: this query groups profiles by agent, and PostgreSQL does not +/// allow FOR SHARE with GROUP BY. Use community-scoped discovery for row locking. pub(super) async fn discover( conn: &mut PgConnection, human: &str, diff --git a/docs/operator-user-deletion-executor.md b/docs/operator-user-deletion-executor.md index 77ec95808df..a65c7f672e4 100644 --- a/docs/operator-user-deletion-executor.md +++ b/docs/operator-user-deletion-executor.md @@ -270,6 +270,13 @@ allow 10,000 distinct identities including the human; account discovery allows Media retains every owned community for each selected agent. Ownership profiles must remain until all dependent cleanup completes; profile removal goes last. +Media has no separate cap on `(community_id, agent_pubkey)` pairs. One agent can +contribute a pair for every community where the human owns it, so the identity +limit does not bound the pair count. These pairs are retained in memory, including +the storage-matching hash set, and the full pair arrays are sent with each media +candidate-page query. They are outside the inventory budget described below; +memory use and query payload size grow with the number of owned agent profiles. + ## Media discovery and remaining limits Every invocation and retry fetches the human's current directly owned agents