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: