Skip to content

Commit c8cd333

Browse files
npub1jmc9dt2lyvzu3h0kxlwxt5zg4fxp9476awyxw6gwxn72g6cw7exqs64whmTyler Longwell
andcommitted
rewrite(search): ChannelScope enum closes ChannelLessOnly fence hole
The legacy 2x2 `(channel_ids: Option<Vec<Uuid>>, include_channel_less: bool)` shape could not unambiguously express "channel-less events only" — both `Some(vec![]) + true` and `None + true` fell into the no-constraint branch, silently broadening to all community channels rather than restricting to `channel_id IS NULL`. That matched the legacy Typesense `channel_id:=__global__` sentinel one way (per-channel + global) but not the other (global only). Replace with a single `ChannelScope` enum whose four variants are 1-to-1 with the legacy `(accessible_channels, include_global)` matrix: - non-empty + true -> ChannelsOrChannelLess(accessible) - non-empty + false -> Channels(accessible) - empty + true -> ChannelLessOnly (the variant the old shape could not express) - empty + false -> caller short-circuits to EOSE, doesn't call search Emitted SQL fragments are byte-identical to the legacy match for the three carry-over cases; `ChannelLessOnly` adds `AND channel_id IS NULL` — the fence the old type could not express. Verification: - Full package `cargo test -p buzz-search -- --include-ignored --test-threads=1`: 9/9 green (8 existing + 1 new `channel_less_only_excludes_per_channel_events`). - Adversarial mutation: replaced the `ChannelLessOnly` SQL emission with a no-op (the buggy semantic the old shape produced); new test went RED with 3 hits instead of 1, restored, green again. The fix is the emitted predicate, not the variant name. - clippy -D warnings clean; fmt clean. - Empty-vec edge cases are intentionally not special-cased: `Channels(vec![])` emits `channel_id = ANY('{}')` (false-for-all, zero hits, preserves the old early-return semantic via SQL); `ChannelsOrChannelLess(vec![])` is equivalent to `ChannelLessOnly`. Coordinated with Eva ahead of relay-wiring sweep at req.rs and bridge.rs so call sites land against the final type, not the buggy one. Co-authored-by: Tyler Longwell <[email protected]> Signed-off-by: Tyler Longwell <[email protected]>
1 parent e31c098 commit c8cd333

3 files changed

Lines changed: 168 additions & 64 deletions

File tree

‎crates/buzz-search/src/lib.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ pub mod query;
2828

2929
pub use buzz_core::CommunityId;
3030
pub use error::SearchError;
31-
pub use query::{search, SearchHit, SearchQuery, SearchResult};
31+
pub use query::{search, ChannelScope, SearchHit, SearchQuery, SearchResult};
3232

3333
use sqlx::PgPool;
3434

‎crates/buzz-search/src/query.rs‎

Lines changed: 61 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,44 @@ use uuid::Uuid;
1414

1515
use crate::error::SearchError;
1616

