From e0526e62c8f70a1b55b50e0f2d5d160337197c34 Mon Sep 17 00:00:00 2001 From: Tom Brow Date: Wed, 18 Nov 2026 15:53:32 -0800 Subject: [PATCH 1/2] perf(workflows): bound verified mention alias cost Skip mention resolution when the rendered text has no @, project only the three verified name tags in SQL instead of parsing whole kind:30382 events, deduplicate folded aliases per member, try names only at mention anchors, and read verified names only where the community advertises verified profiles. Signed-off-by: Tom Brow --- crates/buzz-db/src/runtime/observability.rs | 2 +- crates/buzz-db/src/store/channel_members.rs | 36 +++-- crates/buzz-relay/src/workflow_sink.rs | 144 +++++++++++++++----- 3 files changed, 132 insertions(+), 50 deletions(-) diff --git a/crates/buzz-db/src/runtime/observability.rs b/crates/buzz-db/src/runtime/observability.rs index 0fbce0f63d0..b43a0b594b3 100644 --- a/crates/buzz-db/src/runtime/observability.rs +++ b/crates/buzz-db/src/runtime/observability.rs @@ -1619,7 +1619,7 @@ mod tests { .get_members_for_event_write(test_scope, Uuid::new_v4()) .await; let _ = writer_db - .get_mention_names_for_event_write(test_scope, &[vec![11; 32]]) + .get_mention_names_for_event_write(test_scope, &[vec![11; 32]], true) .await; let _ = writer_db .huddle_started_link_exists_for_event_write( diff --git a/crates/buzz-db/src/store/channel_members.rs b/crates/buzz-db/src/store/channel_members.rs index 62b81eea8e8..8d8633a5a90 100644 --- a/crates/buzz-db/src/store/channel_members.rs +++ b/crates/buzz-db/src/store/channel_members.rs @@ -2736,7 +2736,8 @@ impl Db { get_users_bulk(&self.pool, community_id, pubkeys).await } - /// Fetch ordinary display names and verified name aliases for mention tags. + /// Fetch ordinary display names and, when `include_verified`, verified + /// name aliases for mention tags. /// /// Returns `(name, pubkey_hex)` pairs for the supplied community-local members. /// Keep every alias so the caller can reject names shared by distinct keys. @@ -2745,6 +2746,7 @@ impl Db { &self, community_id: CommunityId, pubkeys: &[Vec], + include_verified: bool, ) -> Result> { if pubkeys.is_empty() { return Ok(Vec::new()); @@ -2756,32 +2758,38 @@ impl Db { .await?; let rows = sqlx::query( r#" - SELECT member.pubkey, u.display_name, v.event + SELECT member.pubkey, u.display_name, + jsonb_path_query_first(v.event, 'strict $.tags[*] ? (@[0] == "display_name")[1]', '{}', true) #>> '{}' AS verified_display_name, + jsonb_path_query_first(v.event, 'strict $.tags[*] ? (@[0] == "username")[1]', '{}', true) #>> '{}' AS verified_username, + jsonb_path_query_first(v.event, 'strict $.tags[*] ? (@[0] == "full_name")[1]', '{}', true) #>> '{}' AS verified_full_name FROM unnest($2::bytea[]) AS member(pubkey) LEFT JOIN users u ON u.community_id = $1 AND u.pubkey = member.pubkey LEFT JOIN nip_fi_profile_heads v - ON v.community_id = $1 AND v.pubkey = encode(member.pubkey, 'hex') + ON $3 AND v.community_id = $1 AND v.pubkey = encode(member.pubkey, 'hex') "#, ) .bind(community_id.as_uuid()) .bind(pubkeys) + .bind(include_verified) .fetch_all(&mut *connection) .await?; + drop(connection); + // One entry per case-folded name and member, so a member whose aliases + // repeat a name does not make the resolver scan for it again. + let mut seen = std::collections::HashSet::new(); let mut names = Vec::new(); for row in rows { let pubkey = hex::encode(row.try_get::, _>("pubkey")?); - if let Some(name) = row.try_get::, _>("display_name")? { - names.push((name, pubkey.clone())); - } - let profile: Option> = row.try_get("event")?; - if let Some(profile) = profile { - for tag in profile.tags.iter() { - let [field, name, ..] = tag.as_slice() else { - continue; - }; - if matches!(field.as_str(), "display_name" | "username" | "full_name") { - names.push((name.clone(), pubkey.clone())); + for column in [ + "display_name", + "verified_display_name", + "verified_username", + "verified_full_name", + ] { + if let Some(name) = row.try_get::, _>(column)? { + if seen.insert((name.to_lowercase(), pubkey.clone())) { + names.push((name, pubkey.clone())); } } } diff --git a/crates/buzz-relay/src/workflow_sink.rs b/crates/buzz-relay/src/workflow_sink.rs index 1e641bd8a57..20069583910 100644 --- a/crates/buzz-relay/src/workflow_sink.rs +++ b/crates/buzz-relay/src/workflow_sink.rs @@ -117,24 +117,33 @@ fn resolve_mention_pubkeys(text: &str, members: &[(String, String)]) -> Vec = Vec::new(); + // Only an `@` at a left boundary can start a mention, so collect those + // positions once and try each name only there. This keeps the cost at + // names × mentions rather than names × text length. + let anchors: Vec = (0..chars.len()) + .filter(|&at| chars[at] == '@' && is_left_boundary(at)) + .collect(); + if anchors.is_empty() { + return out; + } + for (name, _) in &names { let folded_name: Vec = name.chars().collect(); if folded_name.is_empty() { continue; } - let mut at = 0; - while at < chars.len() { - // Anchor on `@` at a left boundary and an unconsumed span; only then - // attempt the fold-match. `name_len` is measured in *original* chars, - // so `at + 1 + name_len` is the true position just past the name. - let name_len = (chars[at] == '@' && is_left_boundary(at) && !consumed[at]) - .then(|| match_name_len(at + 1, &folded_name)) - .flatten() - .filter(|&n| { - chars[at + 1 + n..] - .first() - .is_none_or(|&c| !extends_name(c)) - }); + for &at in &anchors { + // Skip anchors inside a span an earlier (longer) match consumed. + // `name_len` is measured in *original* chars, so `at + 1 + name_len` + // is the true position just past the name. + if consumed[at] { + continue; + } + let name_len = match_name_len(at + 1, &folded_name).filter(|&n| { + chars[at + 1 + n..] + .first() + .is_none_or(|&c| !extends_name(c)) + }); if let Some(name_len) = name_len { let span = 1 + name_len; if let Some(Some(pubkey)) = by_name.get(name) { @@ -143,9 +152,6 @@ fn resolve_mention_pubkeys(text: &str, members: &[(String, String)]) -> Vec> = members.iter().map(|m| m.pubkey.clone()).collect(); - let named_members = state - .db - .get_mention_names_for_event_write(tenant.community(), &member_pubkeys) - .await - .map_err(|e| ActionSinkError::Database(e.to_string()))?; - let agent_mentions_withheld = append_workflow_mention_tags( - &mut tags, - &text, - &authored_text, - may_direct_agents, - &named_members, - )?; + // Text without an `@` cannot name anyone, so it skips the member + // and alias reads entirely. + let agent_mentions_withheld = if text.contains('@') { + let members = state + .db + .get_members_for_event_write(tenant.community(), channel_uuid) + .await + .map_err(|e| ActionSinkError::Database(e.to_string()))?; + let member_pubkeys: Vec> = + members.iter().map(|m| m.pubkey.clone()).collect(); + // Verified names count only where the community advertises + // them, matching profile search; leftover heads stay inert. + let include_verified = crate::verified_profiles::discovery(&state, &tenant) + .await + .is_some(); + let named_members = state + .db + .get_mention_names_for_event_write( + tenant.community(), + &member_pubkeys, + include_verified, + ) + .await + .map_err(|e| ActionSinkError::Database(e.to_string()))?; + append_workflow_mention_tags( + &mut tags, + &text, + &authored_text, + may_direct_agents, + &named_members, + )? + } else { + false + }; let kind = Kind::from(KIND_STREAM_MESSAGE as u16); let event = EventBuilder::new(kind, &text) @@ -1027,6 +1049,25 @@ mod postgres_tests { test_state_with_agent_mentions(buzz_workflow::AgentMentions::Any).await } + /// [`test_state`] with verified profiles advertised for every host, so + /// workflow mentions may resolve verified names. + async fn advertised_test_state() -> Arc { + let state = test_state().await; + let mut advertised = (*state).clone(); + let mut config = (*advertised.config).clone(); + config.relay_private_key = Some(advertised.relay_keypair.secret_key().to_secret_hex()); + config.nip_fi.mode = buzz_auth::NipFiMode::Enforce; + config.nip_fi.communities = + crate::nip_fi_core::test_support::any_host("https://relay.example"); + config.nip_fi.profile_policies = vec![buzz_db::verified_profiles::ProfilePolicy { + issuer: "https://issuer.test".to_owned(), + label: Some("Example".to_owned()), + refresh_seconds: 3600, + }]; + advertised.config = Arc::new(config); + Arc::new(advertised) + } + async fn test_state_with_agent_mentions( agent_mentions: buzz_workflow::AgentMentions, ) -> Arc { @@ -1501,7 +1542,7 @@ mod postgres_tests { #[tokio::test] #[ignore = "requires Postgres"] async fn workflow_send_message_binds_authority_to_authored_mentions() { - let state = test_state().await; + let state = advertised_test_state().await; let author = nostr::Keys::generate(); let author_hex = author.public_key().to_hex(); @@ -1741,6 +1782,7 @@ mod postgres_tests { true, ), ("ambiguous-full-name", "@Alex Example", "", false, false), + ("no-at-sign", "alex, Alex Example", "", false, false), ("verified-nonmember", "@outsider", "", false, false), ("foreign-profile", "@foreign-only", "", false, false), ( @@ -1878,6 +1920,38 @@ mod postgres_tests { ); } + // Same roster without the advertisement: leftover verified heads are + // ignored, so the ordinary name is no longer ambiguous. + let unadvertised = test_state().await; + unadvertised + .workflow_engine + .set_action_sink(Arc::new(RelayActionSink::new(&unadvertised))); + for (name, text, expected) in [ + ("unadvertised-username", "@alex", vec![]), + ( + "unadvertised-ordinary", + "@Alex Example", + vec![twin.to_hex()], + ), + ] { + let id = execute_send_message_workflow( + &unadvertised, + community, + channel.id, + &author_bytes, + name, + text, + "", + ) + .await; + let event = load_event(&id).await; + assert_eq!( + tag_values(&event, "p"), + [vec![author_hex.clone()], expected].concat(), + "{name}: verified names need the advertisement" + ); + } + let p_tag_targets = tag_values(&explicit, "p"); assert!( p_tag_targets.contains(&author_hex), From e1c954bb3979adda9fbcb94b770e1b400aa1c6e4 Mon Sep 17 00:00:00 2001 From: Tom Brow Date: Wed, 18 Nov 2026 18:02:15 -0800 Subject: [PATCH 2/2] fix(workflows): fail the send when verified-profile discovery fails A failed binding lookup made the sink treat verified profiles as not advertised, so an authored verified-only mention lost its tags while the run reported success. Propagate the error like the roster and name reads beside it; discovery() keeps its fail-closed behavior for its other callers. Signed-off-by: Tom Brow --- crates/buzz-relay/src/verified_profiles.rs | 18 +++++++++++++----- crates/buzz-relay/src/workflow_sink.rs | 5 ++++- 2 files changed, 17 insertions(+), 6 deletions(-) diff --git a/crates/buzz-relay/src/verified_profiles.rs b/crates/buzz-relay/src/verified_profiles.rs index 22d62059fad..50031602aae 100644 --- a/crates/buzz-relay/src/verified_profiles.rs +++ b/crates/buzz-relay/src/verified_profiles.rs @@ -118,6 +118,16 @@ pub(crate) async fn discovery( state: &AppState, tenant: &TenantContext, ) -> Option { + try_discovery(state, tenant).await.ok().flatten() +} + +/// [`discovery`], but a failed binding lookup is an error rather than +/// "not advertised", for callers that must not mistake an outage for the +/// feature being off. +pub(crate) async fn try_discovery( + state: &AppState, + tenant: &TenantContext, +) -> Result, buzz_db::DbError> { let mut count = 0; for policy in enabled_policies(state) { let authorized = match state.config.nip_fi.source { @@ -130,9 +140,7 @@ pub(crate) async fn discovery( CommunitySource::Database => state .db .lookup_nip_fi_binding_by_host(tenant.host()) - .await - .ok() - .flatten() + .await? .is_some_and(|b| b.active && b.issuers.contains(&policy.issuer)), }; if authorized { @@ -140,7 +148,7 @@ pub(crate) async fn discovery( } } // `searchable`: `POST /profiles/search` also matches and returns these. - (count > 0).then( + Ok((count > 0).then( || serde_json::json!({"kind": 30382, "multiple_issuers": count > 1, "searchable": true}), - ) + )) } diff --git a/crates/buzz-relay/src/workflow_sink.rs b/crates/buzz-relay/src/workflow_sink.rs index 20069583910..a6f69697a7f 100644 --- a/crates/buzz-relay/src/workflow_sink.rs +++ b/crates/buzz-relay/src/workflow_sink.rs @@ -540,8 +540,11 @@ impl ActionSink for RelayActionSink { members.iter().map(|m| m.pubkey.clone()).collect(); // Verified names count only where the community advertises // them, matching profile search; leftover heads stay inert. - let include_verified = crate::verified_profiles::discovery(&state, &tenant) + // A failed lookup fails the send like the reads around it, + // rather than silently dropping verified-only mentions. + let include_verified = crate::verified_profiles::try_discovery(&state, &tenant) .await + .map_err(|e| ActionSinkError::Database(e.to_string()))? .is_some(); let named_members = state .db