From c01d3292a13f8d69ac85315b353eefb10c117e70 Mon Sep 17 00:00:00 2001 From: Ian Oberst Date: Tue, 17 Nov 2026 13:51:18 -0800 Subject: [PATCH] fix(db): hard-delete superseded relay-signed lists (#9586) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Why The relay republishes its own lists in full on every change: - the NIP-43 membership list (kind 13534) - the NIP-IA archived list (13535) - NIP-29 group state (39000 metadata, 39001 admins, 39002 members) Each write soft-deletes the previous head. No reader returns a soft-deleted row, so each retired copy is dead weight in `events` and its indexes. On the deployments we measured, these retired copies are about 40–65% of monthly `events` growth. The NIP-33 path already hard-deletes superseded NIP-RS read state and mesh status in the replacing transaction. This PR applies the same rule to the relay-owned lists. ## What When a write supersedes a head of kind 13534, 13535, 39000, 39001, or 39002, it deletes the old head instead of soft-deleting it. The delete runs in the same transaction, under the same scope and lock as before. The change applies on the 3 paths the relay uses to write these kinds: - `replace_addressable_event_under_lock` (13535, 39000, 39001, including `buzz-admin` writes through `replace_addressable_event`). It gates on the new `hard_deletes_superseded(kind)`. Other kinds on this path (0, 3, 10002, …) keep the soft delete. - `LockedMemberSnapshot::replace_member_event` (39002). - `write_nip43_membership_snapshot` (13534). All 3 paths build their head read and supersede statement with one function, `replacement_sql(in_channel, hard_delete)`, keyed by `hard_deletes_superseded(kind)`. Kind 13535 is now relay-only: ingest rejects a client-submitted 13535 with `restricted: relay-only kind`, as it already does for 13534. NIP-IA defines 13535 as relay-signed, and every relay, desktop, CLI, and mobile reader filters on the relay's pubkey. No client in this repository publishes it. The 39000–39002 paths already use `superseded_with_mentions_sql!`, so the old head's mention rows are deleted with it, as before. The gate checks the kind, not the signer, and every supersede is scoped to the event's own pubkey. A client-signed 39000–39002 is routed to the NIP-33 path, which keeps the soft delete. Channel deletion (`soft_delete_discovery_events`) retires the live heads without a replacement and still soft-deletes them. This PR has no migration and no schema change. ## Why this is safe - **Readers:** relay reads of these kinds filter on `deleted_at IS NULL`, so a retired head was already invisible. One reader includes soft-deleted rows: the admin event preview (`get_event_preview`). It will now report a superseded roster id as absent instead of deleted. A moderation report against an old version of a channel's metadata (for example, a name it had before a rename) will show no target content. An operator can no longer look up an old roster or membership list by id to audit past membership. `docs/admin/README.md` now documents this for `GET /api/admin/v1/events/{id}`. - **Operator repair:** when `buzz-admin`'s group-state reconcile overwrites a 39000–39002 head, the old row is gone, so an operator can no longer restore it with `UPDATE … SET deleted_at = NULL`. The relay rebuilds these lists from `channels` and `channel_members`, so no source data is lost. - **Replays:** while the coordinate has a live head, a replay of a deleted head's id is still rejected, because its `created_at` does not beat the live head's. With no live head (after channel deletion, for example), the deleted row no longer makes the replay a duplicate. Only the relay can submit these events: ingest requires the event's signer to be the authenticated pubkey, 13534 is relay-only, and the relay's writers sign a new event on every attempt. The existing tests for soft-deleted replays seed their own rows and do not change. - **13534 id uniqueness:** the writer still takes `max(created_at)` over every stored list. The live head is always the newest, so the next list's `created_at` still moves past every earlier one. - **13535 strict stamps (NIP-IA, #9476):** each new archived list is stamped past the live head, which the writer reads behind the replacement lock. It never reads retired rows, so deleting them does not change the next `created_at`. - **Database objects:** no foreign key references `events`, and none of these kinds is a push kind. The DELETE runs in the same admitted community write transaction as the old UPDATE. The only trigger left on `events` is the BEFORE INSERT kind 39002 roster guard (`guard_channel_roster_snapshot`), and a DELETE does not fire it. - **Rolling deploy (docs/database.md Rule 7):** old pods keep soft-deleting and new pods delete. Both leave exactly one live head per coordinate, under the same locks. ## Follow-up Rows that are already soft-deleted stay. Rule 3 does not allow a migration to delete them. A separate PR will add a `scripts/maintenance/` repair script: bounded batches, the community-deletion lock, and a validation query. An operator runs it after this change is fully rolled out. Not in this PR: the relay-signed NIP-DV DM visibility snapshot (kind 30622, `publish_dm_visibility_snapshot`) is written on the NIP-33 path and still soft-deletes its superseded heads. We will measure its share of `events` growth before we change it. ## QA focus - **Each roster write keeps exactly one stored row.** Create a channel, then add and remove members, change roles, and edit the metadata. For each of 39000, 39001, and 39002, the channel must have exactly one `events` row (live), not one live row plus retired ones. Do the same for 13534 (relay membership add, remove, and role change) and 13535 (`agents archive` and unarchive). - **Other kinds still soft-delete.** Replace a kind 0 profile or kind 3 contact list. The old row must stay, with `deleted_at` set. - **Mention rows.** After a 39002 or 13535 replacement, `event_mentions` has no rows for the deleted head's id. - **Admin event preview.** Opening the id of a replaced roster now shows the event as absent instead of deleted. Check that this is acceptable in the admin UI, including a report filed against a channel's metadata before a rename. - **13535 `since` cache.** Archive and unarchive several times, including at the same time. Each new list has a `created_at` later than the one before. A mobile client that asks `since` its list's `created_at` + 1 gets the newer list. - **Client 13535 is rejected.** Publishing a kind 13535 signed by a user key returns `restricted: relay-only kind`. Archive and unarchive (kinds 9035 and 9036) still work, and the relay still publishes its own 13535. - **Channel deletion.** Deleting a channel still soft-deletes its live 39000–39002 heads. This path is unchanged. - **Mixed-version rollout.** With an old and a new relay on one database, each coordinate keeps exactly one live head. Rows that old pods soft-deleted stay until the follow-up script runs. - **Existing soft-deleted rows are not touched.** The disk-space gain shows only in growth after deploy. The follow-up script cleans up the backlog. ## Tests - `only_relay_owned_lists_hard_delete_their_superseded_heads`: checks the kind set, including the neighbours 13533, 13536, 38999, and 39003, and negative kinds. - `superseded_heads_drop_their_mention_rows` (Postgres) now expects the old head to be gone for the 39002 member snapshot, 13535 (global), and 39000 (in a channel). A kind 3 contact list on the same addressable path is the control: it must stay soft-deleted. - `replacement_channel_predicate_is_an_index_condition` (Postgres) now builds its statements with `replacement_sql`, the same function production uses, for all 4 scope and retire-mode combinations. Before, it checked hand-copied SQL. It checks that each `DELETE` seeks by `channel_id` on every populated partition, as the `UPDATE` does. - The 39002 and 13534 writers take their statements from `replacement_sql` and `hard_deletes_superseded`, so the index-condition test covers each statement production runs. - `nip_ia_archived_list_is_relay_only` (buzz-core): 13535 is relay-only, and the 9035 and 9036 requests are not. - `test_client_submitted_nip_ia_archive_snapshots_are_rejected` (buzz-test-client e2e, against a running relay): a client-signed 13535 is rejected with `restricted: relay-only kind` over both WebSocket and HTTP. It shares a helper with the existing 13534 test. Against a relay built without the 13535 gate, it fails at the WebSocket assertion. The Relay E2E step in `.github/workflows/_ci-relay.yml` now selects it, next to the 13534 test. - `late_owner_link_closes_ownerless_agent_sockets_on_owner_revoke` (buzz-relay, Postgres) copies selected tables into a private schema. The 13534 writer's supersede now also deletes the old list's `event_mentions` rows, so the fixture copies `event_mentions` too. - `every_membership_write_commits_its_list` (Postgres): after each membership writer runs, the community stores exactly one kind 13534 row. - `concurrent_archival_publishers_stamp_strictly_increasing_snapshots` (buzz-relay, Postgres, from #9476) counted the 16 stored kind 13535 rows, superseded ones included. It now pins the head an hour ahead and asserts that the coordinate stores exactly one row, at the pinned `created_at` + 16 s. That holds only if each of the 16 publishers stored exactly one snapshot, one second past the head it replaced. A same-second replacement leaves the row short of + 16 s, and a publisher that runs out of attempts still fails its `expect`. - `a_publisher_that_read_before_an_edit_cannot_replace_it` (buzz-relay, Postgres) counted retired kind 39000 rows to prove that each publisher stores a new second. It now asserts that the coordinate stores exactly one row, at the pinned `created_at` + 2 s. The mutation it guards against (taking the live `created_at` before the lock) leaves the head at + 1 s, so the test still catches it. Commands run: - `cargo clippy -p buzz-core -p buzz-db -p buzz-relay --all-targets -- -D warnings` - `cargo test -p buzz-core --lib` - `cargo nextest run -p buzz-relay --lib` - `cargo test -p buzz-test-client --test e2e_relay -- --ignored` for the 13534 and 13535 rejection tests, against a local relay built from this branch - `cargo test -p buzz-db --lib` - `cargo test -p buzz-db --test observability_source` - `scripts/postgres-test-run.sh -p buzz-db -p buzz-relay --lib --tests` (the CI PostgreSQL lane, run locally) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: Ian Oberst Co-authored-by: Ian Oberst Co-authored-by: Claude Opus 5.5 --- .github/workflows/_ci-relay.yml | 1 + crates/buzz-core/src/kind.rs | 8 + crates/buzz-db/src/lib.rs | 10 +- crates/buzz-db/src/store/channel_members.rs | 33 ++-- crates/buzz-db/src/store/relay_members.rs | 36 ++-- crates/buzz-db/src/store/replaceable.rs | 182 +++++++++++++----- crates/buzz-relay/src/api/bridge.rs | 6 +- .../handlers/group_state_postgres_tests.rs | 46 ++--- .../src/handlers/identity_archive.rs | 43 ++++- crates/buzz-test-client/tests/e2e_relay.rs | 37 +++- docs/admin/README.md | 6 +- 11 files changed, 289 insertions(+), 119 deletions(-) diff --git a/.github/workflows/_ci-relay.yml b/.github/workflows/_ci-relay.yml index fca045d6c3..f9eb369724 100644 --- a/.github/workflows/_ci-relay.yml +++ b/.github/workflows/_ci-relay.yml @@ -694,6 +694,7 @@ jobs: cargo test -p buzz-test-client --test e2e_persona --test e2e_team_catalog --test e2e_nostr_interop --test e2e_thread_roots --test e2e_project -- --ignored --nocapture cargo test -p buzz-test-client --test e2e_relay invite -- --ignored --nocapture cargo test -p buzz-test-client --test e2e_relay nip43_membership_snapshots_are_rejected -- --ignored --nocapture + cargo test -p buzz-test-client --test e2e_relay nip_ia_archive_snapshots_are_rejected -- --ignored --nocapture cargo test -p buzz-test-client --test e2e_relay nip29_departure_wire -- --ignored --nocapture cargo test -p buzz-test-client --test e2e_relay nip29_batch_put_user_wire -- --ignored --nocapture cargo test -p buzz-test-client --test e2e_relay nip29_announce_channel_wire -- --ignored --nocapture diff --git a/crates/buzz-core/src/kind.rs b/crates/buzz-core/src/kind.rs index 26d85177a0..7428c75cfe 100644 --- a/crates/buzz-core/src/kind.rs +++ b/crates/buzz-core/src/kind.rs @@ -926,6 +926,7 @@ pub const fn is_relay_only_kind(kind: u32) -> bool { KIND_VERIFIED_PROFILE | KIND_ARTIFACT_REMOVAL | KIND_NIP43_MEMBERSHIP_LIST + | KIND_IA_ARCHIVED_LIST | KIND_CHANNEL_SUMMARY | KIND_PRESENCE_SNAPSHOT | KIND_DM_VISIBILITY @@ -1024,6 +1025,13 @@ mod tests { assert!(!is_relay_only_kind(KIND_NIP43_LEAVE_REQUEST)); } + #[test] + fn nip_ia_archived_list_is_relay_only() { + assert!(is_relay_only_kind(KIND_IA_ARCHIVED_LIST)); + assert!(!is_relay_only_kind(KIND_IA_ARCHIVE_REQUEST)); + assert!(!is_relay_only_kind(KIND_IA_UNARCHIVE_REQUEST)); + } + #[test] fn thread_window_bounds_is_relay_only() { assert_eq!(KIND_THREAD_WINDOW_BOUNDS, 39007); diff --git a/crates/buzz-db/src/lib.rs b/crates/buzz-db/src/lib.rs index f52ad2a4a4..106b46eda3 100644 --- a/crates/buzz-db/src/lib.rs +++ b/crates/buzz-db/src/lib.rs @@ -28,9 +28,13 @@ /// discard: one per member for every kind:39002 roster republish. `$1` must /// bind the community. /// -/// The three replacement paths that index mentions (NIP-33 parameterized, -/// addressable, and the relay's member snapshot) go through this, so a head -/// and its mention rows leave together on those paths. +/// The addressable path, the relay's member snapshot, and the kind:13534 +/// list writer (whose `member` tags index no mentions) supersede through +/// this, so a head and its mention rows leave together when a newer head +/// replaces it. NIP-33 parameterized replacement drops its superseded rows' +/// mentions itself (`remove_coordinate_versions_in_tx`). Channel deletion +/// (`soft_delete_discovery_events`) retires live heads without a +/// replacement and does not go through this. macro_rules! superseded_with_mentions_sql { ($retire:expr) => { concat!( diff --git a/crates/buzz-db/src/store/channel_members.rs b/crates/buzz-db/src/store/channel_members.rs index 1ba517c547..a002805bda 100644 --- a/crates/buzz-db/src/store/channel_members.rs +++ b/crates/buzz-db/src/store/channel_members.rs @@ -494,15 +494,17 @@ impl LockedMemberSnapshot { let created_at_secs = event.created_at.as_secs() as i64; let created_at = chrono::DateTime::from_timestamp(created_at_secs, 0) .ok_or(DbError::InvalidTimestamp(created_at_secs))?; - let existing: Option<(chrono::DateTime, Vec)> = sqlx::query_as( - "SELECT created_at, id FROM events WHERE community_id = $1 AND kind = $2 AND pubkey = $3 AND channel_id = $4 AND deleted_at IS NULL ORDER BY created_at DESC, id ASC LIMIT 1", - ) - .bind(community_id.as_uuid()) - .bind(kind) - .bind(pubkey.as_slice()) - .bind(channel_id) - .fetch_optional(self.tx.conn()) - .await?; + let (head_sql, supersede_sql) = crate::replaceable::replacement_sql( + true, + crate::replaceable::hard_deletes_superseded(kind), + ); + let existing: Option<(chrono::DateTime, Vec)> = sqlx::query_as(head_sql) + .bind(community_id.as_uuid()) + .bind(kind) + .bind(pubkey.as_slice()) + .bind(channel_id) + .fetch_optional(self.tx.conn()) + .await?; let incoming_id = event.id.as_bytes().as_slice(); if let Some((existing_ts, existing_id)) = existing { if created_at < existing_ts @@ -527,11 +529,14 @@ impl LockedMemberSnapshot { Some(channel_id), ) .await?; - sqlx::query(superseded_with_mentions_sql!( - "UPDATE events SET deleted_at = NOW() WHERE community_id = $1 AND kind = $2 AND pubkey = $3 AND channel_id = $4 AND deleted_at IS NULL" - )) - .bind(community_id.as_uuid()).bind(kind).bind(pubkey.as_slice()).bind(channel_id) - .execute(self.tx.conn()).await?; + // A superseded roster is deleted, not soft-deleted. + sqlx::query(supersede_sql) + .bind(community_id.as_uuid()) + .bind(kind) + .bind(pubkey.as_slice()) + .bind(channel_id) + .execute(self.tx.conn()) + .await?; let received_at = Utc::now(); let sig = event.sig.serialize(); let inserted = sqlx::query("INSERT INTO events (community_id, id, pubkey, created_at, kind, tags, content, sig, received_at, channel_id, d_tag) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11) ON CONFLICT DO NOTHING") diff --git a/crates/buzz-db/src/store/relay_members.rs b/crates/buzz-db/src/store/relay_members.rs index 81b832f587..b8973d2b71 100644 --- a/crates/buzz-db/src/store/relay_members.rs +++ b/crates/buzz-db/src/store/relay_members.rs @@ -1099,8 +1099,9 @@ pub(crate) async fn write_nip43_membership_snapshot( .bind(community_id.as_uuid()) .fetch_all(tx.conn()) .await?; - // Retired lists count too: a list newer than every prior one can't - // repeat an earlier list's id. + // Soft-deleted lists count too: a list newer than every prior one can't + // repeat an earlier list's id. A superseded list is deleted below, but the + // live head it gives way to is always newer. let newest_created_at: Option> = sqlx::query_scalar( "SELECT max(created_at) FROM events \ WHERE community_id = $1 AND kind = $2 AND pubkey = $3 AND channel_id IS NULL", @@ -1140,17 +1141,16 @@ pub(crate) async fn write_nip43_membership_snapshot( let received_at = Utc::now(); let d_tag = crate::event::extract_d_tag(&event); - // The relay is authoritative: retire every prior list unconditionally. - sqlx::query( - "UPDATE events SET deleted_at = NOW() \ - WHERE community_id = $1 AND kind = $2 AND pubkey = $3 \ - AND channel_id IS NULL AND deleted_at IS NULL", - ) - .bind(community_id.as_uuid()) - .bind(kind_i32) - .bind(pubkey_bytes.as_slice()) - .execute(tx.conn()) - .await?; + // The relay is authoritative: retire every prior live list + // unconditionally. A superseded list is deleted, not soft-deleted. + let (_, supersede_sql) = + replaceable::replacement_sql(false, replaceable::hard_deletes_superseded(kind_i32)); + sqlx::query(supersede_sql) + .bind(community_id.as_uuid()) + .bind(kind_i32) + .bind(pubkey_bytes.as_slice()) + .execute(tx.conn()) + .await?; sqlx::query( "INSERT INTO events (community_id, id, pubkey, created_at, kind, tags, content, sig, received_at, channel_id, d_tag) \ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, NULL, $10)", @@ -2588,6 +2588,16 @@ mod postgres_tests { .expect("transfer ownership"); assert!(matches!(write.outcome, TransferResult::Transferred { .. })); assert_membership_list_matches(&pool, community, &keys, write.snapshot.as_ref()).await; + // Each write above deleted the list it superseded, so only the live + // list is stored. + let stored: i64 = + sqlx::query_scalar("SELECT count(*) FROM events WHERE community_id = $1 AND kind = $2") + .bind(community.as_uuid()) + .bind(buzz_core::kind::KIND_NIP43_MEMBERSHIP_LIST as i32) + .fetch_one(&pool) + .await + .expect("count stored lists"); + assert_eq!(stored, 1, "superseded lists are deleted"); let provisioned = make_test_community(&pool).await; let write = db diff --git a/crates/buzz-db/src/store/replaceable.rs b/crates/buzz-db/src/store/replaceable.rs index c7ca35e517..b67cc12dd5 100644 --- a/crates/buzz-db/src/store/replaceable.rs +++ b/crates/buzz-db/src/store/replaceable.rs @@ -342,6 +342,41 @@ async fn replace_parameterized_event_in_transaction_impl( )) } +/// Whether the relay's replacement writers delete a superseded head of +/// `kind` instead of soft-deleting it. +/// +/// These are the lists the relay signs and republishes in full on every +/// change: the NIP-43 membership list (13534), the NIP-IA archived list +/// (13535) and NIP-29 group state (39000–39002), written by the addressable +/// path, the kind:39002 member snapshot and the kind:13534 writer, which all +/// build their supersede with [`replacement_sql`] from this predicate. A +/// retired head is a full copy that no relay reader returns. +/// +/// While the coordinate has a live head, a replay of a deleted id is still +/// rejected: its `created_at` does not beat the head's. With no live head (a +/// deleted channel's soft-deleted state, say), the deleted row no longer +/// makes the replay a duplicate, and kinds without a channel have no +/// created-at floor. Only the relay can submit these events: ingest requires +/// the signer to be the authenticated pubkey, kinds 13534 and 13535 are +/// relay-only, and the relay's writers sign a new event on every attempt. +/// +/// The check is by kind, not signer, and every supersede is scoped to the +/// event's own pubkey. A client's kind:39000–39002 goes through the NIP-33 +/// path, which keeps the soft delete. Channel deletion +/// (`soft_delete_discovery_events`) retires the live head and still +/// soft-deletes it. +pub(crate) const fn hard_deletes_superseded(kind: i32) -> bool { + use buzz_core::kind::{ + KIND_IA_ARCHIVED_LIST, KIND_NIP29_GROUP_ADMINS, KIND_NIP29_GROUP_MEMBERS, + KIND_NIP29_GROUP_METADATA, KIND_NIP43_MEMBERSHIP_LIST, + }; + kind == KIND_NIP43_MEMBERSHIP_LIST as i32 + || kind == KIND_IA_ARCHIVED_LIST as i32 + || kind == KIND_NIP29_GROUP_METADATA as i32 + || kind == KIND_NIP29_GROUP_ADMINS as i32 + || kind == KIND_NIP29_GROUP_MEMBERS as i32 +} + /// The `WHERE` predicate (after the keyword, which each caller spells so the /// floor policy can see where a `SET` list ends) of one replaceable /// coordinate's head read and supersede. @@ -374,6 +409,48 @@ macro_rules! replacement_head_sql { }; } +/// The statement that retires a coordinate's live head: `soft` sets +/// `deleted_at`, `hard` deletes the row (`hard_deletes_superseded`). Either +/// way the head's mention rows are deleted with it. +macro_rules! replacement_supersede_sql { + (soft, $scope:tt) => { + superseded_with_mentions_sql!(concat!( + "UPDATE events SET deleted_at = NOW() WHERE ", + replacement_scope!($scope) + )) + }; + (hard, $scope:tt) => { + superseded_with_mentions_sql!(concat!( + "DELETE FROM events WHERE ", + replacement_scope!($scope) + )) + }; +} + +/// The head read and the supersede statement of one replaceable coordinate, +/// in a channel (`$4` binds it) or global, retiring the head by delete when +/// `hard_delete` holds and by soft delete otherwise. The addressable path, +/// the kind:39002 member snapshot and the kind:13534 writer build their +/// replacement statements here, so the index-condition test covers each +/// replacement statement they run. The snapshot locks' own head reads +/// (`latest_member_event_timestamp`, `lock_group_state_snapshot`) are +/// separate SQL that the test does not check. The NIP-33 path keys on +/// `d_tag` and builds its own. +pub(crate) fn replacement_sql(in_channel: bool, hard_delete: bool) -> (&'static str, &'static str) { + let head = if in_channel { + replacement_head_sql!(in_channel) + } else { + replacement_head_sql!(global) + }; + let supersede = match (in_channel, hard_delete) { + (true, false) => replacement_supersede_sql!(soft, in_channel), + (true, true) => replacement_supersede_sql!(hard, in_channel), + (false, false) => replacement_supersede_sql!(soft, global), + (false, true) => replacement_supersede_sql!(hard, global), + }; + (head, supersede) +} + /// Take the replacement lock of the `(kind, pubkey, channel_id)` coordinate /// on `tx`, serializing every writer of that coordinate until the transaction /// ends. Key collisions only cause extra serialization; they cannot change @@ -409,7 +486,7 @@ pub(crate) async fn take_replacement_lock( /// /// Returns `(event, false)` for a stale write or a duplicate ID. The caller /// commits only when the event was inserted and rolls back otherwise: a -/// duplicate leaves the previous event soft-deleted on the transaction. +/// duplicate leaves the previous event retired on the transaction. pub(crate) async fn replace_addressable_event_under_lock( tx: &mut AdmittedTx, event: &nostr::Event, @@ -424,23 +501,8 @@ pub(crate) async fn replace_addressable_event_under_lock( // Check for the newest existing event. ORDER BY + LIMIT 1 is defensive against // historical data where prior bugs may have left multiple live rows. - let (head_sql, supersede_sql) = if channel_id.is_some() { - ( - replacement_head_sql!(in_channel), - superseded_with_mentions_sql!(concat!( - "UPDATE events SET deleted_at = NOW() WHERE ", - replacement_scope!(in_channel) - )), - ) - } else { - ( - replacement_head_sql!(global), - superseded_with_mentions_sql!(concat!( - "UPDATE events SET deleted_at = NOW() WHERE ", - replacement_scope!(global) - )), - ) - }; + let (head_sql, supersede_sql) = + replacement_sql(channel_id.is_some(), hard_deletes_superseded(kind_i32)); let mut head = sqlx::query_as(head_sql) .bind(community_id.as_uuid()) .bind(kind_i32) @@ -471,7 +533,8 @@ pub(crate) async fn replace_addressable_event_under_lock( crate::channel_members::guard_channel_roster_event(tx, kind_i32, channel_id, &tags_json) .await?; - // Soft-delete the old event (if any). + // Retire the old event (if any): soft-delete it, or delete a relay-owned + // list's head (`hard_deletes_superseded`). let mut supersede = sqlx::query(supersede_sql) .bind(community_id.as_uuid()) .bind(kind_i32) @@ -713,6 +776,21 @@ impl Db { } } +#[cfg(test)] +mod tests { + use super::hard_deletes_superseded; + + #[test] + fn only_relay_owned_lists_hard_delete_their_superseded_heads() { + for kind in [13534, 13535, 39000, 39001, 39002] { + assert!(hard_deletes_superseded(kind), "kind {kind}"); + } + for kind in [-1, 0, 3, 10002, 13533, 13536, 30078, 38999, 39003] { + assert!(!hard_deletes_superseded(kind), "kind {kind}"); + } + } +} + #[cfg(test)] mod postgres_tests { use super::*; @@ -1017,24 +1095,13 @@ mod postgres_tests { .expect("populated partitions"); populated.sort(); - let statements = [ - ( - true, - replacement_head_sql!(in_channel), - superseded_with_mentions_sql!(concat!( - "UPDATE events SET deleted_at = NOW() WHERE ", - replacement_scope!(in_channel) - )), - ), - ( - false, - replacement_head_sql!(global), - superseded_with_mentions_sql!(concat!( - "UPDATE events SET deleted_at = NOW() WHERE ", - replacement_scope!(global) - )), - ), - ]; + // The statements production runs, for every scope and retire mode. + let statements = [(true, false), (false, false), (true, true), (false, true)].map( + |(in_channel, hard_delete)| { + let (head_sql, supersede_sql) = replacement_sql(in_channel, hard_delete); + (in_channel, head_sql, supersede_sql) + }, + ); for (in_channel, head_sql, supersede_sql) in statements { for sql in [head_sql, supersede_sql] { let explain = format!("EXPLAIN (FORMAT JSON) {sql}"); @@ -1133,13 +1200,16 @@ mod postgres_tests { let base = Timestamp::now().as_secs(); // Every supersede path retires the old head with a soft delete, except - // NIP-RS read state and mesh status, which the NIP-33 path hard-deletes. - // The relay roster writer is the production kind:39002 path; its p tags - // must match the channel's members. The relay-signed kind:13535 list - // goes through the addressable path. + // NIP-RS read state and mesh status, which the NIP-33 path hard-deletes, + // and the relay-signed lists (`hard_deletes_superseded`), which the + // relay's writers hard-delete. The relay roster writer is the + // production kind:39002 path; its p tags must match the channel's + // members. The relay-signed kind:13535 list and the channel's + // kind:39000 metadata go through the addressable path, as does a + // user's kind:3 contact list, which keeps the soft delete. enum Path { MemberSnapshot, - Addressable, + Addressable(Option), Parameterized, } let roster_p = vec![vec![owner.as_str(), "", "owner"]]; @@ -1154,15 +1224,33 @@ mod postgres_tests { Some(channel.to_string()), vec![], roster_p, - false, + true, ), ( - "addressable", - Path::Addressable, + "archived list", + Path::Addressable(None), 13535_u16, None, vec![], people_p(), + true, + ), + ( + "group metadata", + Path::Addressable(Some(channel)), + 39000_u16, + Some(channel.to_string()), + vec![], + people_p(), + true, + ), + ( + "contact list", + Path::Addressable(None), + 3_u16, + None, + vec![], + people_p(), false, ), ( @@ -1234,8 +1322,8 @@ mod postgres_tests { snapshot.release().await.expect("commit roster"); inserted } - Path::Addressable => { - db.replace_addressable_event(community, &event, None) + Path::Addressable(channel_id) => { + db.replace_addressable_event(community, &event, *channel_id) .await .expect("replace addressable") .1 diff --git a/crates/buzz-relay/src/api/bridge.rs b/crates/buzz-relay/src/api/bridge.rs index 7429c411c3..3357dbf32b 100644 --- a/crates/buzz-relay/src/api/bridge.rs +++ b/crates/buzz-relay/src/api/bridge.rs @@ -11170,7 +11170,8 @@ pub(crate) mod postgres_tests { // A schema whose `users` table can be taken away after the link, // so only the owner-to-agent lookup fails at revoke time. It // carries `communities` so writes pass community write admission, - // and `events` for the member list each membership change writes. + // and `events` and `event_mentions` for the member list each + // membership change writes and the superseded list it deletes. let db_url = crate::test_support::database_url(); let schema = format!("late_owner_{}", uuid::Uuid::new_v4().simple()); sqlx::raw_sql(sqlx::AssertSqlSafe(format!( @@ -11182,7 +11183,8 @@ pub(crate) mod postgres_tests { CREATE TABLE {schema}.join_policy_acceptances \ (LIKE public.join_policy_acceptances INCLUDING ALL); \ CREATE TABLE {schema}.communities (LIKE public.communities INCLUDING ALL); \ - CREATE TABLE {schema}.events (LIKE public.events INCLUDING ALL);" + CREATE TABLE {schema}.events (LIKE public.events INCLUDING ALL); \ + CREATE TABLE {schema}.event_mentions (LIKE public.event_mentions INCLUDING ALL);" ))) .execute(state.db.pool()) .await diff --git a/crates/buzz-relay/src/handlers/group_state_postgres_tests.rs b/crates/buzz-relay/src/handlers/group_state_postgres_tests.rs index c6955c3a4d..9134433a4e 100644 --- a/crates/buzz-relay/src/handlers/group_state_postgres_tests.rs +++ b/crates/buzz-relay/src/handlers/group_state_postgres_tests.rs @@ -1072,15 +1072,15 @@ enum HoldPublisher { /// holds the join after its read behind the lock until the edit is waiting /// for that lock, so the edit must still win with its own state. /// -/// Both legs also check the timestamps: every kind:39000 publication for -/// the coordinate, replaced rows included, leaves exactly one row, and -/// their `created_at` strictly increase in storage order. The live event is -/// first pinned an hour ahead, so each publication's timestamp is the live -/// one plus a second and the clock cannot separate the two publishers. -/// Mutation: take the live `created_at` before the lock → RED every time: -/// the publisher that locks second computes the same second as the first, -/// and either loses the id tie and leaves no row, or wins it and repeats -/// the second. +/// Both legs also check the timestamps. A superseded kind:39000 is deleted, +/// so the coordinate stores exactly one row, and it is two seconds past the +/// pinned one: each of the two publications stored the live `created_at` +/// plus a second. The live event is first pinned an hour ahead, so the clock +/// cannot separate the two publishers. Mutation: take the live `created_at` +/// before the lock → RED every time: the publisher that locks second +/// computes the same second as the first, and either loses the id tie and +/// stores nothing, or wins it and repeats the second; either way the live +/// row is one second past the pinned one. #[tokio::test] #[ignore = "requires Postgres"] async fn a_publisher_that_read_before_an_edit_cannot_replace_it() { @@ -1089,8 +1089,10 @@ async fn a_publisher_that_read_before_an_edit_cannot_replace_it() { } } -/// `created_at` of every relay-signed kind:39000 row for `channel_id`, -/// replaced rows included, in storage order. +/// `created_at` of every stored relay-signed kind:39000 row for +/// `channel_id`, in storage order. Superseded rows are deleted, so a +/// soft-deleted row here would come only from channel deletion or an older +/// relay. async fn stored_metadata_created_at( state: &AppState, tenant: &TenantContext, @@ -1155,9 +1157,13 @@ async fn join_publisher_held_against_an_auto_join_edit(hold: HoldPublisher) { .expect("store pinned kind:39000") .1 ); - let rows_before = stored_metadata_created_at(&state, &tenant, channel_id) - .await - .len(); + let pinned_at = chrono::DateTime::from_timestamp(pinned.created_at.as_secs() as i64, 0) + .expect("pinned created_at"); + assert_eq!( + stored_metadata_created_at(&state, &tenant, channel_id).await, + [pinned_at], + "{hold:?}: the pinned kind:39000 deleted the heads it superseded" + ); let (arrived, release) = match hold { HoldPublisher::BeforeLock => { @@ -1233,15 +1239,11 @@ async fn join_publisher_held_against_an_auto_join_edit(hold: HoldPublisher) { !tags.contains(&vec!["auto_join".to_string()]), "{hold:?}: the join's stale kind:39000 replaced the edit's: {tags:?}" ); - let created_at = stored_metadata_created_at(&state, &tenant, channel_id).await; assert_eq!( - created_at.len(), - rows_before + 2, - "{hold:?}: the join and the edit each leave one kind:39000 row: {created_at:?}" - ); - assert!( - created_at.windows(2).all(|pair| pair[0] < pair[1]), - "{hold:?}: kind:39000 timestamps must strictly increase in storage order: {created_at:?}" + stored_metadata_created_at(&state, &tenant, channel_id).await, + [pinned_at + chrono::Duration::seconds(2)], + "{hold:?}: the join and the edit each publish one second past the live kind:39000, \ + and each deletes the head it supersedes" ); } diff --git a/crates/buzz-relay/src/handlers/identity_archive.rs b/crates/buzz-relay/src/handlers/identity_archive.rs index 0daa80b409..58e0dbae12 100644 --- a/crates/buzz-relay/src/handlers/identity_archive.rs +++ b/crates/buzz-relay/src/handlers/identity_archive.rs @@ -705,9 +705,14 @@ mod tests { /// NIP-IA: every snapshot's `created_at` is strictly past the previous /// one's, even when publishers race on one head. Concurrent publishers - /// each read the head behind the replacement lock. RED-on-revert: with the - /// head read before the lock, publishers keep tying on head + 1 and one - /// exhausts its replacement attempts. + /// each read the head behind the replacement lock. The head is first + /// pinned an hour ahead, so each snapshot is stamped exactly one second + /// past the one it replaces. A superseded kind:13535 is deleted, so the + /// coordinate stores one row, 16 seconds past the pinned one only if + /// each of the 16 publishers stored exactly one snapshot one second + /// later. RED-on-revert: with the head read before the lock, publishers + /// keep tying on head + 1, so a same-second replacement leaves the row + /// short of + 16 s, or a publisher exhausts its replacement attempts. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] #[ignore = "requires Postgres and Redis"] async fn concurrent_archival_publishers_stamp_strictly_increasing_snapshots() { @@ -718,6 +723,26 @@ mod tests { .await .expect("Redis for an ignored test"); let tenant = seed_test_community(&pool).await; + let pinned = EventBuilder::new( + Kind::Custom(buzz_core::kind::KIND_IA_ARCHIVED_LIST as u16), + "", + ) + .tags([Tag::parse(["-"]).expect("'-' tag")]) + .custom_created_at(nostr::Timestamp::from( + nostr::Timestamp::now().as_secs() + 3600, + )) + .sign_with_keys(&state.relay_keypair) + .expect("sign pinned kind:13535"); + assert!( + state + .db + .replace_addressable_event(tenant.community(), &pinned, None) + .await + .expect("store pinned kind:13535") + .1 + ); + let pinned_at = chrono::DateTime::from_timestamp(pinned.created_at.as_secs() as i64, 0) + .expect("pinned created_at"); let publishers: Vec<_> = (0..16) .map(|_| { @@ -733,8 +758,7 @@ mod tests { .expect("publisher succeeds"); } - // Superseded snapshots stay as soft-deleted rows, so every snapshot - // ever stored is visible here. + // Every stored row of the coordinate, retired rows included. let stamps: Vec> = sqlx::query_scalar( "SELECT created_at FROM events WHERE community_id = $1 AND kind = $2 \ AND pubkey = $3 ORDER BY created_at", @@ -745,10 +769,11 @@ mod tests { .fetch_all(&pool) .await .expect("read stored snapshots"); - assert_eq!(stamps.len(), 16, "every publisher stores its own snapshot"); - assert!( - stamps.windows(2).all(|pair| pair[0] < pair[1]), - "snapshots must never share a created_at: {stamps:?}" + assert_eq!( + stamps, + [pinned_at + chrono::Duration::seconds(16)], + "each publisher stores one snapshot one second past the head it \ + replaces, and deletes that head" ); } } diff --git a/crates/buzz-test-client/tests/e2e_relay.rs b/crates/buzz-test-client/tests/e2e_relay.rs index 6a214860a7..e854102f06 100644 --- a/crates/buzz-test-client/tests/e2e_relay.rs +++ b/crates/buzz-test-client/tests/e2e_relay.rs @@ -223,22 +223,43 @@ async fn test_connect_and_authenticate() { #[tokio::test] #[ignore] async fn test_client_submitted_nip43_membership_snapshots_are_rejected() { - let url = relay_url(); let keys = Keys::generate(); // Prove this actor can submit a normal event so the rejection below is // specifically the relay-only invariant, not a broader authorization failure. create_test_channel(&keys).await; - let forged = EventBuilder::new(Kind::Custom(13_534), "") - .tags([Tag::parse(["member", &keys.public_key().to_hex(), "owner"]).unwrap()]) - .sign_with_keys(&keys) - .expect("sign forged membership snapshot"); + let member = Tag::parse(["member", &keys.public_key().to_hex(), "owner"]).unwrap(); + assert_relay_only_snapshot_rejected(&keys, 13_534, member).await; +} - let mut ws = BuzzTestClient::connect(&url, &keys).await.expect("connect"); +/// NIP-IA's kind:13535 archived-identities list is relay-signed, like the +/// kind:13534 membership list; a client-signed copy is rejected at ingest. +#[tokio::test] +#[ignore] +async fn test_client_submitted_nip_ia_archive_snapshots_are_rejected() { + let keys = Keys::generate(); + create_test_channel(&keys).await; + let archived = Tag::parse(["p", &Keys::generate().public_key().to_hex()]).unwrap(); + assert_relay_only_snapshot_rejected(&keys, 13_535, archived).await; +} + +/// Submit a `kind` snapshot signed by `keys` over WebSocket and HTTP and +/// assert that both transports reject it as a relay-only kind. +async fn assert_relay_only_snapshot_rejected(keys: &Keys, kind: u16, tag: Tag) { + let url = relay_url(); + let forged = EventBuilder::new(Kind::Custom(kind), "") + .tags([tag]) + .sign_with_keys(keys) + .expect("sign forged snapshot"); + + let mut ws = BuzzTestClient::connect(&url, keys).await.expect("connect"); let ok = ws .send_event(forged.clone()) .await .expect("submit forged snapshot via websocket"); - assert!(!ok.accepted, "forged WebSocket snapshot must be rejected"); + assert!( + !ok.accepted, + "forged WebSocket kind:{kind} snapshot must be rejected" + ); assert_eq!(ok.message, "restricted: relay-only kind"); ws.disconnect().await.expect("disconnect"); @@ -254,7 +275,7 @@ async fn test_client_submitted_nip43_membership_snapshots_are_rejected() { let body = response.text().await.expect("read HTTP rejection"); assert!( body.contains("restricted: relay-only kind"), - "unexpected HTTP rejection: {body}" + "unexpected kind:{kind} HTTP rejection: {body}" ); } diff --git a/docs/admin/README.md b/docs/admin/README.md index 2ffe30f1be..d343e88731 100644 --- a/docs/admin/README.md +++ b/docs/admin/README.md @@ -393,7 +393,11 @@ not the JSON error envelope, before authentication). All four accept a signed owner's. - `GET /api/admin/v1/events/{id}?communityHost=` Reads a single event scoped to that community, including soft-deleted - ones. Response: `{"id", "authorPubkey", "kind", "content", "createdAt", + ones. A relay-signed list (kinds 13534, 13535, and 39000–39002) that a + newer list replaced is deleted, so its ID returns `404 event_not_found`. + A list retired another way (channel deletion, NIP-09, or a replacement + written before this behavior) stays soft-deleted and is returned with + `deletedAt` set. Response: `{"id", "authorPubkey", "kind", "content", "createdAt", "deletedAt"|null, "channelId"|null}`. Never returns author-only kinds (event reminders, push leases, private managed agents) or result-gated kinds (DM visibility, agent turn metrics). Absent, other-community,