17+
/// Channel-scope filter for a community-scoped FTS query.
18+
///
19+
/// Four variants, 1-to-1 with the legacy `(accessible_channels: &[Uuid],
20+
/// include_global: bool)` matrix from the Typesense relay:
21+
///
22+
/// | accessible | include_global | `ChannelScope` |
23+
/// |---|---|---|
24+
/// | non-empty | true | `ChannelsOrChannelLess(accessible)` |
25+
/// | non-empty | false | `Channels(accessible)` |
26+
/// | empty | true | `ChannelLessOnly` |
27+
/// | empty | false | (don't call — caller short-circuits to EOSE) |
28+
///
29+
/// `ChannelLessOnly` is the variant that the old `Option<Vec<Uuid>>` +
30+
/// `bool` 2x2 could not express unambiguously: with empty accessible
31+
/// channels and `include_global=true`, both `Some(vec![]) + true` and
32+
/// `None + true` would broaden to all community channels rather than
33+
/// restrict to channel-less events. The enum closes that hole at the
34+
/// type level.
35+
///
36+
/// Empty-vec edge cases are intentionally not special-cased:
37+
/// `Channels(vec![])` emits `channel_id = ANY('{}')` which Postgres
38+
/// evaluates as false-for-all-rows (zero hits), and
39+
/// `ChannelsOrChannelLess(vec![])` emits `(channel_id = ANY('{}') OR
40+
/// channel_id IS NULL)` which is equivalent to `ChannelLessOnly`.
41+
#[derive(Debug, Clone)]
42+
pub enum ChannelScope {
43+
/// No channel constraint. Matches every event in the community.
44+
Any,
45+
/// Restrict to `channel_id IS NULL` events only — what the legacy
46+
/// Typesense `channel_id:=__global__` sentinel meant.
47+
ChannelLessOnly,
48+
/// Restrict to events whose `channel_id` is in this list.
49+
Channels(Vec<Uuid>),
50+
/// Restrict to events whose `channel_id` is in this list, OR are
51+
/// channel-less (`channel_id IS NULL`).
52+
ChannelsOrChannelLess(Vec<Uuid>),
53+
}
54+
1755
/// A community-scoped FTS query.
1856
///
1957
/// The community is REQUIRED at the type level — there is no construction path
@@ -26,15 +64,11 @@ pub struct SearchQuery {
2664
/// NIP-50 search text. Empty string is rejected by `search()` early
2765
/// (no hits, no SQL roundtrip).
2866
pub q: String,
29-
/// Restrict hits to one of these channel UUIDs. `None` = no channel
30-
/// constraint (community-global within the community). An empty `Some(vec![])`
31-
/// is also treated as "no channel constraint" — call sites that mean
32-
/// "no channels are accessible" must short-circuit before calling.
33-
pub channel_ids: Option<Vec<Uuid>>,
34-
/// If `true`, include channel-less events (channel_id IS NULL) in addition
35-
/// to any `channel_ids` filter. If `channel_ids` is `None`, this is
36-
/// implicitly satisfied. Maps to today's `__global__` sentinel semantic.
37-
pub include_channel_less: bool,
67+
/// How to scope hits by channel. See [`ChannelScope`] — the four variants
68+
/// are 1-to-1 with the legacy `(accessible_channels, include_global)`
69+
/// matrix, and `ChannelLessOnly` closes the gap where "empty accessible
70+
/// channels + include global" used to silently broaden to all channels.
71+
pub channel_scope: ChannelScope,
3872
/// NIP-01 kinds filter. None = no kind constraint.
3973
pub kinds: Option<Vec<i32>>,
4074
/// NIP-01 authors filter (32-byte pubkeys). None = no author constraint.
@@ -127,35 +161,26 @@ pub async fn search(pool: &PgPool, query: &SearchQuery) -> Result<SearchResult,
127161
qb.push_bind(*query.community.as_uuid());
128162
qb.push(" AND deleted_at IS NULL AND search_tsv @@ query");
129163

130-
// Channel scope. Three shapes:
131-
// - channel_ids = Some([..]) + include_channel_less = true: (channel_id = ANY($) OR channel_id IS NULL)
132-
// - channel_ids = Some([..]) + include_channel_less = false: channel_id = ANY($)
133-
// - channel_ids = None + include_channel_less = true: (no constraint — also covers None/false for callers
134-
// that explicitly want "no channel scope at all")
135-
// - channel_ids = None + include_channel_less = false: caller meant "nothing accessible" but didn't
136-
// short-circuit; we conservatively return no hits
137-
match (&query.channel_ids, query.include_channel_less) {
138-
(Some(ids), include_global) if !ids.is_empty() => {
139-
qb.push(" AND (channel_id = ANY(");
140-
qb.push_bind(ids.clone());
141-
if include_global {
142-
qb.push(") OR channel_id IS NULL)");
143-
} else {
144-
qb.push("))");
145-
}
164+
// Channel scope — see `ChannelScope` doc for the four-case mapping. The
165+
// emitted SQL fragments are identical to the legacy 2x2 tuple for the
166+
// three carry-over cases; `ChannelLessOnly` is the new fence that the
167+
// old shape could not express.
168+
match &query.channel_scope {
169+
ChannelScope::Any => {
170+
// No channel constraint.
146171
}
147-
(Some(_), true) | (None, true) => {
148-
// No channel constraint — include everything in the community.
149-
// (channel_ids = Some(empty) falls here because no IDs to filter
150-
// by and channel-less events are included.)
172+
ChannelScope::ChannelLessOnly => {
173+
qb.push(" AND channel_id IS NULL");
151174
}
152-
(Some(_), false) | (None, false) => {
153-
// Caller said "no accessible channels and exclude channel-less" —
154-
// produces an empty result.
155-
return Ok(SearchResult {
156-
hits: Vec::new(),
157-
page,
158-
});
175+
ChannelScope::Channels(ids) => {
176+
qb.push(" AND channel_id = ANY(");
177+
qb.push_bind(ids.clone());
178+
qb.push(")");
179+
}
180+
ChannelScope::ChannelsOrChannelLess(ids) => {
181+
qb.push(" AND (channel_id = ANY(");
182+
qb.push_bind(ids.clone());
183+
qb.push(") OR channel_id IS NULL)");
159184
}
160185
}
161186

‎crates/buzz-search/tests/fts_integration.rs‎

Lines changed: 106 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
//! parallel-safe.
88
99
use buzz_core::CommunityId;
10-
use buzz_search::{SearchQuery, SearchService};
10+
use buzz_search::{ChannelScope, SearchQuery, SearchService};
1111
use sqlx::{postgres::PgPoolOptions, Executor, PgPool};
1212
use uuid::Uuid;
1313

@@ -136,8 +136,7 @@ async fn search_finds_event_in_same_community() {
136136
.search(&SearchQuery {
137137
community: c_a,
138138
q: "wonderland".into(),
139-
channel_ids: None,
140-
include_channel_less: true,
139+
channel_scope: ChannelScope::Any,
141140
kinds: None,
142141
authors: None,
143142
since: None,
@@ -184,8 +183,7 @@ async fn search_does_not_return_other_community_events() {
184183
.search(&SearchQuery {
185184
community: c_a,
186185
q: "unique-token-xyz".into(),
187-
channel_ids: None,
188-
include_channel_less: true,
186+
channel_scope: ChannelScope::Any,
189187
kinds: None,
190188
authors: None,
191189
since: None,
@@ -201,8 +199,7 @@ async fn search_does_not_return_other_community_events() {
201199
.search(&SearchQuery {
202200
community: c_b,
203201
q: "unique-token-xyz".into(),
204-
channel_ids: None,
205-
include_channel_less: true,
202+
channel_scope: ChannelScope::Any,
206203
kinds: None,
207204
authors: None,
208205
since: None,
@@ -245,8 +242,7 @@ async fn kind0_search_by_display_name_works_without_flattening() {
245242
.search(&SearchQuery {
246243
community: c,
247244
q: q.to_string(),
248-
channel_ids: None,
249-
include_channel_less: true,
245+
channel_scope: ChannelScope::Any,
250246
kinds: Some(vec![0]),
251247
authors: None,
252248
since: None,
@@ -324,8 +320,7 @@ async fn channel_scope_restricts_results() {
324320
.search(&SearchQuery {
325321
community: c,
326322
q: "shared-token".into(),
327-
channel_ids: Some(vec![ch_a]),
328-
include_channel_less: false,
323+
channel_scope: ChannelScope::Channels(vec![ch_a]),
329324
kinds: None,
330325
authors: None,
331326
since: None,
@@ -343,8 +338,7 @@ async fn channel_scope_restricts_results() {
343338
.search(&SearchQuery {
344339
community: c,
345340
q: "shared-token".into(),
346-
channel_ids: Some(vec![ch_a]),
347-
include_channel_less: true,
341+
channel_scope: ChannelScope::ChannelsOrChannelLess(vec![ch_a]),
348342
kinds: None,
349343
authors: None,
350344
since: None,
@@ -361,8 +355,7 @@ async fn channel_scope_restricts_results() {
361355
.search(&SearchQuery {
362356
community: c,
363357
q: "shared-token".into(),
364-
channel_ids: None,
365-
include_channel_less: true,
358+
channel_scope: ChannelScope::Any,
366359
kinds: None,
367360
authors: None,
368361
since: None,
@@ -379,8 +372,7 @@ async fn channel_scope_restricts_results() {
379372
.search(&SearchQuery {
380373
community: c,
381374
q: "shared-token".into(),
382-
channel_ids: Some(vec![]),
383-
include_channel_less: false,
375+
channel_scope: ChannelScope::Channels(vec![]),
384376
kinds: None,
385377
authors: None,
386378
since: None,
@@ -418,8 +410,7 @@ async fn deleted_events_are_excluded() {
418410
.search(&SearchQuery {
419411
community: c,
420412
q: "deleted-token-q".into(),
421-
channel_ids: None,
422-
include_channel_less: true,
413+
channel_scope: ChannelScope::Any,
423414
kinds: None,
424415
authors: None,
425416
since: None,
@@ -449,8 +440,7 @@ async fn empty_query_returns_empty_result_no_roundtrip() {
449440
.search(&SearchQuery {
450441
community: c,
451442
q: q.into(),
452-
channel_ids: None,
453-
include_channel_less: true,
443+
channel_scope: ChannelScope::Any,
454444
kinds: None,
455445
authors: None,
456446
since: None,
@@ -516,8 +506,7 @@ async fn since_until_filters() {
516506
.search(&SearchQuery {
517507
community: c,
518508
q: "time-token-zz".into(),
519-
channel_ids: None,
520-
include_channel_less: true,
509+
channel_scope: ChannelScope::Any,
521510
kinds: None,
522511
authors: None,
523512
since: Some(1_700_005_000),
@@ -560,8 +549,7 @@ async fn pagination_works() {
560549
.search(&SearchQuery {
561550
community: c,
562551
q: "page-token-qq".into(),
563-
channel_ids: None,
564-
include_channel_less: true,
552+
channel_scope: ChannelScope::Any,
565553
kinds: None,
566554
authors: None,
567555
since: None,
@@ -577,8 +565,7 @@ async fn pagination_works() {
577565
.search(&SearchQuery {
578566
community: c,
579567
q: "page-token-qq".into(),
580-
channel_ids: None,
581-
include_channel_less: true,
568+
channel_scope: ChannelScope::Any,
582569
kinds: None,
583570
authors: None,
584571
since: None,
@@ -596,3 +583,95 @@ async fn pagination_works() {
596583

597584
teardown(pool, &schema).await;
598585
}
586+
587+
#[tokio::test]
588+
#[ignore = "requires Postgres"]
589+
async fn channel_less_only_excludes_per_channel_events() {
590+
// Closes the row-3 fence hole: in the legacy 2x2 shape, both
591+
// `Some(vec![]) + true` and `None + true` silently broadened to all
592+
// community channels rather than restricting to channel-less events.
593+
// `ChannelScope::ChannelLessOnly` is the variant that the old type
594+
// could not express.
595+
//
596+
// Adversarial check: mutate this test's expectation to `>= 2` and the
597+
// assertion goes red against the new SQL `AND channel_id IS NULL`,
598+
// proving the predicate bites. Mutate `query.rs` `ChannelLessOnly` arm
599+
// to a no-op (the `Any` semantic the old code emitted) and this test
600+
// also goes red — three hits instead of one — proving the fix is the
601+
// emitted predicate, not the variant name.
602+
let (pool, schema) = setup().await;
603+
604+
let c = mk_community(&pool, "a.example").await;
605+
let ch_a = Uuid::new_v4();
606+
let ch_b = Uuid::new_v4();
607+
sqlx::query("INSERT INTO channels (community_id, id, name, channel_type, created_by) VALUES ($1, $2, $3, 'stream'::channel_type, $4), ($1, $5, $6, 'stream'::channel_type, $4)")
608+
.bind(c.as_uuid())
609+
.bind(ch_a)
610+
.bind("ch-a")
611+
.bind(b"\x01".repeat(32))
612+
.bind(ch_b)
613+
.bind("ch-b")
614+
.execute(&pool)
615+
.await
616+
.expect("insert channels");
617+
618+
let pk = rand_bytes32();
619+
insert_event(
620+
&pool,
621+
c,
622+
rand_bytes32(),
623+
pk,
624+
1,
625+
"fence-token in ch-a",
626+
Some(ch_a),
627+
1_700_000_000,
628+
)
629+
.await;
630+
insert_event(
631+
&pool,
632+
c,
633+
rand_bytes32(),
634+
pk,
635+
1,
636+
"fence-token in ch-b",
637+
Some(ch_b),
638+
1_700_000_001,
639+
)
640+
.await;
641+
insert_event(
642+
&pool,
643+
c,
644+
rand_bytes32(),
645+
pk,
646+
1,
647+
"fence-token channel-less",
648+
None,
649+
1_700_000_002,
650+
)
651+
.await;
652+
653+
let svc = SearchService::new(pool.clone());
654+
655+
let r = svc
656+
.search(&SearchQuery {
657+
community: c,
658+
q: "fence-token".into(),
659+
channel_scope: ChannelScope::ChannelLessOnly,
660+
kinds: None,
661+
authors: None,
662+
since: None,
663+
until: None,
664+
page: 1,
665+
per_page: 10,
666+
})
667+
.await
668+
.unwrap();
669+
assert_eq!(
670+
r.hits.len(),
671+
1,
672+
"ChannelLessOnly must return only the channel_id IS NULL row"
673+
);
674+
assert_eq!(r.hits[0].channel_id, None);
675+
676+
teardown(pool, &schema).await;
677+
}

0 commit comments

Comments
 (0)