Skip to content

Commit 9a56db1

Browse files
murderbotclaude
andcommitted
fix(relay): index artifact mentions and match #d before LIMIT
- Artifact writes insert `p`-tag mentions in the same transaction as the revision, so generic `#p` replay and COUNT find what live subscribers already saw. - Filters over kind 45010 alone push `#d` into SQL via JSONB containment. Artifacts are not NIP-33, so `d_tag` is NULL and the Rust post-filter ran after LIMIT, dropping identity lookups. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: murderbot <3754f8729004d95654c46dbab3129e4ab9ef05cc2534e2a3fbfc155983bd637b@buzz.block.builderlab.xyz>
1 parent a686d9e commit 9a56db1

4 files changed

Lines changed: 123 additions & 0 deletions

File tree

‎crates/buzz-db/src/store/artifact.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -184,6 +184,7 @@ impl Db {
184184
let (stored, _) =
185185
crate::event::insert_event_in_transaction(&mut tx, community, event, Some(env.home))
186186
.await?;
187+
crate::insert_mentions_in_transaction(&mut tx, community, event, Some(env.home)).await?;
187188
let mut accepted = vec![stored];
188189
if let (ArtifactOp::Move, Some(source), Some(prev)) = (env.op, source, &env.prev) {
189190
let removal = removal_marker(relay_keys, env.id, source, prev)?;

‎crates/buzz-db/src/store/event.rs‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,10 @@ pub struct EventQuery {
7878
/// Restrict results to events with an `e` tag referencing any of these event IDs (hex).
7979
/// Uses JSONB containment (`tags @> ...`) against the `tags` column.
8080
pub e_tags: Option<Vec<String>>,
81+
/// Restrict results to events with a `d` tag matching any of these values,
82+
/// via JSONB containment. For non-NIP-33 kinds whose `d_tag` column is NULL
83+
/// (NIP-AR artifacts), so identity lookups match before SQL `LIMIT`.
84+
pub d_tag_values: Option<Vec<String>>,
8185
/// Restrict results to events with an exact custom tag pair.
8286
/// Uses JSONB containment against `tags` before SQL `LIMIT`.
8387
pub custom_tag: Option<(String, String)>,
@@ -139,6 +143,7 @@ impl EventQuery {
139143
authors: None,
140144
ids: None,
141145
e_tags: None,
146+
d_tag_values: None,
142147
custom_tag: None,
143148
channel_ids: None,
144149
channel_ids_include_global: true,
@@ -623,6 +628,20 @@ pub(crate) async fn query_events_on(
623628
}
624629
}
625630

631+
if let Some(ref values) = q.d_tag_values {
632+
if !values.is_empty() {
633+
qb.push(" AND (");
634+
for (i, value) in values.iter().enumerate() {
635+
if i > 0 {
636+
qb.push(" OR ");
637+
}
638+
qb.push(format!("{col_prefix}tags @> "));
639+
qb.push_bind(serde_json::json!([["d", value]]));
640+
}
641+
qb.push(")");
642+
}
643+
}
644+
626645
if let Some((ref name, ref value)) = q.custom_tag {
627646
let containment = serde_json::json!([[name, value]]);
628647
qb.push(format!(" AND {col_prefix}tags @> "))
@@ -898,6 +917,20 @@ pub(crate) async fn count_events_on(conn: &mut sqlx::PgConnection, q: &EventQuer
898917
}
899918
}
900919

920+
if let Some(ref values) = q.d_tag_values {
921+
if !values.is_empty() {
922+
qb.push(" AND (");
923+
for (i, value) in values.iter().enumerate() {
924+
if i > 0 {
925+
qb.push(" OR ");
926+
}
927+
qb.push(format!("{col_prefix}tags @> "));
928+
qb.push_bind(serde_json::json!([["d", value]]));
929+
}
930+
qb.push(")");
931+
}
932+
}
933+
901934
if let Some(s) = q.since {
902935
qb.push(format!(" AND {col_prefix}created_at >= "))
903936
.push_bind(s);

‎crates/buzz-relay/src/api/artifact_postgres_tests.rs‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -317,3 +317,60 @@ async fn writes_use_channel_gates_for_home_and_move_source() {
317317
assert!(!status.is_success() || body["accepted"] == false, "{body}");
318318
assert!(body.to_string().contains("archived"), "{body}");
319319
}
320+
321+
/// Re-sign an artifact revision with extra tags and an explicit timestamp.
322+
fn resign(event: &Event, key: &Keys, extra: &[[&str; 2]], created_at: u64) -> Event {
323+
EventBuilder::new(event.kind, event.content.clone())
324+
.tags(
325+
event
326+
.tags
327+
.iter()
328+
.cloned()
329+
.chain(extra.iter().map(|t| Tag::parse(*t).unwrap())),
330+
)
331+
.custom_created_at(nostr::Timestamp::from(created_at))
332+
.sign_with_keys(key)
333+
.unwrap()
334+
}
335+
336+
#[tokio::test]
337+
#[ignore = "requires Postgres"]
338+
async fn generic_p_reads_find_mentioned_artifacts() {
339+
let f = Fixture::new().await;
340+
let tagged = f.peer.public_key().to_hex();
341+
let create = f.revision(Uuid::new_v4(), "create", None);
342+
let create = resign(
343+
&create,
344+
&f.owner,
345+
&[["p", &tagged]],
346+
create.created_at.as_secs(),
347+
);
348+
f.publish(&create).await;
349+
let filter = json!([{"kinds":[45010],"#h":[f.home],"#p":[tagged]}]);
350+
let (status, body) = f.request("/query", filter.clone()).await;
351+
assert!(status.is_success(), "{status}: {body}");
352+
assert_eq!(body.as_array().unwrap().len(), 1, "{body}");
353+
assert_eq!(body[0]["id"], create.id.to_hex());
354+
let (status, body) = f.request("/count", filter).await;
355+
assert!(status.is_success(), "{status}: {body}");
356+
assert_eq!(body["count"], 1, "{body}");
357+
}
358+
359+
#[tokio::test]
360+
#[ignore = "requires Postgres"]
361+
async fn generic_d_lookup_matches_before_limit() {
362+
let f = Fixture::new().await;
363+
let (a, b) = (Uuid::new_v4(), Uuid::new_v4());
364+
let now = nostr::Timestamp::now().as_secs();
365+
let older = resign(&f.revision(a, "create", None), &f.owner, &[], now - 60);
366+
f.publish(&older).await;
367+
f.publish(&f.revision(b, "create", None)).await;
368+
let filter = json!([{"kinds":[45010],"#h":[f.home],"#d":[a],"limit":1}]);
369+
let (status, body) = f.request("/query", filter.clone()).await;
370+
assert!(status.is_success(), "{status}: {body}");
371+
assert_eq!(body.as_array().unwrap().len(), 1, "{body}");
372+
assert_eq!(body[0]["id"], older.id.to_hex());
373+
let (status, body) = f.request("/count", filter).await;
374+
assert!(status.is_success(), "{status}: {body}");
375+
assert_eq!(body["count"], 1, "{body}");
376+
}

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

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1056,6 +1056,19 @@ fn filter_to_query_params(
10561056
} else {
10571057
(None, None)
10581058
};
1059+
// NIP-AR artifacts carry their stable identity in `d` but are not NIP-33,
1060+
// so `d_tag` stays NULL; match the tag itself before `LIMIT`.
1061+
let filter_is_artifact_only = kinds.as_ref().is_some_and(|ks| {
1062+
!ks.is_empty()
1063+
&& ks
1064+
.iter()
1065+
.all(|&k| k as u32 == buzz_core::kind::KIND_ARTIFACT)
1066+
});
1067+
let d_tag_values = filter_is_artifact_only
1068+
.then(|| filter.generic_tags.get(&d_tag_key))
1069+
.flatten()
1070+
.filter(|values| !values.is_empty())
1071+
.map(|values| values.iter().map(|v| v.to_string()).collect());
10591072

10601073
EventQuery {
10611074
channel_id,
@@ -1070,6 +1083,7 @@ fn filter_to_query_params(
10701083
authors,
10711084
ids,
10721085
e_tags,
1086+
d_tag_values,
10731087
..EventQuery::for_community(community)
10741088
}
10751089
}
@@ -1742,6 +1756,24 @@ mod tests {
17421756
.expect("max_limit") as i64
17431757
}
17441758

1759+
#[test]
1760+
fn artifact_d_filter_is_pushed_before_limit() {
1761+
let community = buzz_core::tenant::CommunityId::from_uuid(uuid::Uuid::new_v4());
1762+
let d = nostr::SingleLetterTag::lowercase(nostr::Alphabet::D);
1763+
let artifact = Filter::new()
1764+
.kind(nostr::Kind::Custom(45010))
1765+
.custom_tag(d, "a")
1766+
.limit(1);
1767+
let q = filter_to_query_params(&artifact, None, community);
1768+
assert_eq!(q.d_tag_values, Some(vec!["a".to_string()]));
1769+
assert_eq!(q.d_tag, None);
1770+
1771+
// Mixed kinds keep the generic post-filter path.
1772+
let mixed = artifact.clone().kind(nostr::Kind::Custom(9));
1773+
let q = filter_to_query_params(&mixed, None, community);
1774+
assert_eq!(q.d_tag_values, None);
1775+
}
1776+
17451777
#[test]
17461778
fn req_filter_limit_clamps_to_advertised_nip11_max_limit() {
17471779
let advertised = advertised_max_limit();

0 commit comments

Comments
 (0)