Skip to content

Commit 1ad28a4

Browse files
wesbillmanMongo
andcommitted
fix(relay): keep archival snapshots monotonic
NIP-IA snapshots used whole-second timestamps, so rapid archive state changes could lose to NIP-16's random same-second event-id tie-break and strand stale state. Advance each snapshot past the current head and retry from canonical archive state when a concurrent replacement wins or changes the set before dispatch. Add a focused archive-to-unarchive regression that verifies the final stored snapshot advances and carries the canonical empty set. Co-authored-by: Mongo <5c25403eab7271f9f94ddd4f2b270e8cac2c92e2c830c51877cca6ec974ffb3f@buzz.block.builderlab.xyz> Signed-off-by: Wes <[email protected]>
1 parent 5bedb05 commit 1ad28a4

2 files changed

Lines changed: 155 additions & 24 deletions

File tree

‎crates/buzz-relay/src/handlers/identity_archive.rs‎

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -512,6 +512,93 @@ mod tests {
512512
TenantContext::resolved(CommunityId::from_uuid(id), host)
513513
}
514514

515+
#[tokio::test]
516+
async fn archival_snapshot_advances_timestamp_for_rapid_state_replacement() {
517+
let Some(pool) = test_pool().await else {
518+
return;
519+
};
520+
if sqlx::query("SELECT 1 FROM archived_identities LIMIT 1")
521+
.execute(&pool)
522+
.await
523+
.is_err()
524+
{
525+
return;
526+
}
527+
let Some(state) = test_state(pool.clone()).await else {
528+
return;
529+
};
530+
let tenant = seed_test_community(&pool).await;
531+
let target_hex = Keys::generate().public_key().to_hex();
532+
let request_id = "a".repeat(64);
533+
534+
state
535+
.db
536+
.archive(
537+
tenant.community(),
538+
&target_hex,
539+
"self",
540+
&target_hex,
541+
None,
542+
None,
543+
&request_id,
544+
)
545+
.await
546+
.expect("archive identity");
547+
publish_nipia_archival_list(&tenant, &state)
548+
.await
549+
.expect("publish archived snapshot");
550+
let archived_snapshot = state
551+
.db
552+
.query_events(&EventQuery {
553+
kinds: Some(vec![buzz_core::kind::KIND_IA_ARCHIVED_LIST as i32]),
554+
pubkey: Some(state.relay_keypair.public_key().to_bytes().to_vec()),
555+
global_only: true,
556+
limit: Some(1),
557+
..EventQuery::for_community(tenant.community())
558+
})
559+
.await
560+
.expect("query archived snapshot")
561+
.into_iter()
562+
.next()
563+
.expect("archived snapshot exists");
564+
565+
state
566+
.db
567+
.unarchive(tenant.community(), &target_hex)
568+
.await
569+
.expect("unarchive identity");
570+
publish_nipia_archival_list(&tenant, &state)
571+
.await
572+
.expect("publish unarchived snapshot");
573+
let final_snapshot = state
574+
.db
575+
.query_events(&EventQuery {
576+
kinds: Some(vec![buzz_core::kind::KIND_IA_ARCHIVED_LIST as i32]),
577+
pubkey: Some(state.relay_keypair.public_key().to_bytes().to_vec()),
578+
global_only: true,
579+
limit: Some(1),
580+
..EventQuery::for_community(tenant.community())
581+
})
582+
.await
583+
.expect("query final snapshot")
584+
.into_iter()
585+
.next()
586+
.expect("final snapshot exists");
587+
588+
assert!(
589+
final_snapshot.event.created_at > archived_snapshot.event.created_at,
590+
"replacement snapshots must not rely on random same-second event-id ordering"
591+
);
592+
assert!(
593+
!final_snapshot.event.tags.iter().any(|tag| {
594+
let fields = tag.as_slice();
595+
fields.first().map(String::as_str) == Some("p")
596+
&& fields.get(1).map(String::as_str) == Some(target_hex.as_str())
597+
}),
598+
"final snapshot must reflect the canonical empty archive set"
599+
);
600+
}
601+
515602
#[tokio::test]
516603
async fn owner_archive_rejects_stale_request_after_live_kind0_owner_flip() {
517604
let Some(pool) = test_pool().await else {

‎crates/buzz-relay/src/handlers/side_effects.rs‎

Lines changed: 68 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -3120,29 +3120,70 @@ pub async fn publish_nipia_archival_list(
31203120
tenant: &TenantContext,
31213121
state: &Arc<AppState>,
31223122
) -> anyhow::Result<()> {
3123-
let archived = state.db.list_archived(tenant.community()).await?;
3124-
let relay_pubkey_hex = state.relay_keypair.public_key().to_hex();
3123+
const MAX_REPLACEMENT_ATTEMPTS: usize = 8;
3124+
let relay_pubkey = state.relay_keypair.public_key();
3125+
let relay_pubkey_hex = relay_pubkey.to_hex();
3126+
3127+
// A concurrent archive mutation can race between reading the current head and
3128+
// replacing it. Rebuild from canonical state on rejection so an older snapshot
3129+
// can never strand the final archive set.
3130+
for _ in 0..MAX_REPLACEMENT_ATTEMPTS {
3131+
let archived = state.db.list_archived(tenant.community()).await?;
3132+
let mut tags: Vec<Tag> = Vec::with_capacity(archived.len() + 1);
3133+
tags.push(Tag::parse(["-"]).map_err(|e| anyhow::anyhow!("failed to build '-' tag: {e}"))?);
3134+
3135+
for identity in &archived {
3136+
tags.push(
3137+
Tag::parse(["p", &identity.pubkey])
3138+
.map_err(|e| anyhow::anyhow!("failed to build p tag: {e}"))?,
3139+
);
3140+
}
31253141

3126-
let mut tags: Vec<Tag> = Vec::with_capacity(archived.len() + 1);
3127-
tags.push(Tag::parse(["-"]).map_err(|e| anyhow::anyhow!("failed to build '-' tag: {e}"))?);
3142+
// NIP-16 resolves same-second replacements by event id. Force this
3143+
// canonical snapshot strictly past the current head instead of letting a
3144+
// rapid archive→unarchive randomly preserve the stale archive state.
3145+
let now = nostr::Timestamp::now().as_secs();
3146+
let previous = state
3147+
.db
3148+
.query_events(&buzz_db::event::EventQuery {
3149+
kinds: Some(vec![KIND_IA_ARCHIVED_LIST as i32]),
3150+
pubkey: Some(relay_pubkey.to_bytes().to_vec()),
3151+
limit: Some(1),
3152+
global_only: true,
3153+
..buzz_db::event::EventQuery::for_community(tenant.community())
3154+
})
3155+
.await?;
3156+
let created_at = previous
3157+
.first()
3158+
.map(|event| (event.event.created_at.as_secs() + 1).max(now))
3159+
.unwrap_or(now);
31283160

3129-
for identity in &archived {
3130-
tags.push(
3131-
Tag::parse(["p", &identity.pubkey])
3132-
.map_err(|e| anyhow::anyhow!("failed to build p tag: {e}"))?,
3133-
);
3134-
}
3161+
let event = EventBuilder::new(Kind::Custom(KIND_IA_ARCHIVED_LIST as u16), "")
3162+
.tags(tags)
3163+
.custom_created_at(nostr::Timestamp::from(created_at))
3164+
.sign_with_keys(&state.relay_keypair)
3165+
.map_err(|e| anyhow::anyhow!("failed to sign kind:{KIND_IA_ARCHIVED_LIST}: {e}"))?;
31353166

3136-
let event = EventBuilder::new(Kind::Custom(KIND_IA_ARCHIVED_LIST as u16), "")
3137-
.tags(tags)
3138-
.sign_with_keys(&state.relay_keypair)
3139-
.map_err(|e| anyhow::anyhow!("failed to sign kind:{KIND_IA_ARCHIVED_LIST}: {e}"))?;
3167+
let (stored, was_inserted) = state
3168+
.db
3169+
.replace_addressable_event(tenant.community(), &event, None)
3170+
.await?;
3171+
if !was_inserted {
3172+
continue;
3173+
}
3174+
3175+
let current_archived = state.db.list_archived(tenant.community()).await?;
3176+
let snapshot_is_current =
3177+
archived
3178+
.iter()
3179+
.map(|identity| identity.pubkey.as_str())
3180+
.eq(current_archived
3181+
.iter()
3182+
.map(|identity| identity.pubkey.as_str()));
3183+
if !snapshot_is_current {
3184+
continue;
3185+
}
31403186

3141-
let (stored, was_inserted) = state
3142-
.db
3143-
.replace_addressable_event(tenant.community(), &event, None)
3144-
.await?;
3145-
if was_inserted {
31463187
dispatch_persistent_event(
31473188
tenant,
31483189
state,
@@ -3152,13 +3193,16 @@ pub async fn publish_nipia_archival_list(
31523193
None,
31533194
)
31543195
.await;
3196+
info!(
3197+
archived_count = archived.len(),
3198+
"NIP-IA archived identities list published"
3199+
);
3200+
return Ok(());
31553201
}
31563202

3157-
info!(
3158-
archived_count = archived.len(),
3159-
"NIP-IA archived identities list published"
3160-
);
3161-
Ok(())
3203+
anyhow::bail!(
3204+
"failed to publish kind:{KIND_IA_ARCHIVED_LIST} after {MAX_REPLACEMENT_ATTEMPTS} concurrent replacements"
3205+
)
31623206
}
31633207

31643208
/// NIP-DV: publish the relay-signed, per-viewer DM visibility snapshot for

0 commit comments

Comments
 (0)