From fc29f6068aada24b488f9743eecb7f280c0614c5 Mon Sep 17 00:00:00 2001 From: Tom Brow Date: Sat, 14 Nov 2026 09:21:19 -0800 Subject: [PATCH] fix(relay): stamp each NIP-IA archive list strictly after the previous one (#9476) ### Why When an admin archives or unarchives an identity, the relay publishes a new archived identities list (kind 13535). This list replaces the previous one. It contains all the identities that are archived in the community. Clients use it to hide archived agents from pickers and search. The list can be large (about 228 KB on Block's Builderlab), and it seldom changes. Thus the mobile app wants to download it only when it changed. To do this, the app keeps the last list it received, and asks the relay only for a list that is newer than that one (`since` its `created_at` plus one, in [#9445 archive list cache](https://github.com/block/buzz/pull/9445)). This works only if each new list has a `created_at` that is later than the previous list's. Today the relay does not always do this: - The relay calculates the new list's `created_at` as "the current list's `created_at` plus one second". But it reads the current list before it gets the lock that controls replacement. - Thus, when two archive requests occur at the same time, two publishers can read the same current list. Then both sign a list with the same `created_at`. The store keeps the one with the lower event id. - A client that already has the other list does not see the replacement, because it asks only for lists with a later `created_at`. It continues to hide or show the wrong agents until the next archive change or an app restart. - With many concurrent publishers it is worse: a publisher can lose that tie again and again, and then stop with `failed to publish kind:13535 after 8 concurrent replacements`. Then no list contains the latest archive change. ### What changes - New `Db::replace_addressable_event_after_head`. It gets the replacement lock first. Then it reads the current list. Then it signs and stores the new list. Thus only one publisher at a time calculates the next `created_at`, and each list is stamped strictly later than the previous one. - `publish_nipia_archival_list` uses this method. The check that publishes again when the archive state changed during a publish does not change. - NIP-IA now makes this a rule: a relay MUST publish each `kind:13535` with a `created_at` strictly greater than its previous one. Clients MAY then ask only for lists `since` their list's `created_at` plus one. ### Validation New relay test: 16 concurrent publishers all complete, and each stored list (superseded rows included) has a strictly later `created_at`. On main the same test fails, because a publisher uses all its retries. The test needs Postgres and Redis, so it is in `postgres_tests` and runs in the PostgreSQL Tests lane; a missing database or Redis makes it fail, not pass. The existing archive tests pass against a local Postgres, including the stale-publisher test. `just test` passes all 160 steps except one NIP-FI session deadline test (`deadline_refused_permit_still_queues_one_denial_when_cancel_wins`), which this change does not touch and which passes 5 of 5 reruns alone. Clippy passes. ### Regressions None expected. - A publisher now holds the replacement lock a little longer: for one read and one signature. Only archive-list writes for the same community wait on this lock, and archive changes are rare. - The new `Db` method is an addition. `replace_addressable_event` and its callers do not change. - Until this is deployed, relays keep the old behavior. [#9445 archive list cache](https://github.com/block/buzz/pull/9445) accepts that same-second case on its own. **Accepted limitation: a database restore.** The rule holds only while the relay keeps its newest list. If an operator restores the relay from a backup, the relay calculates the next `created_at` from the restored list (`max(restored + 1, now)`). If earlier fast publishes went ahead of the clock, that value can be at or below a `created_at` that a client already has. That client then stays stale until a list passes its cached `created_at`, or the app restarts. This change adds no repair for a restore. --------- Signed-off-by: Tom Brow Co-authored-by: Tom Brow --- crates/buzz-db/src/store/replaceable.rs | 63 +++++++++++++++++++ .../src/handlers/identity_archive.rs | 55 +++++++++++++++- .../buzz-relay/src/handlers/side_effects.rs | 50 +++++++-------- docs/nips/NIP-IA.md | 4 +- 4 files changed, 143 insertions(+), 29 deletions(-) diff --git a/crates/buzz-db/src/store/replaceable.rs b/crates/buzz-db/src/store/replaceable.rs index 8d6f9f3b6c..36cc4a5d7a 100644 --- a/crates/buzz-db/src/store/replaceable.rs +++ b/crates/buzz-db/src/store/replaceable.rs @@ -641,6 +641,69 @@ impl Db { .await } + /// Replace a relay-built replaceable event whose `created_at` depends on + /// the live head: `build` receives the head's `created_at` (or `None`) + /// read behind the coordinate's replacement lock, so concurrent writers + /// of one coordinate each see the previous writer's event and can stamp + /// theirs strictly later. The built event must be signed by `pubkey` and + /// have `kind`. Otherwise as [`Db::replace_addressable_event`]. + #[datastore_span(name = "replace_addressable_event_after_head", system = "postgresql")] + pub async fn replace_addressable_event_after_head( + &self, + community_id: CommunityId, + kind: i32, + pubkey: &[u8], + channel_id: Option, + build: impl FnOnce(Option) -> Result + Send, + ) -> Result<(StoredEvent, bool)> { + let mut tx = crate::begin_community_event_write_transaction_with_legacy_metrics( + &self.pool, + community_id, + observability::WriterOperation::EventWrite, + ) + .await?; + tx.set_push_enqueue(self.push_enqueue.clone()); + let transaction_timer = observability::TransactionTimer::start( + observability::TransactionOperation::ReplaceAddressableEvent, + ); + + transaction_timer + .observe(async { + take_replacement_lock(&mut tx, kind, pubkey, channel_id).await?; + let head_sql = if channel_id.is_some() { + replacement_head_sql!(in_channel) + } else { + replacement_head_sql!(global) + }; + let mut head = sqlx::query_as(head_sql) + .bind(community_id.as_uuid()) + .bind(kind) + .bind(pubkey); + if let Some(channel_id) = channel_id { + head = head.bind(channel_id); + } + let existing: Option<(chrono::DateTime, Vec)> = + head.fetch_optional(tx.conn()).await?; + let event = build(existing.map(|(created_at, _)| created_at.timestamp() as u64))?; + if buzz_core::kind::event_kind_i32(&event) != kind + || event.pubkey.to_bytes().as_slice() != pubkey + { + return Err(DbError::InvalidData( + "replacement does not match its locked coordinate".into(), + )); + } + let (stored, was_inserted) = + replace_addressable_event_under_lock(&mut tx, &event, channel_id).await?; + if was_inserted { + tx.commit().await?; + } else { + tx.rollback().await?; + } + Ok((stored, was_inserted)) + }) + .await + } + /// Replace a NIP-33 event inside a caller-owned transaction. /// /// The caller owns commit or rollback. Requiring [`AdmittedTx`] here and diff --git a/crates/buzz-relay/src/handlers/identity_archive.rs b/crates/buzz-relay/src/handlers/identity_archive.rs index 53f25cacee..0daa80b409 100644 --- a/crates/buzz-relay/src/handlers/identity_archive.rs +++ b/crates/buzz-relay/src/handlers/identity_archive.rs @@ -437,7 +437,7 @@ mod tests { async fn test_pool() -> Option { let url = std::env::var("DATABASE_URL") - .unwrap_or_else(|_| "postgres://buzz:buzz_dev@localhost:5432/buzz".into()); + .unwrap_or_else(|_| "postgres://buzz:buzz_dev@localhost:5432/buzz".into()); // sadscan:disable np.postgres.1 -- local test fixture sqlx::PgPool::connect(&url).await.ok() } @@ -700,6 +700,59 @@ mod tests { ); } + mod postgres_tests { + use super::*; + + /// 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. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + #[ignore = "requires Postgres and Redis"] + async fn concurrent_archival_publishers_stamp_strictly_increasing_snapshots() { + // Ignored, so it runs only where Postgres and Redis are provided: a + // missing one is a failure, never a silent pass. + let pool = test_pool().await.expect("Postgres for an ignored test"); + let state = test_state(pool.clone()) + .await + .expect("Redis for an ignored test"); + let tenant = seed_test_community(&pool).await; + + let publishers: Vec<_> = (0..16) + .map(|_| { + let tenant = tenant.clone(); + let state = state.clone(); + tokio::spawn(async move { publish_nipia_archival_list(&tenant, &state).await }) + }) + .collect(); + for publisher in publishers { + publisher + .await + .expect("join publisher") + .expect("publisher succeeds"); + } + + // Superseded snapshots stay as soft-deleted rows, so every snapshot + // ever stored is visible here. + 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", + ) + .bind(tenant.community().as_uuid()) + .bind(buzz_core::kind::KIND_IA_ARCHIVED_LIST as i32) + .bind(state.relay_keypair.public_key().to_bytes().as_slice()) + .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:?}" + ); + } + } + #[tokio::test] async fn owner_archive_rejects_stale_request_after_live_kind0_owner_flip() { let Some(pool) = test_pool().await else { diff --git a/crates/buzz-relay/src/handlers/side_effects.rs b/crates/buzz-relay/src/handlers/side_effects.rs index f7f83f2494..cc0c10ca3c 100644 --- a/crates/buzz-relay/src/handlers/side_effects.rs +++ b/crates/buzz-relay/src/handlers/side_effects.rs @@ -4651,34 +4651,32 @@ pub async fn publish_nipia_archival_list( ); } - // NIP-16 resolves same-second replacements by event id. Force this - // canonical snapshot strictly past the current head instead of letting a - // rapid archive→unarchive randomly preserve the stale archive state. - let now = nostr::Timestamp::now().as_secs(); - let previous = state - .db - .query_events_for_event_write(&buzz_db::event::EventQuery { - kinds: Some(vec![KIND_IA_ARCHIVED_LIST as i32]), - pubkey: Some(relay_pubkey.to_bytes().to_vec()), - limit: Some(1), - global_only: true, - ..buzz_db::event::EventQuery::for_community(tenant.community()) - }) - .await?; - let created_at = previous - .first() - .map(|event| (event.event.created_at.as_secs() + 1).max(now)) - .unwrap_or(now); - - let event = EventBuilder::new(Kind::Custom(KIND_IA_ARCHIVED_LIST as u16), "") - .tags(tags) - .custom_created_at(nostr::Timestamp::from(created_at)) - .sign_with_keys(&state.relay_keypair) - .map_err(|e| anyhow::anyhow!("failed to sign kind:{KIND_IA_ARCHIVED_LIST}: {e}"))?; - + // NIP-IA: each snapshot's created_at is strictly past the previous + // one's, so clients can ask only for a newer list. The head is read + // behind the replacement lock: two publishers racing on one head would + // otherwise both stamp head + 1 and let a same-second replacement win + // by event id. let (stored, was_inserted) = state .db - .replace_addressable_event(tenant.community(), &event, None) + .replace_addressable_event_after_head( + tenant.community(), + KIND_IA_ARCHIVED_LIST as i32, + &relay_pubkey.to_bytes(), + None, + |previous| { + let now = nostr::Timestamp::now().as_secs(); + let created_at = previous.map_or(now, |previous| (previous + 1).max(now)); + EventBuilder::new(Kind::Custom(KIND_IA_ARCHIVED_LIST as u16), "") + .tags(tags) + .custom_created_at(nostr::Timestamp::from(created_at)) + .sign_with_keys(&state.relay_keypair) + .map_err(|e| { + buzz_db::DbError::InvalidData(format!( + "failed to sign kind:{KIND_IA_ARCHIVED_LIST}: {e}" + )) + }) + }, + ) .await .map_err(|e| anyhow::anyhow!("archive snapshot write failed: {}", e.kind()))?; if !was_inserted { diff --git a/docs/nips/NIP-IA.md b/docs/nips/NIP-IA.md index 28b2cfa52d..f54d60d253 100644 --- a/docs/nips/NIP-IA.md +++ b/docs/nips/NIP-IA.md @@ -214,7 +214,7 @@ The NIP-70 marker is intentional on the snapshot even though the snapshot is rep Each archived identity is represented by a bare `p` tag whose second element is the archived pubkey. Additional elements on `p` tags are not defined by this NIP and MUST be ignored for archive-state construction. Metadata such as reason, replacement pubkey, actor, and consent path belongs on the `kind:8002`/`kind:8003` deltas, not on the list. -The relay SHOULD publish a new `kind:13535` list after every accepted archive or unarchive operation. Clients MUST treat the latest valid list as authoritative current state. Deltas are useful for live updates and audit history, but if a delta history and the latest list disagree, the latest valid list wins. +The relay SHOULD publish a new `kind:13535` list after every accepted archive or unarchive operation. Each list the relay publishes MUST have a `created_at` strictly greater than that of the relay's previous `kind:13535`, even when publications race or fall within one second, so that clients can ask only for a newer list (see [Snapshot and Delta Consistency](#snapshot-and-delta-consistency)). Clients MUST treat the latest valid list as authoritative current state. Deltas are useful for live updates and audit history, but if a delta history and the latest list disagree, the latest valid list wins. ## Request Authorization Policy @@ -312,7 +312,7 @@ Clients SHOULD process live `kind:8002` and `kind:8003` deltas for immediate UI ## Snapshot and Delta Consistency -The latest valid `kind:13535` snapshot is authoritative. Deltas are an append-only explanation stream. Clients SHOULD track the highest `created_at` they have accepted per relay identity for `kind:13535` and reject older snapshots from the same relay identity, even if they arrive later over a subscription. This provides rollback resistance against stale snapshot replay. Same-`created_at` resolution follows NIP-01: retain the event with the lowest id (first in lexical order). +The latest valid `kind:13535` snapshot is authoritative. Deltas are an append-only explanation stream. Clients SHOULD track the highest `created_at` they have accepted per relay identity for `kind:13535` and reject older snapshots from the same relay identity, even if they arrive later over a subscription. This provides rollback resistance against stale snapshot replay. Because a relay whose stored history is intact never publishes two snapshots with one `created_at`, a client holding a snapshot MAY reconcile by requesting only `kind:13535` with `since` set to that snapshot's `created_at` plus one, and keep its snapshot when nothing newer exists. Should two snapshots with one `created_at` nevertheless meet, resolution follows NIP-01: retain the event with the lowest id (first in lexical order). A relay restored to an older database can stamp its next snapshot at or below one a client already holds; that client rejects it under the rule above, with or without `since`, until a later snapshot passes its high-water mark. A client reconstructing state from scratch SHOULD: