Skip to content
8 changes: 4 additions & 4 deletions crates/buzz-db/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,10 +97,10 @@ pub use store::{
admin_moderation, allowlist, api_token, archived_identities, artifact, artifact_sync, channel,
channel_members, community, community_auth, deletion, dm, entity_deletion, event, feed,
git_repo, leader_lock, media, membership_snapshot, moderation, nip_fi_binding,
operator_listener, partition, personal_read, pins, product_feedback, push, reaction,
read_state, relay_admin_actions, relay_invite, relay_members, relay_operators, reminder,
replaceable, search_backfill, search_outbox, storage_accounting, thread, thread_window, user,
user_deletion, user_deletion_fences, workflow,
operator_listener, operator_listener_threads, partition, personal_read, pins, product_feedback,
push, reaction, read_state, relay_admin_actions, relay_invite, relay_members, relay_operators,
reminder, replaceable, search_backfill, search_outbox, storage_accounting, thread,
thread_window, user, user_deletion, user_deletion_fences, workflow,
};

pub use allowlist::AllowlistEntry;
Expand Down
18 changes: 15 additions & 3 deletions crates/buzz-db/src/runtime/migration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1057,7 +1057,12 @@ mod postgres_tests {
let mut migrations: Vec<_> = MIGRATOR.iter().collect();
migrations.sort_by_key(|migration| migration.version);

assert_eq!(migrations.len(), 111);
assert_eq!(migrations.len(), 112);
assert_eq!(migrations[111].version, 112);
assert!(migrations[111]
.sql
.as_str()
.contains("CREATE TABLE operator_listener_threads"));
assert_eq!(migrations[110].version, 111);
assert!(migrations[110]
.sql
Expand Down Expand Up @@ -1750,6 +1755,7 @@ mod postgres_tests {
"media_publications",
"search_outbox",
"search_backfill",
"operator_listener_threads",
];
for table in crate::deletion::EXPECTED_SCOPED_TABLES
.iter()
Expand Down Expand Up @@ -3547,6 +3553,8 @@ mod postgres_tests {
.expect("apply migrations for schema parity");

for table in [
"operator_listener_threads",
"operator_listener_outbox",
"community_serving_write_leases",
"media_uploaders",
"audit_log",
Expand Down Expand Up @@ -4547,7 +4555,9 @@ mod postgres_tests {
.expect_err("deletion refuses a catalog missing later tenant tables")
.to_string();
assert!(
drift.contains("(missing=search_backfill,search_outbox, unknown=)"),
drift.contains(
"(missing=operator_listener_threads,search_backfill,search_outbox, unknown=)"
),
"deletion must accept the pre-retirement fences: {drift}"
);
run_migrations(&pool).await.expect("apply all migrations");
Expand Down Expand Up @@ -4636,7 +4646,9 @@ mod postgres_tests {
.expect_err("deletion refuses a catalog missing later tenant tables")
.to_string();
assert!(
drift.contains("(missing=search_backfill,search_outbox, unknown=)"),
drift.contains(
"(missing=operator_listener_threads,search_backfill,search_outbox, unknown=)"
),
"deletion must accept the catalog before the drop: {drift}"
);
run_migrations(&pool).await.expect("apply all migrations");
Expand Down
19 changes: 19 additions & 0 deletions crates/buzz-db/src/store/deletion.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ pub const RELAY_ADMIN_TABLES: &[(&str, &str)] = &[
/// [`PENDING_SCOPED_TABLES`] and [`RETIRING_SCOPED_TABLES`] are accepted present
/// or absent and are not listed here.
pub const EXPECTED_SCOPED_TABLES: &[&str] = &[
"operator_listener_threads",
"nip_fi_profile_heads",
"api_tokens",
"archived_identities",
Expand Down Expand Up @@ -205,6 +206,7 @@ const EXCLUDED_SCOPED_TABLES: &[&str] = &[
/// key needs the order, but the list must stay complete
/// ([`EXPECTED_SCOPED_TABLES`] gates it).
pub const PURGE_SCOPED_TABLES: &[&str] = &[
"operator_listener_threads",
"nip_fi_profile_heads",
"personal_read_frontiers",
"personal_read_accounts",
Expand Down Expand Up @@ -10116,6 +10118,13 @@ DROP FUNCTION protect_community_deletion_manifest_keys();
.as_uuid()
.to_owned();
seed_relay_admin_rows(&db, bystander).await;
// Thread watches are tenant-owned and must be purged without touching
// the bystander's same listener/agent/channel/root tuple.
for tenant in [community, bystander] {
sqlx::query("INSERT INTO operator_listener_threads (community_id,listener_pubkey,target_pubkey,channel_id,root_event_id,expires_at) VALUES ($1,decode(repeat('ab',32),'hex'),decode(repeat('cd',32),'hex'),'00000000-0000-0000-0000-000000000001',decode(repeat('ef',32),'hex'),now()+interval '1 day')")
.bind(tenant).execute(&db.pool).await.unwrap();
}

// Operator workflow history is retained even when its provenance
// community is purged; it is not a tenant-owned serving table.
let entity = db
Expand Down Expand Up @@ -10198,6 +10207,15 @@ DROP FUNCTION protect_community_deletion_manifest_keys();
.await
.expect("bindings");
let deleted = store.purge_postgres(&token).await.expect("purge postgres");
let retained_watches: Vec<Uuid> = sqlx::query_scalar(
"SELECT community_id FROM operator_listener_threads WHERE community_id IN ($1,$2)",
)
.bind(community)
.bind(bystander)
.fetch_all(&db.pool)
.await
.unwrap();
assert_eq!(retained_watches, vec![bystander]);

let upgrade = db
.community_auth_policy_status(upgrade_id, "operator")
Expand Down Expand Up @@ -10320,6 +10338,7 @@ DROP FUNCTION protect_community_deletion_manifest_keys();
.await
.expect("bindings");
store.purge_postgres(&token).await.expect("purge postgres");

store
.mark_cache_purged(&token, serde_json::json!({"keys": 0}))
.await
Expand Down
1 change: 1 addition & 0 deletions crates/buzz-db/src/store/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ pub mod membership_snapshot;
pub mod moderation;
/// Deployment-global operator-listener mention registrations and delivery queues.
pub mod operator_listener;
pub mod operator_listener_threads;
/// Monthly table partition management.
pub mod partition;
/// Private signer-owned accessory read progress.
Expand Down
29 changes: 26 additions & 3 deletions crates/buzz-db/src/store/operator_listener.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ pub struct ClaimedDelivery {
pub event_id: Vec<u8>,
/// Mentioning event kind.
pub event_kind: i32,
/// Present only for a delivery authorized by an explicit thread watch.
pub thread_root_event_id: Option<Vec<u8>>,
/// Author-controlled event timestamp.
pub event_created_at: DateTime<Utc>,
/// Attempt number, starting at one.
Expand Down Expand Up @@ -101,7 +103,7 @@ pub(crate) async fn enqueue_mentions_in_transaction(
}
let targets = event_targets(event);
if targets.is_empty() {
return Ok(0);
return super::operator_listener_threads::enqueue_thread_replies(tx, event).await;
}
let event_created_at = DateTime::from_timestamp(event.created_at.as_secs() as i64, 0).ok_or(
crate::error::DbError::InvalidTimestamp(event.created_at.as_secs() as i64),
Expand All @@ -127,7 +129,9 @@ pub(crate) async fn enqueue_mentions_in_transaction(
}
separated.push_unseparated(") ON CONFLICT DO NOTHING");

Ok(query.build().execute(tx.conn()).await?.rows_affected())
let mentions = query.build().execute(tx.conn()).await?.rows_affected();
let replies = super::operator_listener_threads::enqueue_thread_replies(tx, event).await?;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 this runs the thread-watch INSERT ... SELECT for every top-level message too, inside the event's write transaction, even though only replies can match. could we gate it on the event actually being a reply? passing in the root that insert_event_with_thread_metadata_tx already resolved would skip the call for top-level messages and also remove the thread_metadata lookup inside enqueue_thread_replies. same applies to the early return at line 106.

Ok(mentions + replies)
}

/// Register target pubkeys for one deployment-global listener.
Expand Down Expand Up @@ -229,7 +233,7 @@ pub async fn claim_deliveries(
JOIN communities community ON community.id = c.community_id \
WHERE o.id = c.id \
RETURNING o.id, o.claim_id, o.listener_pubkey, o.target_pubkey, o.community_id, \
community.host, o.event_id, o.event_kind, o.event_created_at, o.attempts",
community.host, o.event_id, o.event_kind, o.thread_root_event_id, o.event_created_at, o.attempts",
)
.bind(claim_id)
.bind(MAX_DELIVERY_ATTEMPTS)
Expand All @@ -250,6 +254,7 @@ pub async fn claim_deliveries(
community_host: row.try_get("host")?,
event_id: row.try_get("event_id")?,
event_kind: row.try_get("event_kind")?,
thread_root_event_id: row.try_get("thread_root_event_id")?,
event_created_at: row.try_get("event_created_at")?,
attempt: row.try_get("attempts")?,
})
Expand Down Expand Up @@ -298,6 +303,22 @@ pub async fn load_deliverable_event(
JOIN events e ON e.community_id = $3 AND e.created_at = $4 AND e.id = $5 \
WHERE r.listener_pubkey = $1 AND r.target_pubkey = $2 \
AND e.deleted_at IS NULL \
AND ($9::bytea IS NULL OR EXISTS ( \
SELECT 1 FROM operator_listener_threads w \
JOIN channels wc ON wc.community_id = w.community_id AND wc.id = w.channel_id \
AND wc.deleted_at IS NULL AND wc.archived_at IS NULL \
JOIN users wu ON wu.community_id = w.community_id AND wu.pubkey = w.target_pubkey AND wu.deactivated_at IS NULL \
JOIN channel_members wm ON wm.community_id = w.community_id AND wm.channel_id = w.channel_id \
AND wm.pubkey = w.target_pubkey AND wm.removed_at IS NULL \
JOIN events root ON root.community_id = w.community_id AND root.channel_id = w.channel_id \
AND root.id = w.root_event_id AND root.deleted_at IS NULL \
JOIN thread_metadata tm ON tm.community_id = w.community_id AND tm.channel_id = w.channel_id \
AND tm.event_id = e.id AND tm.event_created_at = e.created_at \
AND tm.parent_event_id IS NOT NULL \
AND COALESCE(tm.root_event_id, tm.parent_event_id) = w.root_event_id \
WHERE w.community_id = $3 AND w.listener_pubkey = $1 AND w.target_pubkey = $2 \
AND w.root_event_id = $9 AND w.channel_id = e.channel_id AND w.expires_at > now() \
AND r.created_at >= now() - interval '30 days')) \

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 nit: this hard-codes interval '30 days' where operator_listener_threads.rs binds PUBKEY_RETENTION. binding the constant here too keeps them from drifting.

AND (NOT $8 OR EXISTS ( \
SELECT 1 FROM pubkey_allowlist a \
WHERE a.community_id = $3 AND a.pubkey = $2)) \
Expand Down Expand Up @@ -327,6 +348,7 @@ pub async fn load_deliverable_event(
.bind(admission.require_membership)
.bind(admission.allow_owner_membership)
.bind(admission.require_allowlist)
.bind(&delivery.thread_root_event_id)
.fetch_optional(&mut *connection)
.await?;
match row {
Expand Down Expand Up @@ -1237,6 +1259,7 @@ mod postgres_tests {
community_host: String::new(),
event_id: event.id.as_bytes().to_vec(),
event_kind: 9,
thread_root_event_id: None,
event_created_at: DateTime::from_timestamp(
event.created_at.as_secs() as i64,
0,
Expand Down
Loading
Loading