From a3909acc672619375669dff5274bb8e3cdfdc88b Mon Sep 17 00:00:00 2001 From: Logan Johnson Date: Wed, 14 Oct 2026 19:03:34 -0400 Subject: [PATCH 01/22] feat(relay): match label and creator filters before the page limit (#8176) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 🤖 ## Summary After parts 1 and 2, a client can ask for "channels with label X" or "channels created by key K". But the relay applied these tag filters after it read one page of the newest channel events. So a request such as `{kinds:[39000], #t:["workspace"], limit:10}` could return fewer than 10 channels, or none, while matching channels existed. This PR moves the label and creator match into the database query, before the page limit. Part 3 of 3, stacked on part 2. ### Related issue None found. ### Details - Applies only when every kind in the filter is a relay-signed channel-state kind (39000–39003). Other kinds keep today's behavior. - The database match uses JSONB containment on `tags`, which is GIN-indexed. Containment can match a little too much (for example, a tag that contains both strings in another position), never too little. So the relay still checks each returned event with the normal Nostr filter rules, and `COUNT` requests keep that check too. - The same match is applied to the query path and the count path. - **Spec.** NIP-CL now says that `#t` and `#P` match before `limit`. - **Choosing one channel.** The relay does not make labels unique, so two creates for one label can both succeed, for example when two processes of one agent start at the same time. NIP-CL gets a "Choosing one channel" section: a client that needs one channel per creator and label looks it up with `#P` + `#t`, creates it only if none exists, and otherwise uses the oldest one (the lowest `created_at` tag, then the lowest channel ID). Every reader that follows this rule picks the same channel, even after an edit. ### Testing - Relay test: many channels, one match, small `limit`. The request returns the match for both `#t` and `#P`. This test fails without the change. - Unit test: `#t` and `#P` reach the database query only for channel-state kinds. - Relay test: one creator sends two creates for the same label at once. Both channels exist, a `#P` + `#t` lookup finds both, and the oldest-channel rule picks the same one in either order, even after the older channel's metadata is re-published by an edit. ### Stack These are two stacks. Merge them in this order. Client support (creating, labeling and finding these channels) will be in block/buzz-app, not the buzz SDK and CLI. **Stack 1: channel labels and creator lookup (#8174–#8176)** 1. #8174 channel type and creator tags, and the channel creation time 2. #8175 channel labels 3. #8176 database-side label and creator match, and the rule for choosing one channel ← this PR **Stack 2: system channels (#8180–#8182)**, stacked on stack 1 because it uses labels and the creator tag 4. #8180 the system channel type 5. #8181 leave system channels out of reads that do not name them 6. #8182 channel-state filters opt in to system channels --------- Signed-off-by: Logan Johnson Co-authored-by: Larry <627498bd4bd1f281a16431e3c6cce3b5c25b6692798c78672298aefbf2f8f8b5@buzz.block.builderlab.xyz> --- Justfile | 2 +- crates/buzz-db/src/store/event.rs | 103 +++++- .../handlers/group_state_postgres_tests.rs | 308 ++++++++++++++++++ crates/buzz-relay/src/handlers/req.rs | 89 ++++- docs/nips/NIP-CL.md | 25 ++ scripts/run-tests.sh | 3 +- 6 files changed, 525 insertions(+), 5 deletions(-) diff --git a/Justfile b/Justfile index 312ec115b9..a41427d46c 100644 --- a/Justfile +++ b/Justfile @@ -531,7 +531,7 @@ test-unit: # are infra-free; config parses env into a struct and never connects. # `^config::` is anchored so it does not also select nip_fi_config. cargo nextest run -p buzz-relay --lib --bin buzz-relay \ - -E 'test(/^api::admin::/) + test(/^push_runtime::/) + test(/^operator_listener::tests::/) + test(/^handlers::channel_authz::/) + test(/^handlers::moderation_authz::/) + test(/^handlers::side_effects::tests::/) + test(/^storage_sweep::tests::/) + test(/^nip_fi_core::tests::/) + test(/^nip_fi_http::tests::/) + test(/^nip_fi_config::tests::/) + test(/^readiness::tests::/) + test(/^router::tests::/) + test(/^api::parse_query_tests::/) + test(/^api::git::transport::off_mode_precedence_tests::/) + test(/^audio::join::tests::/) + test(/^audio::handler::tests::/) + test(/^nip_fi_gate::tests::/) + test(/^nip_fi_session::tests::/) + test(/^nip_fi_shadow::tests::/) + test(/^nip_fi_shadow_session::tests::/) + test(/^startup_steps::tests::/) + test(/^telemetry::tests::/) + test(/^config::tests::/) + test(=state::tests::neither_a_confirmed_inactive_community_nor_a_failed_lookup_admits_the_socket) + test(=state::tests::periodic_revalidation_disconnects_inside_the_fenced_callback) + test(=state::tests::bare_community_disconnect_fails_closed_when_the_fence_is_unavailable) + test(=connection::tests::send_loop_sends_policy_close_when_community_is_archived) + test(=state::tests::community_disconnect_then_nip_fi_keeps_community_deleted_reason) + test(=state::tests::disconnect_community_wins_reason_losing_nip_fi_does_not_enqueue_frame) + test(=handlers::req::tests::timed_out_historical_read_deregisters_before_closed) + test(=handlers::req::tests::superseded_timeout_leaves_replacement_intact) + test(=handlers::req::tests::search_claim_retires_live_and_yields_to_replacement) + test(=handlers::req::tests::concurrent_claims_and_stale_teardowns_keep_the_last_owner) + test(=handlers::req::tests::timeout_closed_is_emitted_before_a_replacement_can_claim) + test(=handlers::req::tests::revoke_then_replacement_keeps_replacement_whole) + test(=handlers::req::tests::claims_after_connection_cleanup_are_refused) + test(=handlers::req::tests::dropped_terminal_frame_cancels_connection) + test(=handlers::req::tests::revoke_dropped_terminal_frame_cancels_connection) + test(=handlers::req::tests::count_fallback_covers_filters_that_can_match_private_deletions) + (kind(bin) & (test(/^tests::/) + test(/^composition_tests::/) + test(/^env_filter_tests::/)) - test(/^tests::postgres_tests::/))' + -E 'test(/^api::admin::/) + test(/^push_runtime::/) + test(/^operator_listener::tests::/) + test(/^handlers::channel_authz::/) + test(/^handlers::moderation_authz::/) + test(/^handlers::side_effects::tests::/) + test(/^storage_sweep::tests::/) + test(/^nip_fi_core::tests::/) + test(/^nip_fi_http::tests::/) + test(/^nip_fi_config::tests::/) + test(/^readiness::tests::/) + test(/^router::tests::/) + test(/^api::parse_query_tests::/) + test(/^api::git::transport::off_mode_precedence_tests::/) + test(/^audio::join::tests::/) + test(/^audio::handler::tests::/) + test(/^nip_fi_gate::tests::/) + test(/^nip_fi_session::tests::/) + test(/^nip_fi_shadow::tests::/) + test(/^nip_fi_shadow_session::tests::/) + test(/^startup_steps::tests::/) + test(/^telemetry::tests::/) + test(/^config::tests::/) + test(=state::tests::neither_a_confirmed_inactive_community_nor_a_failed_lookup_admits_the_socket) + test(=state::tests::periodic_revalidation_disconnects_inside_the_fenced_callback) + test(=state::tests::bare_community_disconnect_fails_closed_when_the_fence_is_unavailable) + test(=connection::tests::send_loop_sends_policy_close_when_community_is_archived) + test(=state::tests::community_disconnect_then_nip_fi_keeps_community_deleted_reason) + test(=state::tests::disconnect_community_wins_reason_losing_nip_fi_does_not_enqueue_frame) + test(=handlers::req::tests::timed_out_historical_read_deregisters_before_closed) + test(=handlers::req::tests::superseded_timeout_leaves_replacement_intact) + test(=handlers::req::tests::search_claim_retires_live_and_yields_to_replacement) + test(=handlers::req::tests::concurrent_claims_and_stale_teardowns_keep_the_last_owner) + test(=handlers::req::tests::timeout_closed_is_emitted_before_a_replacement_can_claim) + test(=handlers::req::tests::revoke_then_replacement_keeps_replacement_whole) + test(=handlers::req::tests::claims_after_connection_cleanup_are_refused) + test(=handlers::req::tests::dropped_terminal_frame_cancels_connection) + test(=handlers::req::tests::revoke_dropped_terminal_frame_cancels_connection) + test(=handlers::req::tests::count_fallback_covers_filters_that_can_match_private_deletions) + test(=handlers::req::tests::group_state_t_and_creator_tags_reach_sql_only_for_group_state_kinds) + (kind(bin) & (test(/^tests::/) + test(/^composition_tests::/) + test(/^env_filter_tests::/)) - test(/^tests::postgres_tests::/))' # Note on audio::join::tests scope: the full suite is infra-free (no DB, # no Redis). The infra-free audio/FI regression witnesses — bootstrap # ordering barrier, CommitConfirmed arm, pending-close invisibility, diff --git a/crates/buzz-db/src/store/event.rs b/crates/buzz-db/src/store/event.rs index 183585e278..d1b7874a3b 100644 --- a/crates/buzz-db/src/store/event.rs +++ b/crates/buzz-db/src/store/event.rs @@ -92,6 +92,11 @@ pub struct EventQuery { /// Restrict results to events with an exact custom tag pair. /// Uses JSONB containment against `tags` before SQL `LIMIT`. pub custom_tag: Option<(String, String)>, + /// Restrict results to events that, for every `(name, values)` entry, + /// have a tag whose name is `name` and whose first value is one of + /// `values` (NIP-01 tag matching), before SQL `LIMIT`. Entries with no + /// values are ignored. + pub tag_values: Vec<(String, Vec)>, /// Restrict results to events in any of these channels. By default, /// channel-less global events are retained so this can enforce a viewer's /// accessible-channel scope without hiding global events. Set @@ -152,6 +157,7 @@ impl EventQuery { e_tags: None, d_tag_values: None, custom_tag: None, + tag_values: Vec::new(), channel_ids: None, channel_ids_include_global: true, max_limit: None, @@ -580,7 +586,10 @@ pub(crate) async fn query_events_on( let rows = if q.e_tags.is_some() { fetch_with_e_tag_deadline(conn, &mut qb).await? } else { - qb.build().fetch_all(&mut *conn).await? + qb.build() + .persistent(!has_tag_values(q)) + .fetch_all(&mut *conn) + .await? }; let mut out = Vec::with_capacity(rows.len()); @@ -741,6 +750,8 @@ fn build_query_events_sql(q: &EventQuery) -> QueryBuilder { .push_bind(containment); } + push_tag_value_filters(&mut qb, col_prefix, &q.tag_values); + if let Some(s) = q.since { qb.push(format!(" AND {col_prefix}created_at >= ")) .push_bind(s); @@ -865,6 +876,51 @@ fn push_e_tag_filter(qb: &mut QueryBuilder, col_prefix: &str, e_ .push("::jsonb[])"); } +/// Whether `q` carries a [`EventQuery::tag_values`] match. Such a query runs +/// as an unnamed statement, so Postgres plans it with the bound values. After +/// a few runs, a cached generic plan ignores the value and can scan every +/// group-state row in the community instead of using the `tags` GIN index. +fn has_tag_values(q: &EventQuery) -> bool { + q.tag_values.iter().any(|(_, values)| !values.is_empty()) +} + +/// Two tests per [`EventQuery::tag_values`] entry, so each entry is an OR +/// over its values and entries are ANDed: +/// +/// - `tags @> ANY(...)` lets Postgres use the `tags` GIN index. On its own +/// it over-matches, because JSONB containment ignores order and repeats: +/// `[["t", "stream"]]` contains `[["t", "t"]]`, and `[["name", "t"]]` +/// contains `[["t", "name"]]`. Those false candidates could fill the page +/// before `LIMIT` and hide a real match. +/// - The `EXISTS` test then keeps only rows with a tag whose name is +/// exactly `name` and whose first value is one of `values`. +fn push_tag_value_filters( + qb: &mut QueryBuilder, + col_prefix: &str, + tag_values: &[(String, Vec)], +) { + for (name, values) in tag_values { + if values.is_empty() { + continue; + } + let containments: Vec = values + .iter() + .map(|value| serde_json::json!([[name, value]])) + .collect(); + qb.push(format!(" AND {col_prefix}tags @> ANY(")) + .push_bind(containments) + .push("::jsonb[])"); + qb.push(format!( + " AND EXISTS (SELECT 1 FROM jsonb_array_elements({col_prefix}tags) AS tag \ + WHERE tag->>0 = " + )) + .push_bind(name.clone()) + .push(" AND tag->>1 = ANY(") + .push_bind(values.clone()) + .push("::text[]))"); + } +} + /// Match `#d` on artifact rows before `LIMIT` while leaving other kinds to the /// caller's post-filter: `(kind NOT IN (artifact kinds) OR tags @> [["d", v]] ...)`. fn push_artifact_d_tag_predicate( @@ -1063,6 +1119,8 @@ pub(crate) async fn count_events_on(conn: &mut sqlx::PgConnection, q: &EventQuer push_artifact_d_tag_predicate(&mut qb, col_prefix, values); } + push_tag_value_filters(&mut qb, col_prefix, &q.tag_values); + if let Some(s) = q.since { qb.push(format!(" AND {col_prefix}created_at >= ")) .push_bind(s); @@ -1094,7 +1152,10 @@ pub(crate) async fn count_events_on(conn: &mut sqlx::PgConnection, q: &EventQuer .next() .ok_or_else(|| DbError::InvalidData("COUNT returned no rows".to_string()))? } else { - qb.build().fetch_one(&mut *conn).await? + qb.build() + .persistent(!has_tag_values(q)) + .fetch_one(&mut *conn) + .await? }; let cnt: i64 = row.try_get("cnt")?; @@ -2822,6 +2883,44 @@ mod postgres_tests { id } + /// Statements on `conn` that Postgres holds as prepared, matching `like`. + async fn prepared_like(conn: &mut sqlx::PgConnection, like: &str) -> i64 { + sqlx::query_scalar("SELECT count(*) FROM pg_prepared_statements WHERE statement LIKE $1") + .bind(like) + .fetch_one(&mut *conn) + .await + .expect("read prepared statements") + } + + /// A label or creator match must keep parameter-aware planning. A cached + /// generic plan ignores the label value and scans every group-state row in + /// the community instead of using the `tags` GIN index. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn tag_value_queries_are_not_cached_as_prepared_statements() { + let pool = setup_pool().await; + let community = CommunityId::from_uuid(make_test_community(&pool).await); + let mut conn = pool.acquire().await.expect("acquire"); + sqlx::query("DEALLOCATE ALL") + .execute(&mut *conn) + .await + .expect("clear prepared statements"); + let mut q = EventQuery::for_community(community); + q.kinds = Some(vec![39000]); + q.tag_values = vec![("t".to_owned(), vec!["for-you".to_owned()])]; + for _ in 0..6 { + query_events_on(&mut conn, &q).await.expect("label query"); + count_events_on(&mut conn, &q).await.expect("label count"); + } + assert_eq!(prepared_like(&mut conn, "%tags @> ANY(%").await, 0); + + // Control: the same query without a tag match stays a cached statement, + // so the check above can see one. + q.tag_values.clear(); + query_events_on(&mut conn, &q).await.expect("plain query"); + assert!(prepared_like(&mut conn, "%FROM events%").await > 0); + } + /// Effective `statement_timeout` observed *inside* the e-tag deadline, and /// the value restored on `conn` afterwards. async fn deadline_inside_and_after(conn: &mut sqlx::PgConnection) -> (String, String) { diff --git a/crates/buzz-relay/src/handlers/group_state_postgres_tests.rs b/crates/buzz-relay/src/handlers/group_state_postgres_tests.rs index 6f1e65e5c6..22110190b0 100644 --- a/crates/buzz-relay/src/handlers/group_state_postgres_tests.rs +++ b/crates/buzz-relay/src/handlers/group_state_postgres_tests.rs @@ -489,3 +489,311 @@ async fn admins_can_change_labels() { vec!["stream", "theirs"] ); } + +/// Ensure race: one creator sends two kind:9007s for the same label at +/// once. The relay keeps both channels, a `#P` + `#t` lookup finds both, +/// and every reader that follows the NIP-CL rule picks the same one: the +/// lowest stored creation time, then the lowest ID. +/// Mutation: rank by the 39000's own created_at after an edit, or let the +/// lookup miss one channel → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn racing_creates_resolve_to_the_same_oldest_channel() { + let state = state().await; + let tenant = community(&state, "group-state-ensure-race").await; + let creator = Keys::generate(); + let extra: &[&[&str]] = &[&["t", "ensure-race"]]; + + let (first, second) = tokio::join!( + create_channel(&state, &tenant, &creator, extra), + create_channel(&state, &tenant, &creator, extra), + ); + assert_ne!( + first, second, + "both creates must succeed as separate channels" + ); + + // Edit whichever channel is older so its 39000 becomes the newest event. + // Readers must still pick it, because it was created first. + let created = |id: Uuid| { + let state = state.clone(); + let tenant = tenant.clone(); + async move { + state + .db + .get_channel_for_event_write(tenant.community(), id) + .await + .expect("channel") + .created_at + .timestamp() + } + }; + let mut ranked = [ + (created(first).await, first.to_string()), + (created(second).await, second.to_string()), + ]; + ranked.sort(); + let expected = ranked[0].1.clone(); + tokio::time::sleep(std::time::Duration::from_millis(1_100)).await; + edit_channel( + &state, + &tenant, + &creator, + expected.parse().unwrap(), + &[&["about", "edited after the race"]], + ) + .await + .expect("edit the older channel"); + + // Step 1 of Ensure: the creator's label lookup finds both channels. + let found = req_event_ids( + &state, + &tenant, + &creator, + serde_json::json!({ + "kinds": [39000], + "#P": [creator.public_key().to_hex()], + "#t": ["ensure-race"], + }), + ) + .await; + assert_eq!(found.len(), 2, "lookup must find both channels: {found:?}"); + + let mut events = Vec::new(); + for id in [first, second] { + let stored = state + .db + .query_events(&EventQuery { + kinds: Some(vec![39000]), + d_tag: Some(id.to_string()), + limit: Some(1), + ..EventQuery::for_community(tenant.community()) + }) + .await + .expect("query 39000"); + let event = stored.into_iter().next().expect("39000").event; + assert!( + found.contains(&event.id.to_hex()), + "lookup returned the current 39000" + ); + events.push(event); + } + // NIP-CL "Choosing one channel": the lowest `created_at` tag, then the + // lowest channel ID. The edited channel's event is the newest, so this + // only works if its tag still holds the stored creation time. + let pick = |events: Vec<&nostr::Event>| { + events + .into_iter() + .map(|event| { + let created_at = event + .tags + .iter() + .find_map(|tag| match tag.as_slice() { + [name, value, ..] if name == buzz_core::channel::CHANNEL_CREATED_AT_TAG => { + value.parse::().ok() + } + _ => None, + }) + .expect("created_at tag"); + ( + created_at, + event.tags.identifier().expect("d tag").to_owned(), + ) + }) + .min() + .map(|(_, id)| id) + }; + assert_eq!(pick(vec![&events[0], &events[1]]), Some(expected.clone())); + assert_eq!(pick(vec![&events[1], &events[0]]), Some(expected)); +} + +/// Run one historical REQ as `reader` and return the IDs of the events sent +/// before EOSE. +async fn req_event_ids( + state: &Arc, + tenant: &TenantContext, + reader: &Keys, + filter: serde_json::Value, +) -> Vec { + let (send_tx, mut send_rx) = tokio::sync::mpsc::channel(256); + let (ctrl_tx, _ctrl_rx) = tokio::sync::mpsc::channel(4); + let cancel = tokio_util::sync::CancellationToken::new(); + let conn = Arc::new(crate::connection::ConnectionState { + conn_id: Uuid::new_v4(), + tenant: tenant.clone(), + remote_addr: "127.0.0.1:1234".parse().expect("addr"), + auth_state: std::sync::Mutex::new(crate::connection::AuthState::Authenticated( + buzz_auth::AuthContext { + pubkey: reader.public_key(), + scopes: Vec::new(), + channel_ids: None, + auth_method: buzz_auth::AuthMethod::Nip42, + agent_owner_pubkey: None, + }, + )), + subscriptions: Arc::new(tokio::sync::Mutex::new(Default::default())), + send_tx, + ctrl_tx, + terminal_ctrl_tx: tokio::sync::mpsc::channel(1).0, + cancel: cancel.clone(), + backpressure_count: Arc::new(std::sync::atomic::AtomicU8::new(0)), + grace_limit: 3, + nip_fi_assertion: None, + session_deadline: None, + nip_fi_gate: crate::nip_fi_gate::SessionAdmissionGate::off_mode(cancel.clone()), + community_control: crate::state::CommunityConnectionControl::new(cancel.clone()), + }); + let filter: nostr::Filter = serde_json::from_value(filter).expect("filter"); + crate::handlers::req::handle_req("g".into(), vec![filter], vec![None], conn, state.clone()) + .await; + let mut ids = Vec::new(); + while let Ok(frame) = send_rx.try_recv() { + let axum::extract::ws::Message::Text(text) = frame else { + continue; + }; + let message: serde_json::Value = serde_json::from_str(&text).expect("relay frame"); + match message[0].as_str() { + Some("EVENT") => ids.push(message[2]["id"].as_str().expect("id").to_owned()), + Some("EOSE") => return ids, + other => panic!("unexpected frame {other:?}: {text}"), + } + } + panic!("no EOSE; events so far: {ids:?}"); +} + +/// The current kind:39000 event ID for `channel_id`. +async fn metadata_event_id(state: &AppState, tenant: &TenantContext, channel_id: Uuid) -> String { + state + .db + .query_events(&EventQuery { + kinds: Some(vec![39000]), + d_tag: Some(channel_id.to_string()), + limit: Some(1), + ..EventQuery::for_community(tenant.community()) + }) + .await + .expect("query 39000") + .first() + .expect("kind:39000") + .event + .id + .to_hex() +} + +/// A selective `#t` or `#P` REQ on group-state kinds returns its match even +/// when the match is older than a full page of other channels. The tag +/// match must run in SQL before `LIMIT`, not after it. +/// Mutation: drop `group_state_tag_values` from `filter_to_query_params` → +/// RED (the page holds only the newest unrelated channels). +#[tokio::test] +#[ignore = "requires Postgres"] +async fn selective_label_and_creator_reqs_are_not_starved_by_limit() { + let state = state().await; + let tenant = community(&state, "group-state-pushdown").await; + let needle_creator = Keys::generate(); + let other_creator = Keys::generate(); + let reader = Keys::generate(); + + let needle = create_channel(&state, &tenant, &needle_creator, &[&["t", "needle"]]).await; + // Group-state created_at has one-second resolution, and rows with the + // same second sort by ID, so wait for the next second: then every other + // channel's 39000 is strictly newer than the needle's. + tokio::time::sleep(std::time::Duration::from_millis(1_100)).await; + for _ in 0..6 { + create_channel(&state, &tenant, &other_creator, &[&["t", "hay"]]).await; + } + let expected = vec![metadata_event_id(&state, &tenant, needle).await]; + + assert_eq!( + req_event_ids( + &state, + &tenant, + &reader, + serde_json::json!({"kinds": [39000], "#t": ["needle"], "limit": 2}), + ) + .await, + expected, + "#t label match" + ); + assert_eq!( + req_event_ids( + &state, + &tenant, + &reader, + serde_json::json!({ + "kinds": [39000], + "#P": [needle_creator.public_key().to_hex()], + "limit": 2 + }), + ) + .await, + expected, + "#P creator match" + ); + assert!( + req_event_ids( + &state, + &tenant, + &reader, + serde_json::json!({ + "kinds": [39000], + "#P": [needle_creator.public_key().to_hex()], + "#t": ["hay"], + "limit": 2 + }), + ) + .await + .is_empty(), + "#t and #P must both match" + ); +} + +/// JSONB containment ignores order and repeats, so `[["t", "stream"]]` +/// contains `[["t", "t"]]` and a channel named `t` (`["name", "t"]`) +/// contains `[["t", "name"]]`. Those newer channels must not take the only +/// place in the page from an older channel with the label. +/// Mutation: drop the exact `EXISTS` match from `push_tag_value_filters` → +/// RED (each page holds only the newer channel, which the post-filter drops). +#[tokio::test] +#[ignore = "requires Postgres"] +async fn label_reqs_are_not_starved_by_containment_false_matches() { + let state = state().await; + let tenant = community(&state, "group-state-containment").await; + let creator = Keys::generate(); + let reader = Keys::generate(); + + let labeled_t = create_channel(&state, &tenant, &creator, &[&["t", "t"]]).await; + let labeled_name = create_channel(&state, &tenant, &creator, &[&["t", "name"]]).await; + let expected_t = vec![metadata_event_id(&state, &tenant, labeled_t).await]; + let expected_name = vec![metadata_event_id(&state, &tenant, labeled_name).await]; + // Group-state created_at has one-second resolution; wait so the + // unlabeled channel's 39000 is strictly newer. + tokio::time::sleep(std::time::Duration::from_millis(1_100)).await; + let unlabeled = create_channel(&state, &tenant, &creator, &[]).await; + edit_channel(&state, &tenant, &creator, unlabeled, &[&["name", "t"]]) + .await + .expect("rename to t"); + + assert_eq!( + req_event_ids( + &state, + &tenant, + &reader, + serde_json::json!({"kinds": [39000], "#t": ["t"], "limit": 1}), + ) + .await, + expected_t, + "label t" + ); + assert_eq!( + req_event_ids( + &state, + &tenant, + &reader, + serde_json::json!({"kinds": [39000], "#t": ["name"], "limit": 1}), + ) + .await, + expected_name, + "label name" + ); +} diff --git a/crates/buzz-relay/src/handlers/req.rs b/crates/buzz-relay/src/handlers/req.rs index 7572774b3a..df9fecd761 100644 --- a/crates/buzz-relay/src/handlers/req.rs +++ b/crates/buzz-relay/src/handlers/req.rs @@ -988,7 +988,10 @@ pub fn filter_fully_pushable(filter: &Filter) -> bool { // #e is fully pushed (any count) via JSONB containment. } _ => { - // Any other generic tag (#t, #a, etc.) is not pushed. + // Any other generic tag (#t, #a, etc.) is not pushed exactly. + // #t/#P on group-state kinds are matched in SQL + // (`group_state_tag_values`), but this fast path does not + // model them, so COUNT still post-filters them. if !tag_values.is_empty() { return false; } @@ -1161,6 +1164,8 @@ fn filter_to_query_params( .filter(|values| !values.is_empty()) .map(|values| values.iter().map(|v| v.to_string()).collect()); + let tag_values = group_state_tag_values(filter, kinds.as_deref()); + EventQuery { channel_id, kinds, @@ -1175,10 +1180,50 @@ fn filter_to_query_params( ids, e_tags, d_tag_values, + tag_values, ..EventQuery::for_community(community) } } +/// `#t` (channel type and labels) and `#P` (creator) values to match in SQL +/// before `LIMIT`, when every filter kind is a relay-signed group-state kind +/// (39000–39003). Without this, a page of the newest group-state events is +/// read first and the tag match runs after it, so a selective +/// `{kinds:[39000], #t:[