diff --git a/crates/buzz-search/src/query.rs b/crates/buzz-search/src/query.rs index a2bed24e22..9bbd21c2a8 100644 --- a/crates/buzz-search/src/query.rs +++ b/crates/buzz-search/src/query.rs @@ -199,17 +199,20 @@ fn normalized_search_text(q: &str) -> Option { /// Execute a community-scoped FTS query. /// -/// SQL shape (always): +/// SQL shape (bracketed parts are emitted only for `kinds == [0]`): /// ```sql /// SELECT id, kind, pubkey, channel_id, EXTRACT(EPOCH FROM created_at)::bigint AS created_at_s, /// ts_rank_cd(search_tsv, query) AS rank +/// [, @@ query AS name_match] /// FROM events, /// AS query /// WHERE community_id = $ctx /// AND deleted_at IS NULL /// AND search_tsv @@ query /// [+ channel scope, kinds, authors, since, until] -/// ORDER BY rank DESC, created_at DESC, id +/// ORDER BY [name_match DESC,] +/// [search_tsv @@ websearch_to_tsquery('simple', $q) DESC,] -- prefix mode, ≤ 2 chars +/// rank DESC, created_at DESC, id /// LIMIT $per_page OFFSET (($page - 1) * $per_page) /// ``` /// @@ -232,21 +235,42 @@ pub async fn search(pool: &PgPool, query: &SearchQuery) -> Result = QueryBuilder::new( "SELECT id, kind, pubkey, channel_id, \ EXTRACT(EPOCH FROM created_at)::bigint AS created_at_s, \ - ts_rank_cd(search_tsv, search_query.query) AS rank \ - FROM events CROSS JOIN LATERAL (SELECT ", + ts_rank_cd(search_tsv, search_query.query) AS rank", ); + if profile_query { + // The same tsquery as the WHERE clause, applied to the name fields + // only, so both sides normalize identically. `CASE` skips the `THEN` + // arm when the guard is false, so rows that predate ingest-side JSON + // validation never raise on `::jsonb`; a non-object document yields + // NULL from `->>`, an empty vector, and `false`. `pg_input_is_valid` + // needs PostgreSQL 16 or later. + qb.push( + ", CASE WHEN pg_input_is_valid(content, 'jsonb') \ + THEN to_tsvector('simple', concat_ws(' ', \ + content::jsonb ->> 'name', \ + content::jsonb ->> 'display_name', \ + content::jsonb ->> 'displayName')) @@ search_query.query \ + ELSE false END AS name_match", + ); + } + qb.push(" FROM events CROSS JOIN LATERAL (SELECT "); push_tsquery(&mut qb, query.mode, &search_text); qb.push(" AS query) AS search_query WHERE community_id = "); qb.push_bind(*query.community.as_uuid()); @@ -306,13 +330,16 @@ pub async fn search(pool: &PgPool, query: &SearchQuery) -> Result (PgPool, String) { let url = std::env::var("BUZZ_TEST_DATABASE_URL").unwrap_or_else(|_| TEST_DB_URL.to_string()); // The PostgreSQL lane supplies an isolated desired-state database. Outside @@ -302,6 +302,76 @@ async fn short_kind0_prefix_prioritizes_exact_lexeme_on_a_noisy_page() { teardown(pool, &schema).await; } +/// `search_tsv` tokenizes the whole profile JSON, so a profile whose `about` +/// text repeats a matching word outranks a one-word display name on +/// `ts_rank_cd` alone (twelve weight-D covers score 1.2 against 0.1). Kind-0 +/// queries order rows whose name fields match ahead of body-only matches so +/// the person the typeahead is looking for lands on page 1. +/// +/// Mutate-bite: drop the `name_match DESC` ORDER BY term in `query.rs` and Wes +/// falls behind the four newer, higher-ranked body matches onto page 2. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn kind0_prefix_orders_name_match_before_newer_body_match() { + let (pool, schema) = setup().await; + + let c = mk_community(&pool, "profile-name-first.example").await; + let wes_id = rand_bytes32(); + insert_event( + &pool, + c, + wes_id, + rand_bytes32(), + 0, + r#"{"display_name":"Wes"}"#, + None, + 1_700_000_000, + ) + .await; + + // Newer profiles that match wes:* only through body text, each with a + // higher cover-density rank than a single name lexeme. + let about = ["west"; 12].join(" "); + for i in 0..4 { + insert_event( + &pool, + c, + rand_bytes32(), + rand_bytes32(), + 0, + &format!(r#"{{"name":"Pollen {i}","about":"{about}"}}"#), + None, + 1_700_000_100 + i, + ) + .await; + } + + let svc = SearchService::new(pool.clone()); + let first_page = svc + .search(&SearchQuery { + community: c, + q: "wes".into(), + channel_scope: ChannelScope::Any, + kinds: Some(vec![0]), + authors: None, + since: None, + until: None, + page: 1, + per_page: 3, + mode: buzz_search::SearchMode::Prefix, + }) + .await + .expect("profile prefix search ok"); + + assert_eq!(first_page.hits.len(), 3); + assert_eq!( + first_page.hits[0].event_id, wes_id, + "name match must outrank newer body-only matches" + ); + + teardown(pool, &schema).await; +} + #[tokio::test] #[ignore = "requires Postgres"] async fn prefix_mode_matches_final_token_prefix_without_changing_full_text() {