Files
buzz/crates/buzz-admin/tests/postgres_user_inventory.rs
ravarora2 a8f55e637a Add real content cleanup for users and agents (#9363)
## Summary

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

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

### Reply preservation and live writes

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

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

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

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

### Included content

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

### Testing

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

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

### Scope and compatibility

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

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

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

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

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

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

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

Generated with Codex

---------

Signed-off-by: Ravneet Arora <rarora@squareup.com>
Co-authored-by: maincourse <37ce551b493d4a998caf030929c47bce0b6a0e43f1178b3a63c4151d7c16b76e@buzz.block.builderlab.xyz>
2026-11-17 10:17:45 -05:00

440 lines
16 KiB
Rust

//! Exercise inventory access, demo completion, and unfinished real workflows.
use nostr::ToBech32;
use serde_json::Value;
use sqlx::PgPool;
use tokio::process::Command;
use url::Url;
use uuid::Uuid;
fn admin_binary() -> std::ffi::OsString {
// Nextest relocates binaries when extracting an archive. Cargo's build-time
// path remains the fallback for local cargo test runs.
std::env::var_os("NEXTEST_BIN_EXE_buzz_admin")
.unwrap_or_else(|| env!("CARGO_BIN_EXE_buzz-admin").into())
}
#[tokio::test]
#[ignore = "requires Postgres"]
async fn cluster_global_inventory_cli_uses_only_existing_membership_tables() {
let database_url = std::env::var("BUZZ_TEST_DATABASE_URL")
.or_else(|_| std::env::var("DATABASE_URL"))
.unwrap();
let pool = PgPool::connect(&database_url).await.unwrap();
// All interpolated identifiers are this fixed prefix plus generated hex.
let name = format!("inventory_{}", Uuid::new_v4().simple());
let mut tx = pool.begin().await.unwrap();
sqlx::raw_sql(sqlx::AssertSqlSafe(format!(
"CREATE SCHEMA {name}; SET LOCAL search_path TO {name}, public;"
)))
.execute(&mut *tx)
.await
.unwrap();
// These are existing deployed tables. No entity_deletion_* schema is needed.
sqlx::raw_sql(include_str!(
"../../../schema/tables/public/communities.sql"
))
.execute(&mut *tx)
.await
.unwrap();
sqlx::raw_sql(include_str!(
"../../../schema/tables/public/relay_members.sql"
))
.execute(&mut *tx)
.await
.unwrap();
for schema in [
include_str!("../../../schema/tables/public/channels.sql"),
include_str!("../../../schema/tables/public/channel_members.sql"),
] {
sqlx::raw_sql(schema).execute(&mut *tx).await.unwrap();
}
let pubkey = "5e4083a7a793d02575876eaf47932b4835999f5af2653d26250a909b450da7c9";
let community = Uuid::new_v4();
sqlx::query("INSERT INTO communities (id, host) VALUES ($1, 'inventory-cli.example')")
.bind(community)
.execute(&mut *tx)
.await
.unwrap();
sqlx::query("INSERT INTO relay_members (community_id, pubkey, role) VALUES ($1, $2, 'member')")
.bind(community)
.bind(pubkey)
.execute(&mut *tx)
.await
.unwrap();
let participant_community = Uuid::new_v4();
sqlx::query("INSERT INTO communities (id, host) VALUES ($1, 'channel-only-cli.example')")
.bind(participant_community)
.execute(&mut *tx)
.await
.unwrap();
for target in [community, participant_community] {
for _ in 0..2 {
let channel = Uuid::new_v4();
sqlx::query("INSERT INTO channels (community_id, id, name, created_by) VALUES ($1, $2, 'inventory-test-' || $2::uuid::text, decode($3, 'hex'))")
.bind(target).bind(channel).bind(pubkey).execute(&mut *tx).await.unwrap();
sqlx::query("INSERT INTO channel_members (community_id, channel_id, pubkey) VALUES ($1, $2, decode($3, 'hex'))")
.bind(target).bind(channel).bind(pubkey).execute(&mut *tx).await.unwrap();
}
}
sqlx::raw_sql(sqlx::AssertSqlSafe(format!(
"CREATE ROLE {name} LOGIN PASSWORD 'inventory-local-fixture'; \
GRANT USAGE ON SCHEMA {name} TO {name}; \
GRANT SELECT ON ALL TABLES IN SCHEMA {name} TO {name};"
)))
.execute(&mut *tx)
.await
.unwrap();
tx.commit().await.unwrap();
let mut reader_url = Url::parse(&database_url).unwrap();
reader_url.set_username(&name).unwrap();
reader_url
.set_password(Some("inventory-local-fixture"))
.unwrap();
reader_url
.query_pairs_mut()
.append_pair("options", &format!("-csearch_path={name}"));
let npub = nostr::PublicKey::parse(pubkey)
.unwrap()
.to_bech32()
.unwrap();
let mut outputs = Vec::new();
for input in [pubkey, npub.as_str()] {
outputs.push(
tokio::time::timeout(
std::time::Duration::from_secs(15),
Command::new(admin_binary())
.args(["user-deletions", "inventory", "--pubkey", input])
.env("DATABASE_URL", reader_url.as_str())
.kill_on_drop(true)
.output(),
)
.await
.unwrap()
.unwrap(),
);
}
let demo = Command::new(admin_binary())
.args(["user-deletions", "inventory"])
.env("DATABASE_URL", reader_url.as_str())
.kill_on_drop(true)
.output()
.await
.unwrap();
// Clean cluster-wide role state before asserting the subprocess results.
sqlx::raw_sql(sqlx::AssertSqlSafe(format!(
"DROP SCHEMA {name} CASCADE; DROP OWNED BY {name}; DROP ROLE {name};"
)))
.execute(&pool)
.await
.unwrap();
let inventories: Vec<Value> = outputs
.into_iter()
.map(|output| {
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
serde_json::from_slice(&output.stdout).unwrap()
})
.collect();
assert_eq!(inventories[0], inventories[1]);
assert!(
demo.status.success(),
"{}",
String::from_utf8_lossy(&demo.stderr)
);
let demo: Value = serde_json::from_slice(&demo.stdout).unwrap();
assert_eq!(
demo,
serde_json::json!({
"communities": [
{"community_id": "00000000-0000-0000-0000-00000000000b", "label": "demo:community-b", "relationship": "participant"},
{"community_id": "00000000-0000-0000-0000-00000000000c", "label": "demo:community-c", "relationship": "former_participant"}
]
})
);
let inventory = &inventories[0];
assert_eq!(inventory.as_object().unwrap().len(), 1);
assert_eq!(demo.as_object().unwrap().len(), 1);
let communities = inventory["communities"].as_array().unwrap();
assert_eq!(communities.len(), 2);
let explicit_member = communities
.iter()
.find(|item| item["community_id"] == community.to_string())
.unwrap();
assert_eq!(explicit_member["label"], "inventory-cli.example");
assert_eq!(explicit_member["relationship"], "participant");
let participant = communities
.iter()
.find(|item| item["community_id"] == participant_community.to_string())
.unwrap();
assert_eq!(participant["label"], "channel-only-cli.example");
assert_eq!(participant["relationship"], "participant");
for output in [&demo, inventory] {
for row in output["communities"].as_array().unwrap() {
assert_eq!(row.as_object().unwrap().len(), 3);
}
}
}
#[test]
fn invalid_inventory_key_fails_before_database_connection() {
let output = std::process::Command::new(admin_binary())
.args(["user-deletions", "inventory", "--pubkey", "invalid-npub"])
.env_remove("DATABASE_URL")
.output()
.unwrap();
assert_eq!(output.status.code(), Some(2));
assert!(output.stdout.is_empty());
assert!(String::from_utf8_lossy(&output.stderr)
.contains("expected a 64-character hex public key or an npub"));
}
async fn workflow_cli(url: &str, args: &[&str], success: bool) -> Value {
let output = tokio::time::timeout(
std::time::Duration::from_secs(20),
Command::new(admin_binary())
.arg("user-deletions")
.args(args)
.env("DATABASE_URL", url)
.env("BUZZ_DB_POOL_SIZE", "1")
.kill_on_drop(true)
.output(),
)
.await
.unwrap()
.unwrap();
assert_eq!(
output.status.success(),
success,
"{args:?}: {}",
String::from_utf8_lossy(&output.stderr)
);
if success {
serde_json::from_slice(&output.stdout).unwrap()
} else {
serde_json::json!({
"exit_code": output.status.code(),
"stderr": String::from_utf8_lossy(&output.stderr),
})
}
}
async fn assert_real_workflow_stops_at_gate(url: &str, id: &str) -> Value {
let approved = workflow_cli(url, &["inspect", id], true).await;
let refused = workflow_cli(url, &["run", id, "--next-step"], false).await;
assert_eq!(refused["exit_code"], 5);
assert!(refused["stderr"]
.as_str()
.unwrap()
.contains("real workflow execution requires --delete"));
assert_eq!(workflow_cli(url, &["inspect", id], true).await, approved);
let mut first_stage = None;
for _ in 0..2 {
let refused = workflow_cli(url, &["run", id, "--delete", "--next-step"], false).await;
assert_eq!(refused["exit_code"], 5);
assert!(refused["stderr"]
.as_str()
.unwrap()
.contains("real handler gate_user is not implemented"));
let inspected = workflow_cli(url, &["inspect", id], true).await;
assert_ne!(inspected["status"], "completed");
assert!(inspected["completed_at"].is_null());
assert!(inspected["lease_owner"].is_null());
assert_eq!(inspected["target"], approved["target"]);
assert_eq!(
inspected["inventory_manifest"],
approved["inventory_manifest"]
);
let stages = inspected["stage_history"].as_array().unwrap();
assert_eq!(stages.len(), 1);
assert_eq!(stages[0]["stage"], "gate_user");
assert_eq!(stages[0]["status"], "pending");
assert_eq!(stages[0]["is_current"], true);
assert_eq!(
stages[0]["metadata_json"]["inputs"]["target"],
approved["target"]
);
if let Some(first) = &first_stage {
assert_eq!(&stages[0]["id"], first);
} else {
first_stage = Some(stages[0]["id"].clone());
}
}
workflow_cli(url, &["inspect", id], true).await
}
#[tokio::test]
#[ignore = "requires Postgres"]
async fn inventory_submission_completes_demo_and_stops_unimplemented_real_workflow() {
let url = std::env::var("BUZZ_TEST_DATABASE_URL").unwrap();
let pool = PgPool::connect(&url).await.unwrap();
let key = "ab".repeat(32);
let npub = nostr::PublicKey::parse(&key).unwrap().to_bech32().unwrap();
let community = Uuid::new_v4();
let channel = Uuid::new_v4();
sqlx::query("INSERT INTO communities (id, host) VALUES ($1, 'workflow-fixture.example')")
.bind(community)
.execute(&pool)
.await
.unwrap();
sqlx::query("INSERT INTO channels (community_id, id, name, created_by) VALUES ($1, $2, 'fixture', decode($3, 'hex'))")
.bind(community).bind(channel).bind(&key).execute(&pool).await.unwrap();
sqlx::query("INSERT INTO channel_members (community_id, channel_id, pubkey) VALUES ($1, $2, decode($3, 'hex'))")
.bind(community).bind(channel).bind(&key).execute(&pool).await.unwrap();
for subject in ["demo", npub.as_str()] {
let preview = workflow_cli(&url, &["inventory", "--pubkey", subject], true).await;
let saved = workflow_cli(
&url,
&[
"submit",
"--pubkey",
subject,
"--requested-by",
"operator-a",
],
true,
)
.await;
assert_eq!(saved["inventory_manifest"], preview);
assert_eq!(
saved["target"],
if subject == "demo" {
"demo:default"
} else {
&key
}
);
assert_eq!(saved["status"], "inventoried");
let id = saved["id"].as_str().unwrap();
workflow_cli(&url, &["run", id], false).await;
workflow_cli(
&url,
&[
"approve",
id,
"--approved-by",
"operator-b",
"--inventory-digest",
"wrong",
],
false,
)
.await;
let approved = workflow_cli(
&url,
&[
"approve",
id,
"--approved-by",
"operator-b",
"--inventory-digest",
saved["inventory_digest"].as_str().unwrap(),
],
true,
)
.await;
assert!(approved["stage_history"].as_array().unwrap().is_empty());
let outcome = if subject == "demo" {
let stepped = workflow_cli(&url, &["run", id, "--next-step"], true).await;
assert_eq!(stepped["stage_history"][0]["status"], "completed");
let first_id = stepped["stage_history"][0]["id"].clone();
let done = workflow_cli(&url, &["run", id], true).await;
assert_eq!(done["status"], "completed");
assert_eq!(done["stage_history"][0]["id"], first_id);
let stages = done["stage_history"].as_array().unwrap();
assert_eq!(stages.len(), 6);
assert!(stages
.iter()
.all(|s| s["status"] == "completed" && s["is_current"] == false));
done
} else {
assert_real_workflow_stops_at_gate(&url, id).await
};
let inspected = workflow_cli(&url, &["inspect", id], true).await;
assert_eq!(inspected, outcome);
// Hex and npub converge on the same saved request without rediscovery.
let repeat = workflow_cli(
&url,
&[
"submit",
"--pubkey",
if subject == "demo" { "demo" } else { &key },
"--requested-by",
"operator-a",
],
true,
)
.await;
for (field, value) in repeat.as_object().unwrap() {
assert_eq!(value, &outcome[field]);
}
workflow_cli(
&url,
&[
"submit",
"--pubkey",
subject,
"--requested-by",
"someone-else",
],
false,
)
.await;
}
// Demo completion and real-handler refusal both preserve membership data.
let count: i64 = sqlx::query_scalar("SELECT count(*) FROM channel_members WHERE community_id = $1 AND pubkey = decode($2, 'hex')")
.bind(community).bind(&key).fetch_one(&pool).await.unwrap();
assert_eq!(count, 1);
}
#[tokio::test]
#[ignore = "requires Postgres"]
async fn inventory_approval_preserves_saved_account_identity_without_dummy_execution() {
let url = std::env::var("BUZZ_TEST_DATABASE_URL").unwrap();
let pool = PgPool::connect(&url).await.unwrap();
let saved = workflow_cli(
&url,
&[
"submit",
"--target",
"demo:resolved-account",
"--requested-by",
"operator-a",
],
true,
)
.await;
let id = saved["id"].as_str().unwrap();
// Model the output of a future account resolver. This is not CLI support
// for resolving account IDs: the inventory is already saved and complete.
let account = "builderlab:account-123";
sqlx::query("UPDATE entity_deletion_requests SET target = $2 WHERE id = $1")
.bind(Uuid::parse_str(id).unwrap())
.bind(account)
.execute(&pool)
.await
.unwrap();
workflow_cli(
&url,
&[
"approve",
id,
"--approved-by",
"operator-b",
"--inventory-digest",
saved["inventory_digest"].as_str().unwrap(),
],
true,
)
.await;
let stopped = assert_real_workflow_stops_at_gate(&url, id).await;
assert_eq!(stopped["target"], account);
assert_eq!(stopped["inventory_manifest"], saved["inventory_manifest"]);
}