diff --git a/crates/buzz-relay/src/handlers/search_backend_postgres_tests.rs b/crates/buzz-relay/src/handlers/search_backend_postgres_tests.rs index 1b25aa6659c..a17057770ea 100644 --- a/crates/buzz-relay/src/handlers/search_backend_postgres_tests.rs +++ b/crates/buzz-relay/src/handlers/search_backend_postgres_tests.rs @@ -878,25 +878,28 @@ async fn outbox_gauges_follow_a_paused_and_resumed_indexer() { .await; } -/// Prefix mode, which OpenSearch does not serve yet, stays on Postgres at -/// every value and is counted: shadow skips the comparison, and 2 serves it -/// from Postgres. Not a fallback: OpenSearch is never tried. -/// Mutation: route prefix searches like word searches → RED (the cluster is -/// contacted, and at 2 the search fails). +/// Prefix mode follows the flag like word searches: at 1 Postgres serves +/// and OpenSearch shadows it, at 2 OpenSearch serves. +/// Mutation: keep prefix searches on Postgres → RED (no shadow search at 1, +/// and at 2 the OpenSearch-only word finds nothing). #[tokio::test(flavor = "current_thread")] -#[ignore = "requires Postgres and Redis"] -async fn prefix_searches_stay_on_postgres_and_are_counted() { +#[ignore = "requires Postgres, Redis and OpenSearch"] +async fn prefix_searches_follow_the_flag() { let recorder = DebuggingRecorder::new(); let _metrics = metrics::set_default_local_recorder(&recorder); let mut recorded = Recorded::new(&recorder); - let cluster = FakeCluster::start(Answer::Error).await; - let f = Fixture::new(cluster.index.clone(), Duration::from_secs(1)).await; + let f = Fixture::on_opensearch().await; let c = f.community().await; - let needle = word("prefixed"); - let message = f.post(&c, c.private, &needle).await; - let query = buzz_search::SearchQuery { + + // Postgres holds `pg_word`; the index holds the message under `os_word`. + // Both stay short enough for the index to keep their prefixes. + let pg_word = word("prefixpg")[..16].to_owned(); + let os_word = word("prefixos")[..16].to_owned(); + let message = f.post(&c, c.private, &pg_word).await; + f.index_as(&c, &message, &os_word, c.private).await; + let query = |word: &str| buzz_search::SearchQuery { community: c.tenant.community(), - q: needle[..12].to_owned(), + q: word[..12].to_owned(), channel_scope: buzz_search::ChannelScope::Channels(vec![c.private]), kinds: Some(vec![9]), authors: None, @@ -907,37 +910,45 @@ async fn prefix_searches_stay_on_postgres_and_are_counted() { mode: buzz_search::SearchMode::Prefix, sort: buzz_search::SearchSort::Relevance, }; + let found = |hits: buzz_search::SearchResult| { + hits.hits.iter().map(|hit| hit.event_id).collect::>() + }; - for (value, setting) in [(1, "shadow"), (2, "opensearch")] { - f.set_backend(value); - let hits = f.state.search.search(&query).await.expect("search"); - assert_eq!( - hits.hits.iter().map(|hit| hit.event_id).collect::>(), - vec![message.id.to_bytes()], - "{setting}" - ); - recorded.collect(); - assert_eq!( - recorded.counter( - "buzz_search_opensearch_skipped_total", - &[("setting", setting), ("reason", "unsupported_mode")] - ), - 1, - "{setting}" - ); - } - tokio::time::sleep(Duration::from_millis(200)).await; - assert_eq!(cluster.connections(), 0); + f.set_backend(1); + let hits = f + .state + .search + .search(&query(&pg_word)) + .await + .expect("search"); + assert_eq!(found(hits), vec![message.id.to_bytes()], "Postgres serves"); + recorded.wait_for_shadows(1).await; + assert_eq!(recorded.requests("opensearch", "shadow", "zero_results"), 1); + + f.set_backend(2); + let hits = f + .state + .search + .search(&query(&os_word)) + .await + .expect("search"); + assert_eq!( + found(hits), + vec![message.id.to_bytes()], + "OpenSearch serves" + ); + recorded.collect(); + assert_eq!(recorded.requests("opensearch", "primary", "hits"), 1); + f.delete().await; } -/// The index holds only message kinds, so a search that names another kind, -/// mixes one in, or names no kinds stays on Postgres at 1 and 2, is not -/// shadowed, and counts as skipped with `unindexed_kinds`. That rule comes -/// before the mode rule, so a people search (kind 0, in prefix mode as -/// clients send it) counts there too. A message-kind search at 2 still -/// reaches the cluster. +/// The index holds only message kinds, so a search that names another kind +/// (a people search for kind 0, in prefix mode as clients send it), mixes +/// one in, or names no kinds stays on Postgres at 1 and 2, is not shadowed, +/// and counts as skipped. A message-kind search at 2 still reaches the +/// cluster. /// Mutation: drop the kind check from routing → RED (the cluster is -/// contacted and fails the word searches at 2). +/// contacted and fails the searches at 2). #[tokio::test(flavor = "current_thread")] #[ignore = "requires Postgres and Redis"] async fn searches_of_unindexed_kinds_stay_on_postgres() { @@ -959,10 +970,7 @@ async fn searches_of_unindexed_kinds_stay_on_postgres() { .expect("store the profile"); let query = |kinds: Option>, mode: buzz_search::SearchMode| buzz_search::SearchQuery { community: c.tenant.community(), - q: match mode { - buzz_search::SearchMode::FullText => needle.clone(), - buzz_search::SearchMode::Prefix => needle[..12].to_owned(), - }, + q: needle[..12].to_owned(), channel_scope: buzz_search::ChannelScope::ChannelsOrChannelLess(vec![c.private]), kinds, authors: None, @@ -990,45 +998,33 @@ async fn searches_of_unindexed_kinds_stay_on_postgres() { }; let mut both = vec![message.id.to_bytes(), profile.id.to_bytes()]; both.sort(); - let words = buzz_search::SearchMode::FullText; let prefix = buzz_search::SearchMode::Prefix; f.set_backend(2); - assert_eq!( - found(query(Some(vec![0]), words)).await, - vec![profile.id.to_bytes()] - ); - assert_eq!(found(query(Some(vec![9, 0]), words)).await, both); - assert_eq!(found(query(None, words)).await, both); assert_eq!( found(query(Some(vec![0]), prefix)).await, vec![profile.id.to_bytes()] ); + assert_eq!(found(query(Some(vec![9, 0]), prefix)).await, both); + assert_eq!(found(query(None, prefix)).await, both); f.set_backend(1); - assert_eq!(found(query(Some(vec![9, 0]), words)).await, both); + assert_eq!(found(query(Some(vec![9, 0]), prefix)).await, both); tokio::time::sleep(Duration::from_millis(200)).await; assert_eq!(cluster.connections(), 0, "OpenSearch was contacted"); recorded.collect(); - let skipped = |setting: &str, reason: &str| { + let skipped = |setting: &str| { recorded.counter( "buzz_search_opensearch_skipped_total", - &[("setting", setting), ("reason", reason)], + &[("setting", setting), ("reason", "unindexed_kinds")], ) }; - assert_eq!( - ( - skipped("opensearch", "unindexed_kinds"), - skipped("shadow", "unindexed_kinds"), - skipped("opensearch", "unsupported_mode"), - ), - (4, 1, 0) - ); + assert_eq!((skipped("opensearch"), skipped("shadow")), (3, 1)); f.set_backend(2); f.state .search - .search(&query(Some(vec![9]), words)) + .search(&query(Some(vec![9]), prefix)) .await .expect_err("a message search at 2 goes to the failing cluster"); } diff --git a/crates/buzz-search/src/backend.rs b/crates/buzz-search/src/backend.rs index 014a9002d3b..1cb4a7e25df 100644 --- a/crates/buzz-search/src/backend.rs +++ b/crates/buzz-search/src/backend.rs @@ -12,10 +12,10 @@ //! the other. It is read on every search, so a provider that changes values //! while the relay runs switches it without a restart. //! -//! Searches the index cannot answer stay on Postgres at every setting: -//! prefix mode, and any search that names a kind outside -//! [`buzz_db::search_outbox::SEARCHABLE_KINDS`] or names no kinds. That is -//! a routing rule known before the search runs, not a fallback: an +//! A search that names a kind outside +//! [`buzz_db::search_outbox::SEARCHABLE_KINDS`], or names no kinds, stays on +//! Postgres at every setting: the index would silently drop those results. +//! That is a routing rule known before the search runs, not a fallback: an //! OpenSearch failure at setting 2 still fails the search. //! //! Metrics and the shadow log line never carry query text. @@ -31,7 +31,7 @@ use tracing::info; use buzz_db::search_outbox::SEARCHABLE_KINDS; use crate::opensearch::SearchIndex; -use crate::{SearchError, SearchMode, SearchQuery, SearchResult}; +use crate::{SearchError, SearchQuery, SearchResult}; /// Integer flag choosing the search backend for the relay; see the module /// docs. Environment form: `BUZZ_FEATURE_FLAG_SEARCH_BACKEND`. @@ -161,6 +161,13 @@ impl OpenSearchBackend { self.shadow_deadline = deadline; } + /// The index serving `query`, if the setting is OpenSearch and the + /// index holds every kind it asks for. + pub(crate) fn serving(&self, query: &SearchQuery) -> Option<&SearchIndex> { + (self.selection.setting() == BackendSetting::OpenSearch && index_holds_kinds(query)) + .then_some(&self.index) + } + /// Decide where `query` runs, starting the shadow search if it gets one. pub(crate) fn route(&self, query: &SearchQuery) -> Route<'_> { let setting = self.selection.setting(); @@ -171,10 +178,6 @@ impl OpenSearchBackend { skipped(setting, "unindexed_kinds"); return Route::Postgres; } - if query.mode != SearchMode::FullText { - skipped(setting, "unsupported_mode"); - return Route::Postgres; - } if setting == BackendSetting::OpenSearch { return Route::OpenSearch(&self.index); } diff --git a/crates/buzz-search/src/lib.rs b/crates/buzz-search/src/lib.rs index 51a57e7b16e..dd6ddd256a5 100644 --- a/crates/buzz-search/src/lib.rs +++ b/crates/buzz-search/src/lib.rs @@ -50,8 +50,8 @@ pub use backend::{BackendSetting, SEARCH_BACKEND_FLAG}; pub use buzz_core::CommunityId; pub use error::SearchError; pub use query::{ - search, search_profile_names, ChannelScope, SearchHit, SearchMode, SearchQuery, SearchResult, - SearchSort, PROFILE_NAMES_PER_PAGE_MAX, + search, search_profile_names, ChannelScope, ScoreParts, ScoredHit, ScoredResult, SearchHit, + SearchMode, SearchQuery, SearchResult, SearchSort, PROFILE_NAMES_PER_PAGE_MAX, }; use std::sync::Arc; @@ -157,6 +157,20 @@ impl SearchService { } } + /// [`SearchService::search`] with each hit's score parts, for tests and + /// ranking evaluation. It asks the backend that would serve the search, + /// Postgres while the relay shadows, and records no metrics. + pub async fn search_scored(&self, query: &SearchQuery) -> Result { + match self + .opensearch + .as_ref() + .and_then(|opensearch| opensearch.serving(query)) + { + Some(index) => index.search_scored(query).await, + None => query::search(&self.pool, query).await.map(Into::into), + } + } + /// Find people by profile name, and by verified profile names signed by /// `verified_by`; see [`search_profile_names`]. pub async fn search_profile_names( diff --git a/crates/buzz-search/src/opensearch.rs b/crates/buzz-search/src/opensearch.rs index b6afcce7596..2bb83fb84a5 100644 --- a/crates/buzz-search/src/opensearch.rs +++ b/crates/buzz-search/src/opensearch.rs @@ -1,7 +1,8 @@ //! The OpenSearch message index: layout, writes and searches. //! //! One alias, `{prefix}messages`, points at the index of the mapping version -//! this code writes, `{prefix}messages-v1`. A document is one message, with +//! this code writes, `{prefix}messages-v{MAPPING_VERSION}`; text analysis +//! and ranking are in [`relevance`]. A document is one message, with //! id `community:event_id`. Documents are routed by id, so messages spread //! evenly over shards, and every search filters on the community first: that //! filter, not routing, is the multi-tenant fence. @@ -10,6 +11,8 @@ //! relay re-reads every hit from Postgres, so the index holds only what search //! needs. +mod relevance; + use std::ops::Range; use std::time::Duration; @@ -23,7 +26,8 @@ use opensearch::http::transport::{SingleNodeConnectionPool, TransportBuilder}; use opensearch::http::Url; use opensearch::indices::IndicesRefreshParts; use opensearch::indices::{ - IndicesCreateParts, IndicesDeleteParts, IndicesExistsParts, IndicesGetSettingsParts, + IndicesCreateParts, IndicesDeleteParts, IndicesExistsParts, IndicesGetAliasParts, + IndicesGetSettingsParts, }; use opensearch::params::VersionType; use opensearch::{BulkOperation, BulkParts, OpenSearch, SearchParts}; @@ -32,12 +36,16 @@ use serde_json::{json, Value}; use crate::aws_credentials::{default_chain, CachedCredentials}; use crate::query::{normalized_search_text, page_bounds, PageBounds}; use crate::{ - ChannelScope, SearchError, SearchHit, SearchMode, SearchQuery, SearchResult, SearchSort, + ChannelScope, ScoreParts, ScoredHit, ScoredResult, SearchError, SearchHit, SearchQuery, + SearchResult, SearchSort, }; /// Mapping version this code writes and searches. Bump it, with a reindex, -/// whenever the mapping or analysis changes. -const MAPPING_VERSION: u32 = 1; +/// whenever the mapping or analysis changes. Until reindexing exists, an +/// index of an older version is deleted, recreated and backfilled again. +/// +/// 2: word parts, accent folding, stems, prefixes and recency. +pub const MAPPING_VERSION: u32 = 2; /// Index names used when the configuration sets no prefix. pub const DEFAULT_INDEX_PREFIX: &str = "buzz-"; @@ -184,6 +192,9 @@ impl SearchIndex { /// Create the versioned index behind the alias unless the alias exists. /// Returns whether this call created it. For tests and tools: the /// indexer clears the backfill progress between `missing` and `create`. + /// An alias pointing anywhere but this mapping version's index is an + /// error, so the indexer never writes documents of one mapping into an + /// index of another. pub async fn ensure(&self) -> Result { if !self.missing().await? { return Ok(false); @@ -195,7 +206,7 @@ impl SearchIndex { /// index exists. Any other answer is an error, so a cluster that fails /// or throttles a lookup is never taken for one that lost the index. pub(crate) async fn missing(&self) -> Result { - if self.exists(&self.alias).await? { + if self.alias_checked().await? { return Ok(false); } if self.exists(&self.index).await? { @@ -219,7 +230,7 @@ impl SearchIndex { if response.status_code().as_u16() == 400 { let body: Value = response.json().await.map_err(transport_error)?; if body["error"]["type"] == "resource_already_exists_exception" { - if self.exists(&self.alias).await? { + if self.alias_checked().await? { return Ok(false); } return Err(SearchError::Engine("index exists without its alias".into())); @@ -246,6 +257,35 @@ impl SearchIndex { } } + /// Whether the alias exists, failing if it points at anything but this + /// version's index. + async fn alias_checked(&self) -> Result { + let response = self + .client + .indices() + .get_alias(IndicesGetAliasParts::Name(&[&self.alias])) + .send() + .await + .map_err(transport_error)?; + if response.status_code().as_u16() == 404 { + return Ok(false); + } + let body = checked(response).await?; + let targets: Vec<&String> = body + .as_object() + .into_iter() + .flat_map(|m| m.keys()) + .collect(); + if targets != [&self.index] { + return Err(SearchError::Engine(format!( + "alias {} points at {targets:?}, not {}: delete that index to rebuild \ + it at this version", + self.alias, self.index + ))); + } + Ok(true) + } + /// How long ago the versioned index was created, by the cluster's /// creation time and this host's clock; zero if that time is ahead. pub(crate) async fn age(&self) -> Result { @@ -472,32 +512,58 @@ impl SearchIndex { /// Run a message search against the alias. pub(crate) async fn search(&self, query: &SearchQuery) -> Result { + self.search_scored(query).await.map(Into::into) + } + + /// Run a message search against the alias, keeping each hit's score + /// parts. + pub(crate) async fn search_scored( + &self, + query: &SearchQuery, + ) -> Result { let PageBounds { page, per_page, offset, } = page_bounds(query); - let Some(text) = normalized_search_text(&query.q) else { - return Ok(SearchResult { + let empty = || { + Ok(ScoredResult { hits: Vec::new(), page, - }); + }) + }; + let Some(text) = normalized_search_text(&query.q).and_then(|text| { + relevance::text_query(&text, query.mode, query.sort == SearchSort::Relevance) + }) else { + return empty(); }; if offset + i64::from(per_page) > MAX_RESULT_WINDOW { - return Ok(SearchResult { - hits: Vec::new(), - page, - }); + return empty(); } + let rescored = query.sort == SearchSort::Relevance; + // Relevance results end at the rescore window: hits past it keep Q + // without the age factor, so a page reaching past it would mix them + // with the window's and repeat or skip hits of other pages. + let size = if rescored { + (relevance::RESCORE_WINDOW - offset).min(i64::from(per_page)) + } else { + i64::from(per_page) + }; + let Ok(size @ 1..) = u32::try_from(size) else { + return empty(); + }; + let now = chrono::Utc::now().timestamp(); let response = self .client .search(SearchParts::Index(&[&self.alias])) - .body(search_body(query, &text, offset, per_page)) + .body(search_body(query, text, offset, size, now)) .send() .await .map_err(transport_error)?; let body = checked(response).await?; - // A partly failed search is an error, not fewer hits. + // A partly failed search is an error, not fewer hits. Serverless + // reports `_shards` as all zeros, so there only `timed_out` can + // catch it. if body["timed_out"] == true { return Err(SearchError::Engine(crate::error::SEARCH_TIMED_OUT.into())); } @@ -508,16 +574,36 @@ impl SearchIndex { .as_array() .into_iter() .flatten() - .map(parse_hit) - .collect::>()?; - Ok(SearchResult { hits, page }) + .map(|hit| { + let hit = parse_hit(hit)?; + // Every relevance hit is in the rescore window, so its rank + // carries the age factor; a hit sorted by time has none. + let parts = if rescored { + let age = relevance::age_factor(hit.created_at, now); + ScoreParts { + query_match: (f64::from(hit.rank) / age) as f32, + age: age as f32, + } + } else { + ScoreParts { + query_match: hit.rank, + age: 1.0, + } + }; + Ok(ScoredHit { hit, parts }) + }) + .collect::>()?; + Ok(ScoredResult { hits, page }) } } /// Settings, mapping and alias of a new index. fn index_definition(alias: &str) -> Value { json!({ - "settings": { "index": { "refresh_interval": "30s" } }, + "settings": { + "index": { "refresh_interval": "30s" }, + "analysis": relevance::analysis() + }, "mappings": { "dynamic": "strict", "_source": { "excludes": ["content"] }, @@ -532,7 +618,7 @@ fn index_definition(alias: &str) -> Value { "thread_root": { "type": "keyword" }, "mentions": { "type": "keyword" }, "created_at": { "type": "date", "format": "epoch_second" }, - "content": { "type": "text" } + "content": relevance::content_mapping() } }, "aliases": { alias: {} } @@ -598,8 +684,16 @@ fn document_source(community: CommunityId, document: &SearchDocument) -> Value { } /// The request body of a search: filters on the community first, then on -/// scope, kinds, authors and time; the text must match every word. -fn search_body(query: &SearchQuery, text: &str, offset: i64, per_page: u32) -> Value { +/// scope, kinds, authors and time; `text` decides what matches and its Q. +/// Relevance order is Q times the age factor at `now`; newest order is by +/// time alone. +fn search_body( + query: &SearchQuery, + text: relevance::TextQuery, + offset: i64, + per_page: u32, + now: i64, +) -> Value { let mut filter = vec![json!({ "term": { "community": query.community.as_uuid().to_string() } })]; let channels = |ids: &[uuid::Uuid]| json!({ "terms": { "channel": ids.iter().map(|id| id.to_string()).collect::>() } }); @@ -629,31 +723,25 @@ fn search_body(query: &SearchQuery, text: &str, offset: i64, per_page: u32) -> V if !range.is_empty() { filter.push(json!({ "range": { "created_at": range } })); } - let text_match = match query.mode { - SearchMode::FullText => { - json!({ "match": { "content": { "query": text, "operator": "and" } } }) - } - SearchMode::Prefix => { - json!({ "match_bool_prefix": { "content": { "query": text, "operator": "and" } } }) - } - }; - let tiebreak = [ - json!({ "created_at": "desc" }), - json!({ "event_id": "asc" }), - ]; - let sort: Vec = match query.sort { - SearchSort::Relevance => std::iter::once(json!("_score")).chain(tiebreak).collect(), - SearchSort::Newest => tiebreak.into(), - }; - json!({ + let mut body = json!({ "from": offset, "size": per_page, + // No hit count: counting would visit every match. "track_total_hits": false, - "track_scores": true, "_source": ["event_id", "kind", "author", "channel", "created_at"], - "query": { "bool": { "filter": filter, "must": [text_match] } }, - "sort": sort - }) + "query": { "bool": { "filter": filter, "must": [text.matched.clone()] } }, + }); + match query.sort { + // A rescore cannot follow a sort, so ties keep the engine's order; + // the age factor already puts the newer of two equal matches first. + SearchSort::Relevance => body["rescore"] = relevance::rescore(&text, now), + // No scores: computing them made a common word's search six times + // slower on a million messages, and time alone orders the hits. + SearchSort::Newest => { + body["sort"] = json!([{ "created_at": "desc" }, { "event_id": "asc" }]); + } + } + body } fn parse_hit(hit: &Value) -> Result { diff --git a/crates/buzz-search/src/opensearch/relevance.rs b/crates/buzz-search/src/opensearch/relevance.rs new file mode 100644 index 00000000000..3147996a325 --- /dev/null +++ b/crates/buzz-search/src/opensearch/relevance.rs @@ -0,0 +1,316 @@ +//! How the index analyzes message text and how a search ranks it. +//! +//! Every relevance choice lives here: the analyzers, the text fields they +//! fill, the match query and the age rescore. The rest of [`super`] only +//! filters and pages. The reasons the code can't show: +//! +//! - **Letters and digits stay together.** `word_delimiter_graph` splits at +//! `.`, `_`, `-`, `:` and case changes but not between letters and digits, +//! so a hex id stays one token instead of dozens of fragments. The query +//! is split the same way, so part of an identifier (`snake_case` of +//! `snake_case_name`, `OutboxBatch` of `SearchOutboxBatch`) finds it. On +//! `content` the split parts are a phrase, so `foo_bar` ranks itself, then +//! `foo bar`. The stem and prefix fields keep no positions, so there the +//! parts match anywhere: a message holding `foo` and `bar` apart is still +//! found, last. +//! - **Typos only rank.** A word matched only with a typo scores a third +//! of an exact match, so relevance order keeps it below. Newest order has +//! no such defence: for a short word most matches are other words one +//! letter away (`log` and `lag`), so it matches no typos. In prefix +//! mode the unfinished last word gets typos only from +//! [`MIN_TYPO_PREFIX`] characters. +//! - **Long tokens get no prefixes.** Tokens over [`LONG_TOKEN`] characters +//! (`nostr:` URIs, keys, hashes) are not typed a letter at a time, and +//! each would add dozens of prefixes. +//! - **Phrase and proximity are a rescore.** They read the positions of +//! every message holding all the words. In the main query that cost 55 ms +//! for two common words on a million messages, against 22 ms over the top +//! [`RESCORE_WINDOW`] hits, and it grows with the history. +//! - **Age is a rescore too**: `0.2 + 0.8 × 0.5^(age / 30 days)`, applied to +//! the top [`RESCORE_WINDOW`] hits per shard. Matching can still skip +//! documents that cannot reach the top, so cost does not grow with every +//! match of a common word. The trade-off: recency cannot lift a weak match +//! from outside the window. +//! - **Serverless.** Built-in analysis only (no ICU plugin), and no scripts +//! are used. `word_delimiter_graph`, `edge_ngram`, `length`, `truncate`, +//! the `light_english` stemmer and `rescore` with a `function_score` +//! decay were checked on a NextGen Serverless collection, where an inline +//! Painless `script_score` also ran. + +use serde_json::{json, Value}; + +use crate::SearchMode; + +/// Shortest prefix indexed for prefix mode. +const MIN_PREFIX: u32 = 2; +/// Longest prefix indexed: a longer partial word matches through its first +/// [`MAX_PREFIX`] characters. Ten characters rather than twenty makes the +/// prefix field a quarter smaller (1.03 to 0.77 KB a message on a million +/// messages, 2.7 times the whole-word field), at the same search speed. +const MAX_PREFIX: u32 = 10; +/// Tokens longer than this get no prefixes. +const LONG_TOKEN: u32 = 24; + +/// How many of the query words a message must match: all of one or two, +/// three quarters (rounded down) of more. +const MIN_WORDS_MATCHED: &str = "2<75%"; +/// Query words past this many are ignored, which bounds a query's clauses. +const MAX_WORDS: usize = 32; +/// Weight of a word matched only through its stem. +const STEM_WEIGHT: f64 = 0.4; +/// Weight of a word matched only with a typo. +const TYPO_WEIGHT: f64 = 0.3; +/// Weight of a partial last word matched as a prefix. +const PREFIX_WEIGHT: f64 = 0.5; +/// Shortest unfinished last word that may match with a typo in prefix mode: +/// a shorter one is a single edit from too many other words. +const MIN_TYPO_PREFIX: usize = 4; +/// Bonus weight of the query found as an exact phrase. An exact phrase is +/// also within [`PROXIMITY_SLOP`], so it earns both bonuses. +const PHRASE_WEIGHT: f64 = 2.0; +/// Bonus weight of the query words found within [`PROXIMITY_SLOP`] moves of +/// each other. +const PROXIMITY_WEIGHT: f64 = 1.0; +const PROXIMITY_SLOP: u32 = 4; + +/// How many of the best hits by Q the age factor reorders, and so how far +/// relevance results go: past the window a hit would keep Q alone and +/// interleave with the window's, so pages would repeat or skip hits. It +/// covers the relay's search scan, which pages through up to +/// [`buzz_db::DEFAULT_MAX_PAGE_LIMIT`] candidates. On a million messages, +/// 1,000 rather than 500 added 3 ms to a one-word search (29 to 32 ms) and +/// nothing measurable to longer ones, whose matching costs far more. +pub(super) const RESCORE_WINDOW: i64 = 1_000; +const _: () = assert!(RESCORE_WINDOW >= buzz_db::DEFAULT_MAX_PAGE_LIMIT); +/// T never falls below this, so old exact matches survive. +const AGE_FLOOR: f64 = 0.2; +/// Age at which the decaying part of T has halved. +const AGE_HALF_LIFE_DAYS: u32 = 30; + +/// The index's `analysis` settings. +pub(super) fn analysis() -> Value { + json!({ + "filter": { + "word_parts": { + "type": "word_delimiter_graph", + "preserve_original": true, + "split_on_numerics": false + }, + "short_tokens": { "type": "length", "max": LONG_TOKEN }, + "prefixes": { "type": "edge_ngram", "min_gram": MIN_PREFIX, "max_gram": MAX_PREFIX }, + "longest_prefix": { "type": "truncate", "length": MAX_PREFIX }, + "light_stem": { "type": "stemmer", "language": "light_english" } + }, + "analyzer": { + "message": analyzer(&["word_parts", "lowercase", "asciifolding"]), + "message_stem": analyzer(&["word_parts", "lowercase", "asciifolding", "light_stem"]), + "message_prefix": analyzer(&[ + "word_parts", "lowercase", "asciifolding", "short_tokens", "prefixes" + ]), + "message_prefix_search": analyzer(&[ + "word_parts", "lowercase", "asciifolding", "longest_prefix" + ]) + } + }) +} + +fn analyzer(filters: &[&str]) -> Value { + json!({ "type": "custom", "tokenizer": "standard", "filter": filters }) +} + +/// The mapping of `content`, the message text. +pub(super) fn content_mapping() -> Value { + json!({ + "type": "text", + "analyzer": "message", + "fields": { + "stem": { + "type": "text", + "analyzer": "message_stem", + "index_options": "freqs" + }, + "prefix": prefix_mapping() + } + }) +} + +/// The prefix field: edge n-grams, searched with whole query tokens. +fn prefix_mapping() -> Value { + json!({ + "type": "text", + "analyzer": "message_prefix", + "search_analyzer": "message_prefix_search", + "index_options": "freqs" + }) +} + +/// `word` as a prefix of an indexed word. +fn prefix_query(word: &str) -> Value { + json!({ "match": { "content.prefix": { + "query": word, "operator": "and", "boost": PREFIX_WEIGHT + } } }) +} + +/// `word` with up to `AUTO` edits (none for one or two characters, one up to +/// five, then two), its first letter exact. +fn typo_clause(word: &str) -> Value { + json!({ "match": { "content": { + "query": word, + "operator": "and", + "fuzziness": "AUTO", + "prefix_length": 1, + "boost": TYPO_WEIGHT + } } }) +} + +/// A search's text: what matches, and the phrase bonus for a +/// [`rescore`]. +pub(super) struct TextQuery { + /// The words: which messages match, and their Q before any bonus. + pub(super) matched: Value, + /// The phrase and proximity bonus, for queries of two words or more. + bonus: Option, +} + +/// The text query for `text` in `mode`, or `None` if it has no words. +/// `typos` says whether a word may match with a typo. +pub(super) fn text_query(text: &str, mode: SearchMode, typos: bool) -> Option { + // A punctuation-only word analyzes to nothing and would count against + // the minimum without ever matching. + let words: Vec<&str> = text + .split_whitespace() + .filter(|word| word.chars().any(char::is_alphanumeric)) + .take(MAX_WORDS) + .collect(); + let (last, completed) = words.split_last()?; + let mut clauses: Vec = completed + .iter() + .map(|word| word_clause(word, typos)) + .collect(); + clauses.push(match mode { + SearchMode::FullText => word_clause(last, typos), + SearchMode::Prefix => { + let mut queries = vec![exact_clause(last), stem_clause(last), prefix_query(last)]; + if typos && last.chars().count() >= MIN_TYPO_PREFIX { + queries.push(typo_clause(last)); + } + json!({ "dis_max": { "queries": queries } }) + } + }); + let matched = json!({ "bool": { + "should": clauses, + "minimum_should_match": MIN_WORDS_MATCHED + } }); + if words.len() < 2 { + return Some(TextQuery { + matched, + bonus: None, + }); + } + let phrase = words.join(" "); + let phrase_query = match mode { + SearchMode::FullText => "match_phrase", + SearchMode::Prefix => "match_phrase_prefix", + }; + let bonus = |slop: u32, boost: f64| json!({ phrase_query: { "content": { "query": phrase, "slop": slop, "boost": boost } } }); + Some(TextQuery { + matched, + bonus: Some(json!({ "bool": { + "should": [bonus(0, PHRASE_WEIGHT), bonus(PROXIMITY_SLOP, PROXIMITY_WEIGHT)] + } })), + }) +} + +/// One query word, matched exactly, by stem or (with `typos`) with a typo, +/// scored by the best of them. +fn word_clause(word: &str, typos: bool) -> Value { + let mut queries = vec![exact_clause(word), stem_clause(word)]; + if typos { + queries.push(typo_clause(word)); + } + json!({ "dis_max": { "queries": queries } }) +} + +fn exact_clause(word: &str) -> Value { + json!({ "match": { "content": { "query": word, "operator": "and" } } }) +} + +fn stem_clause(word: &str) -> Value { + json!({ "match": { "content.stem": { + "query": word, "operator": "and", "boost": STEM_WEIGHT + } } }) +} + +/// The rescores of a relevance search over the top [`RESCORE_WINDOW`] hits: +/// add `text`'s phrase bonus to their Q, then multiply it by the age factor +/// at `now` (Unix seconds); see [`age_factor`]. +pub(super) fn rescore(text: &TextQuery, now: i64) -> Value { + let bonus = text.bonus.as_ref().map(|bonus| { + json!({ + "window_size": RESCORE_WINDOW, + "query": { + "rescore_query": bonus, + "query_weight": 1.0, + "rescore_query_weight": 1.0, + "score_mode": "total" + } + }) + }); + Value::Array(bonus.into_iter().chain([age_rescore(now)]).collect()) +} + +fn age_rescore(now: i64) -> Value { + json!({ + "window_size": RESCORE_WINDOW, + "query": { + "rescore_query": { "function_score": { + "query": { "match_all": {} }, + "functions": [ + { + "exp": { "created_at": { + "origin": now.to_string(), + "scale": format!("{AGE_HALF_LIFE_DAYS}d"), + "decay": 0.5 + } }, + "weight": 1.0 - AGE_FLOOR + }, + { "weight": AGE_FLOOR } + ], + "score_mode": "sum", + "boost_mode": "replace" + } }, + "query_weight": 1.0, + "rescore_query_weight": 1.0, + "score_mode": "multiply" + } + }) +} + +/// T for a message created at `created_at`, at `now` (both Unix seconds): +/// what [`rescore`] multiplies by. A message from the future (clock +/// skew) decays as if as old, as the index's decay does. +pub(super) fn age_factor(created_at: i64, now: i64) -> f64 { + let age_days = now.abs_diff(created_at) as f64 / 86_400.0; + AGE_FLOOR + (1.0 - AGE_FLOOR) * 0.5_f64.powf(age_days / f64::from(AGE_HALF_LIFE_DAYS)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn age_factor_halves_its_decaying_part_every_thirty_days() { + let now = 1_800_000_000; + let day = 86_400; + for (age, expected) in [(0, 1.0), (30 * day, 0.6), (60 * day, 0.4)] { + assert!((age_factor(now - age, now) - expected).abs() < 1e-9); + } + assert!((age_factor(now - 3650 * day, now) - AGE_FLOOR).abs() < 1e-9); + } + + #[test] + fn punctuation_only_queries_have_no_words() { + assert!(text_query(" ' : & | ", SearchMode::FullText, true).is_none()); + assert!(text_query("alpha ' bet", SearchMode::Prefix, true).is_some()); + } +} diff --git a/crates/buzz-search/src/query.rs b/crates/buzz-search/src/query.rs index ef8fb2fd2ac..5d585639e58 100644 --- a/crates/buzz-search/src/query.rs +++ b/crates/buzz-search/src/query.rs @@ -57,7 +57,9 @@ pub enum ChannelScope { /// Search matching semantics. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum SearchMode { - /// Standard NIP-50-ish word/lexeme search using `websearch_to_tsquery`. + /// Standard NIP-50-ish word/lexeme search: `websearch_to_tsquery` on + /// Postgres; on OpenSearch, most query words matched exactly, by stem or + /// with a typo. FullText, /// Prefix-match the trailing normalized query token (`pro` matches `project`). /// @@ -67,15 +69,18 @@ pub enum SearchMode { /// the newest 1000 matches. It does not change the access boundary. A /// trailing token that yields a lexeme shorter than three characters /// returns no hits unless the query is kind:0-only (see `PREFIX_MIN_CHARS`). + /// These limits are Postgres's: OpenSearch completes a trailing token of + /// two characters or more and ranks every match. Prefix, } /// Result ordering for a search. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum SearchSort { - /// `ts_rank_cd` relevance, newest first among equal ranks. In - /// [`SearchMode::Prefix`] outside profile search, only the newest 1000 - /// matches are ranked, so pages end with them. + /// On Postgres, `ts_rank_cd` relevance, newest first among equal ranks; + /// in [`SearchMode::Prefix`] outside profile search, only the newest 1000 + /// matches are ranked, so pages end with them. On OpenSearch, the query + /// match times an age factor (see [`ScoreParts`]). Relevance, /// Newest first, ignoring relevance; ties ordered by event id. Newest, @@ -131,7 +136,8 @@ pub struct SearchHit { pub channel_id: Option, /// Unix seconds. pub created_at: i64, - /// `ts_rank_cd` relevance score (higher = better). + /// Relevance score (higher = better): `ts_rank_cd` on Postgres. Zero + /// for an OpenSearch hit sorted by time, which is not scored. pub rank: f32, } @@ -144,6 +150,67 @@ pub struct SearchResult { pub page: u32, } +/// The parts of a hit's relevance score, for tests, tuning and ranking +/// evaluation; never sent to clients. An OpenSearch hit ranked by relevance +/// has the rank Q × T: those results end at the age rescore's window, so +/// every hit is in it. A hit sorted by time, or from Postgres, has T = 1. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct ScoreParts { + /// Q, how well the message matches the query. + pub query_match: f32, + /// T, the age factor: 1 for a new message, falling towards 0.2. A search + /// sorted by time or run on Postgres has no age factor and reports 1. + pub age: f32, +} + +/// A hit with the parts of its score. +#[derive(Debug, Clone)] +pub struct ScoredHit { + /// The hit, as [`SearchService::search`](crate::SearchService::search) + /// returns it. + pub hit: SearchHit, + /// How its rank was made. + pub parts: ScoreParts, +} + +/// A search result with each hit's score parts. +#[derive(Debug, Clone)] +pub struct ScoredResult { + /// Hits on this page, in the query's `sort` order. + pub hits: Vec, + /// 1-indexed page returned. + pub page: u32, +} + +impl From for ScoredResult { + /// Each hit's rank as its query match, with no age factor. + fn from(result: SearchResult) -> Self { + Self { + hits: result + .hits + .into_iter() + .map(|hit| ScoredHit { + parts: ScoreParts { + query_match: hit.rank, + age: 1.0, + }, + hit, + }) + .collect(), + page: result.page, + } + } +} + +impl From for SearchResult { + fn from(result: ScoredResult) -> Self { + Self { + hits: result.hits.into_iter().map(|scored| scored.hit).collect(), + page: result.page, + } + } +} + const PER_PAGE_MAX: u32 = 500; const PER_PAGE_DEFAULT: u32 = 100; /// Hard cap on search text handed to Postgres text-search parsers. This keeps a diff --git a/crates/buzz-search/tests/postgres_opensearch_relevance.rs b/crates/buzz-search/tests/postgres_opensearch_relevance.rs new file mode 100644 index 00000000000..267885e41f2 --- /dev/null +++ b/crates/buzz-search/tests/postgres_opensearch_relevance.rs @@ -0,0 +1,632 @@ +//! OpenSearch ranking: typos, rare words, phrases, word parts, accents, +//! markdown, stems, prefixes and recency, each checked through +//! [`SearchService::search`] against a real cluster. +//! +//! Needs Postgres (run through `scripts/postgres-test-run.sh -p buzz-search +//! --tests`) and an OpenSearch cluster at `BUZZ_TEST_OPENSEARCH_URL` +//! (default `http://localhost:9200`). + +#[allow(unused_macros, unused_imports)] +mod search_suite; + +use buzz_core::CommunityId; +use buzz_search::{ChannelScope, SearchMode, SearchQuery, SearchSort}; +use search_suite::{insert_event, mk_community, rand_bytes32, Backend, Fixture}; +use sqlx::PgPool; +use uuid::Uuid; + +const DAY: i64 = 86_400; + +/// A community of its own on a fresh OpenSearch fixture. +async fn setup() -> (PgPool, Fixture, CommunityId) { + let (pool, fixture) = Fixture::setup(Backend::OpenSearch).await; + let host = format!("{}.relevance.example", Uuid::new_v4().simple()); + let community = mk_community(&pool, &host).await; + (pool, fixture, community) +} + +fn now() -> i64 { + chrono::Utc::now().timestamp() +} + +/// Store a kind 9 message `age` seconds old, queued for indexing. +async fn post(pool: &PgPool, community: CommunityId, content: &str, age: i64) -> [u8; 32] { + let id = rand_bytes32(); + insert_event( + pool, + community, + id, + rand_bytes32(), + 9, + content, + None, + now() - age, + ) + .await; + id +} + +fn query(community: CommunityId, q: &str, mode: SearchMode, sort: SearchSort) -> SearchQuery { + SearchQuery { + community, + q: q.into(), + channel_scope: ChannelScope::Any, + kinds: None, + authors: None, + since: None, + until: None, + page: 1, + per_page: 50, + mode, + sort, + } +} + +/// Hit ids of a relevance search, best first. +async fn ranked(fx: &Fixture, community: CommunityId, q: &str, mode: SearchMode) -> Vec<[u8; 32]> { + fx.service() + .search(&query(community, q, mode, SearchSort::Relevance)) + .await + .expect("search") + .hits + .iter() + .map(|hit| hit.event_id) + .collect() +} + +async fn words(fx: &Fixture, community: CommunityId, q: &str) -> Vec<[u8; 32]> { + ranked(fx, community, q, SearchMode::FullText).await +} + +/// Each hit's query match (Q) for a word search. +async fn query_match(fx: &Fixture, community: CommunityId, q: &str) -> Vec<([u8; 32], f32)> { + fx.service() + .search_scored(&query( + community, + q, + SearchMode::FullText, + SearchSort::Relevance, + )) + .await + .expect("debug search") + .hits + .iter() + .map(|hit| (hit.hit.event_id, hit.parts.query_match)) + .collect() +} + +fn q_of(scores: &[([u8; 32], f32)], id: &[u8; 32], what: &str) -> f32 { + scores + .iter() + .find(|(hit, _)| hit == id) + .unwrap_or_else(|| panic!("{what} not found")) + .1 +} + +fn position(hits: &[[u8; 32]], id: &[u8; 32], what: &str) -> usize { + hits.iter() + .position(|hit| hit == id) + .unwrap_or_else(|| panic!("{what} not found in {} hits", hits.len())) +} + +/// `better` is found and ranks above `worse`, which is found too. +fn ranks_above(hits: &[[u8; 32]], better: &[u8; 32], worse: &[u8; 32], what: &str) { + let (b, w) = (position(hits, better, what), position(hits, worse, what)); + assert!(b < w, "{what}: expected rank {b} above {w}"); +} + +/// One- and two-letter typos still find a message, below an exact match, in +/// either mode; the first letter is never a typo, and an unfinished word of +/// three letters gets none. +#[tokio::test] +#[ignore = "requires Postgres and OpenSearch"] +async fn typos_find_the_message_below_an_exact_match() { + let (pool, fx, c) = setup().await; + let exact = post(&pool, c, "kubernetes upgrade tonight", DAY).await; + let misspelt = post(&pool, c, "kubernates upgrade tonight", DAY).await; + let log = post(&pool, c, "deploy log attached", DAY).await; + + for mode in [SearchMode::FullText, SearchMode::Prefix] { + for typo in ["kubernates", "kubarnates", "kubrenetes"] { + let hits = ranked(&fx, c, typo, mode).await; + assert!( + hits.contains(&exact), + "{mode:?}: {typo} finds the exact spelling" + ); + } + let hits = ranked(&fx, c, "kubernetes", mode).await; + ranks_above(&hits, &exact, &misspelt, "exact above typo"); + } + assert!( + !ranked(&fx, c, "lag", SearchMode::Prefix) + .await + .contains(&log), + "an unfinished three-letter word gets no typos" + ); + // Kept well apart, not just below: a typo is worth under half a word. + let scores = query_match(&fx, c, "kubernetes").await; + let (exact_q, typo_q) = ( + q_of(&scores, &exact, "exact"), + q_of(&scores, &misspelt, "typo"), + ); + assert!(typo_q < exact_q * 0.5, "typo Q {typo_q}, exact Q {exact_q}"); + assert!( + words(&fx, c, "cubernetes").await.is_empty(), + "the first letter must match" + ); + fx.teardown(pool).await; +} + +/// The message with the rare query word ranks above one repeating common +/// query words. +#[tokio::test] +#[ignore = "requires Postgres and OpenSearch"] +async fn a_rare_word_outranks_repeated_common_words() { + let (pool, fx, c) = setup().await; + for n in 0..30 { + post(&pool, c, &format!("deploy today item {n}"), DAY).await; + } + let rare = post(&pool, c, "zephyrine deploy", DAY).await; + let repeated = post(&pool, c, "deploy today deploy today deploy today", DAY).await; + + let hits = words(&fx, c, "zephyrine deploy today").await; + ranks_above(&hits, &rare, &repeated, "rare word above repeats"); + assert_eq!(hits.first(), Some(&rare)); + fx.teardown(pool).await; +} + +/// An exact phrase ranks above the same words scattered. +#[tokio::test] +#[ignore = "requires Postgres and OpenSearch"] +async fn an_exact_phrase_outranks_scattered_words() { + let (pool, fx, c) = setup().await; + let scattered = post(&pool, c, "train everyone before the next release", DAY).await; + let phrase = post(&pool, c, "everyone catch the release train before", DAY).await; + + let hits = words(&fx, c, "release train").await; + ranks_above(&hits, &phrase, &scattered, "phrase above scattered"); + fx.teardown(pool).await; +} + +/// An identifier in the query ranks itself first, then its parts side by +/// side, then its parts apart or out of order, alone and inside a longer +/// query. +#[tokio::test] +#[ignore = "requires Postgres and OpenSearch"] +async fn an_identifier_outranks_its_parts_side_by_side_then_apart() { + let (pool, fx, c) = setup().await; + let snake = post(&pool, c, "rename retry_budget in the client", DAY).await; + let snake_parts = post(&pool, c, "rename the retry budget in the client", DAY).await; + let snake_apart = post(&pool, c, "rename it, retry later within budget", DAY).await; + let snake_reversed = post(&pool, c, "rename the budget before any retry", DAY).await; + let camel = post(&pool, c, "rename OutboxBatch soon", DAY).await; + let camel_parts = post(&pool, c, "rename the outbox batch soon", DAY).await; + let camel_apart = post(&pool, c, "rename the outbox, one batch at a time", DAY).await; + let camel_reversed = post(&pool, c, "rename this batch in the outbox", DAY).await; + + let cases = [ + ("retry_budget", SearchMode::FullText, snake, snake_parts), + ( + "rename retry_budget", + SearchMode::FullText, + snake, + snake_parts, + ), + ("rename retry_bud", SearchMode::Prefix, snake, snake_parts), + ("OutboxBatch", SearchMode::FullText, camel, camel_parts), + ( + "rename OutboxBatch", + SearchMode::FullText, + camel, + camel_parts, + ), + ]; + for (q, mode, whole, parts) in cases { + let hits = ranked(&fx, c, q, mode).await; + assert_eq!(hits[..2], [whole, parts], "{q}"); + } + // Parts apart still match, by stem, below both. + let hits = words(&fx, c, "retry_budget").await; + assert_eq!(hits.len(), 4, "retry_budget finds its parts apart too"); + assert!(hits.contains(&snake_apart) && hits.contains(&snake_reversed)); + let hits = words(&fx, c, "OutboxBatch").await; + assert!(hits.contains(&camel_apart) && hits.contains(&camel_reversed)); + fx.teardown(pool).await; +} + +/// A short message holding the query as a phrase outranks long messages +/// holding its words several times, close together or scattered: the +/// production "ranking rules" case, where long agent output filled the top. +#[tokio::test] +#[ignore = "requires Postgres and OpenSearch"] +async fn a_short_exact_phrase_outranks_long_messages_repeating_the_words() { + let (pool, fx, c) = setup().await; + let filler = |n: usize| { + (0..n) + .map(|i| format!("step{i} output")) + .collect::>() + .join(" ") + }; + let close = post( + &pool, + c, + &format!( + "{} ranking rules {} ranking rules {} ranking rules {}", + filler(40), + filler(40), + filler(40), + filler(40) + ), + DAY, + ) + .await; + let scattered = post( + &pool, + c, + &format!( + "rules {} ranking {} rules {} ranking {} rules ranking", + filler(50), + filler(50), + filler(50), + filler(50) + ), + DAY, + ) + .await; + let short = post(&pool, c, "where are the ranking rules", DAY).await; + + let hits = words(&fx, c, "ranking rules").await; + assert_eq!(hits.first(), Some(&short), "the short phrase comes first"); + ranks_above(&hits, &short, &close, "short above close repeats"); + ranks_above(&hits, &short, &scattered, "short above scattered repeats"); + fx.teardown(pool).await; +} + +/// Words are OR-ed with a minimum: most of the words is enough, one is not. +#[tokio::test] +#[ignore = "requires Postgres and OpenSearch"] +async fn most_query_words_are_enough() { + let (pool, fx, c) = setup().await; + let most = post(&pool, c, "quarterly budget review notes", DAY).await; + let one = post(&pool, c, "budget only", DAY).await; + + let hits = words(&fx, c, "quarterly budget review meeting").await; + assert!(hits.contains(&most), "three of four words match"); + assert!(!hits.contains(&one), "one of four words is not enough"); + fx.teardown(pool).await; +} + +/// URLs, hostnames, dotted file names, package names and code identifiers +/// match whole and by part, as do words wrapped in markdown punctuation. +#[tokio::test] +#[ignore = "requires Postgres and OpenSearch"] +async fn urls_names_and_markdown_match_whole_and_by_part() { + let (pool, fx, c) = setup().await; + let url = post( + &pool, + c, + "read https://docs.example.org/guide/setup first", + DAY, + ) + .await; + let file = post(&pool, c, "edit config.prod.yaml then restart", DAY).await; + let package = post(&pool, c, "install @example-scope/search-widget now", DAY).await; + let identifier = post(&pool, c, "call getUserName or buzz_search::run", DAY).await; + let quoted = post(&pool, c, "ask \"Ingrid\" about it", DAY).await; + let code = post(&pool, c, "run `frobnicate` twice", DAY).await; + let bold = post(&pool, c, "this is **crucial** stuff", DAY).await; + let link = post(&pool, c, "see [handbook](https://example.org/hb)", DAY).await; + let fenced = post(&pool, c, "```\nwibble --force\n```", DAY).await; + let italic = post(&pool, c, "an _emphatic_ yes", DAY).await; + + for (q, id) in [ + ("https://docs.example.org/guide/setup", url), + ("docs.example.org", url), + ("example", url), + ("guide", url), + ("config.prod.yaml", file), + ("yaml", file), + ("prod", file), + ("@example-scope/search-widget", package), + ("search-widget", package), + ("widget", package), + ("getUserName", identifier), + ("user", identifier), + ("UserName", identifier), + ("buzz_search", identifier), + ("search", identifier), + ("\"Ingrid\"", quoted), + ("Ingrid", quoted), + ("frobnicate", code), + ("crucial", bold), + ("handbook", link), + ("wibble", fenced), + ("emphatic", italic), + ] { + assert!(words(&fx, c, q).await.contains(&id), "{q}"); + } + fx.teardown(pool).await; +} + +/// Accented and unaccented spellings find each other. +#[tokio::test] +#[ignore = "requires Postgres and OpenSearch"] +async fn accents_fold() { + let (pool, fx, c) = setup().await; + let accented = post(&pool, c, "meet at the Café Zoë", DAY).await; + let unaccented = post(&pool, c, "meet at the Cafe Zoe", DAY).await; + let plain = post(&pool, c, "a naive resume", DAY).await; + + // Folded spellings are the same word, not a typo of it. + let scores = query_match(&fx, c, "cafe zoe").await; + let (folded, same) = ( + q_of(&scores, &accented, "accented"), + q_of(&scores, &unaccented, "unaccented"), + ); + assert!((folded - same).abs() <= same * 1e-3, "{folded} vs {same}"); + assert!(words(&fx, c, "naïve résumé").await.contains(&plain)); + fx.teardown(pool).await; +} + +/// A plural finds its singular and back, and the exact form ranks first. +#[tokio::test] +#[ignore = "requires Postgres and OpenSearch"] +async fn stems_match_below_the_exact_form() { + let (pool, fx, c) = setup().await; + let plural = post(&pool, c, "the queries were slow", DAY).await; + let singular = post(&pool, c, "the query was slow", DAY).await; + + let hits = words(&fx, c, "queries").await; + ranks_above(&hits, &plural, &singular, "exact plural first"); + let hits = words(&fx, c, "query").await; + ranks_above(&hits, &singular, &plural, "exact singular first"); + fx.teardown(pool).await; +} + +/// Prefix mode completes the last word only, and long machine tokens such +/// as `nostr:` URIs and hex ids get no prefixes while the message's other +/// words still do. +#[tokio::test] +#[ignore = "requires Postgres and OpenSearch"] +async fn prefix_mode_completes_the_last_word_but_not_long_tokens() { + let (pool, fx, c) = setup().await; + let planning = post( + &pool, + c, + "project planning milestone transcontinentalrailways", + DAY, + ) + .await; + let archive = post(&pool, c, "project archive", DAY).await; + let npub = format!("npub1{}", "q".repeat(58)); + let hex = "a3f9b2c4".repeat(8); + let machine = post( + &pool, + c, + &format!("ping nostr:{npub} about event {hex} and the roadmap"), + DAY, + ) + .await; + + let prefix = |q: &'static str| ranked(&fx, c, q, SearchMode::Prefix); + assert_eq!(prefix("project pla").await, vec![planning]); + let pro = prefix("pro").await; + assert!(pro.contains(&planning) && pro.contains(&archive)); + assert!( + ranked(&fx, c, "pro", SearchMode::FullText).await.is_empty(), + "full text does not complete words" + ); + assert_eq!( + prefix("transcontinentalrailw").await, + vec![planning], + "a partial word longer than the longest prefix matches by its start" + ); + assert_eq!(prefix("roadm").await, vec![machine]); + let variable = post( + &pool, + c, + "set BUZZ_OPENSEARCH_AWS_SIGV4_SERVICE to aoss", + DAY, + ) + .await; + assert_eq!( + prefix("set BUZZ_OPENSEARCH_AW").await, + vec![variable], + "part of an identifier too long for its own prefixes" + ); + assert!(prefix("npub1qqq").await.is_empty(), "no prefixes of a key"); + assert!( + prefix("a3f9b2c4a3").await.is_empty(), + "no prefixes of an id" + ); + assert_eq!( + words(&fx, c, &hex).await, + vec![machine], + "the whole id still matches" + ); + fx.teardown(pool).await; +} + +/// Prefix mode ranks every match: a strong match older than the newest 1000 +/// still comes first. +#[tokio::test] +#[ignore = "requires Postgres and OpenSearch"] +async fn prefix_mode_ranks_a_strong_match_older_than_the_newest_thousand() { + let (pool, fx, c) = setup().await; + let old = post(&pool, c, "planning planning planning planning", 3 * DAY).await; + sqlx::query( + "WITH rows AS ( \ + SELECT sha256((g || '/' || $1::text)::bytea) AS id, now() - make_interval(secs => g) AS at \ + FROM generate_series(1, 1000) g), \ + stored AS ( \ + INSERT INTO events (community_id, id, pubkey, created_at, kind, tags, content, sig) \ + SELECT $2, id, id, at, 9, '[]'::jsonb, 'planning notes', 'signature' FROM rows) \ + INSERT INTO search_outbox (community_id, event_id, event_created_at) \ + SELECT $2, id, at FROM rows", + ) + .bind(c.as_uuid().to_string()) + .bind(c.as_uuid()) + .execute(&pool) + .await + .expect("store 1000 newer, weaker matches"); + + let hits = ranked(&fx, c, "plan", SearchMode::Prefix).await; + assert_eq!(hits.first(), Some(&old)); + fx.teardown(pool).await; +} + +/// Between equal matches the newer ranks first, but an old exact match still +/// outranks recent weak ones. +#[tokio::test] +#[ignore = "requires Postgres and OpenSearch"] +async fn recency_breaks_close_calls_only() { + let (pool, fx, c) = setup().await; + let older = post(&pool, c, "standup moved to thursday", 40 * DAY).await; + let newer = post(&pool, c, "standup moved to thursday", 2 * DAY).await; + let hits = words(&fx, c, "standup thursday").await; + ranks_above(&hits, &newer, &older, "newer of two equal matches"); + + let old_exact = post(&pool, c, "incident rollback checklist", 2 * 365 * DAY).await; + let filler = (0..60) + .map(|i| format!("log{i}")) + .collect::>() + .join(" "); + let mut recent = Vec::new(); + for n in 0..5 { + recent.push( + post( + &pool, + c, + &format!("incident {filler} checklist {filler} {n}"), + n * 60, + ) + .await, + ); + } + let hits = words(&fx, c, "incident rollback checklist").await; + assert_eq!(hits.first(), Some(&old_exact), "old exact match first"); + assert_eq!(hits.len(), 6, "the weak matches are still found"); + fx.teardown(pool).await; +} + +/// Newest sort orders by time alone, whatever the match quality, so it +/// matches no typos: they would crowd out the word that was typed. +#[tokio::test] +#[ignore = "requires Postgres and OpenSearch"] +async fn newest_sort_ignores_relevance() { + let (pool, fx, c) = setup().await; + let strong = post(&pool, c, "migration migration plan", 3 * DAY).await; + let typo = post(&pool, c, "migraton notes", DAY).await; + let weak = post( + &pool, + c, + &format!("{} migration", "word ".repeat(80)), + 2 * DAY, + ) + .await; + + for mode in [SearchMode::FullText, SearchMode::Prefix] { + let hits: Vec<_> = fx + .service() + .search(&query(c, "migration", mode, SearchSort::Newest)) + .await + .expect("search") + .hits + .iter() + .map(|hit| hit.event_id) + .collect(); + assert_eq!(hits, vec![weak, strong], "{mode:?}"); + assert!(!hits.contains(&typo)); + } + fx.teardown(pool).await; +} + +/// Debug mode gives each hit's query match Q and age factor T, with +/// T = 0.2 + 0.8 × 0.5^(age / 30 days) and the hit's rank Q × T. +#[tokio::test] +#[ignore = "requires Postgres and OpenSearch"] +async fn debug_mode_returns_query_match_and_age() { + let (pool, fx, c) = setup().await; + let ages = [0, 30 * DAY, 60 * DAY, 3 * 365 * DAY]; + let mut ids = Vec::new(); + for age in ages { + ids.push(post(&pool, c, "telemetry dashboard", age).await); + } + + let scored = fx + .service() + .search_scored(&query( + c, + "telemetry dashboard", + SearchMode::FullText, + SearchSort::Relevance, + )) + .await + .expect("debug search"); + assert_eq!(scored.hits.len(), ages.len()); + for (id, age) in ids.iter().zip(ages) { + let hit = scored + .hits + .iter() + .find(|hit| &hit.hit.event_id == id) + .expect("hit"); + let expected = 0.2 + 0.8 * 0.5_f64.powf(age as f64 / (30 * DAY) as f64); + assert!( + (f64::from(hit.parts.age) - expected).abs() < 0.01, + "age {age}: T {} not {expected}", + hit.parts.age + ); + assert!(hit.parts.query_match > 0.0); + let rank = hit.parts.query_match * hit.parts.age; + assert!( + (rank - hit.hit.rank).abs() <= rank * 1e-3, + "rank {} is Q × T {rank}", + hit.hit.rank + ); + } + let in_order: Vec<_> = scored.hits.iter().map(|hit| hit.hit.event_id).collect(); + assert_eq!(in_order, ids, "equal matches, newest first"); + fx.teardown(pool).await; +} + +/// Relevance pages tile one order, so paging through a long list of +/// matches, as the relay's search scan does, returns each message once. The +/// order holds within the rescore window, where relevance results end: past +/// it, hits would keep a rank without the age factor and interleave with +/// the window's. +#[tokio::test] +#[ignore = "requires Postgres and OpenSearch"] +async fn relevance_pages_tile_one_order_up_to_the_rescore_window() { + let (pool, fx, c) = setup().await; + for _ in 0..1_100 { + post(&pool, c, "quarterly report", 365 * DAY).await; + } + let page = |page: u32, per_page: u32| SearchQuery { + page, + per_page, + ..query(c, "quarterly", SearchMode::FullText, SearchSort::Relevance) + }; + let hits = |page: SearchQuery| { + let fx = &fx; + async move { fx.service().search(&page).await.expect("search").hits } + }; + + let mut seen = std::collections::HashSet::new(); + for n in 1..=10 { + let hits = hits(page(n, 100)).await; + assert_eq!(hits.len(), 100, "page {n} is full"); + for hit in hits { + assert!(seen.insert(hit.event_id), "page {n} repeats a hit"); + } + } + assert!( + hits(page(11, 100)).await.is_empty(), + "results end at the window" + ); + assert_eq!( + hits(page(4, 300)).await.len(), + 100, + "a page across it is cut" + ); + fx.teardown(pool).await; +} diff --git a/crates/buzz-search/tests/postgres_opensearch_search.rs b/crates/buzz-search/tests/postgres_opensearch_search.rs index a8b81ffbcf0..2f1bb5aec85 100644 --- a/crates/buzz-search/tests/postgres_opensearch_search.rs +++ b/crates/buzz-search/tests/postgres_opensearch_search.rs @@ -12,7 +12,11 @@ use search_suite::{search_suite_tests, Backend}; // Not run here, with the reason: // - kind0_* and artifact_*: kinds 0 and 45010 are not searchable kinds; -// - prefix_*: prefix mode is reworked with prefix analysis (issue 06). +// - prefix_mode_matches_final_token_prefix_without_changing_full_text and +// prefix_relevance_ranks_only_the_newest_matches: Postgres' own prefix +// rules (a three-character minimum, all words required, only the newest +// 1000 matches ranked). OpenSearch's prefix and word matching are checked +// in postgres_opensearch_relevance. search_suite_tests! { Backend::OpenSearch; #[ignore = "requires Postgres and OpenSearch"] @@ -33,6 +37,8 @@ search_suite_tests! { fn author_only_kinds_are_storage_level_unsearchable, fn p_gated_persistent_kinds_have_storage_null_tsvector, fn deleted_events_are_excluded, + fn prefix_mode_handles_tsquery_boundary_punctuation, + fn prefix_mode_preserves_storage_level_privacy_exclusions, } use std::time::Duration; @@ -45,7 +51,7 @@ use buzz_db::user_deletion::content_batches::ContentBatchOptions; use buzz_db::user_deletion::ExecutionMode; use buzz_db::{search_outbox, Db, DbConfig, DeletionTarget}; use buzz_search::indexer::{Indexer, IndexerError}; -use buzz_search::opensearch::{OpenSearchConfig, SearchIndex}; +use buzz_search::opensearch::{OpenSearchConfig, SearchIndex, MAPPING_VERSION}; use buzz_search::{ChannelScope, SearchMode, SearchQuery, SearchService, SearchSort}; use nostr::{Event, EventBuilder, Keys, Kind, Tag, Timestamp}; use opensearch::http::transport::Transport; @@ -312,7 +318,9 @@ async fn a_failed_bulk_item_keeps_only_its_own_row() { let prefix = format!("test-{}-", Uuid::new_v4().simple()); let response = raw_client() .indices() - .create(IndicesCreateParts::Index(&format!("{prefix}messages-v1"))) + .create(IndicesCreateParts::Index(&format!( + "{prefix}messages-v{MAPPING_VERSION}" + ))) .body(serde_json::json!({ "mappings": { "properties": { "content": { "type": "keyword" } } }, "aliases": { format!("{prefix}messages"): {} } @@ -390,7 +398,7 @@ async fn writes_never_create_an_index() { let exists = raw_client() .indices() .exists(IndicesExistsParts::Index(&[&format!( - "{prefix}messages-v1" + "{prefix}messages-v{MAPPING_VERSION}" )])) .send() .await @@ -406,6 +414,59 @@ async fn writes_never_create_an_index() { index.delete().await.expect("delete index"); } +/// A relay on a newer mapping version neither adopts nor writes into an +/// older version's index behind the alias: `ensure`, which the indexer runs +/// before every pass, refuses it and names the fix. Once that index is +/// deleted, `ensure` creates this version's and indexing resumes. +#[tokio::test] +#[ignore = "requires Postgres and OpenSearch"] +async fn an_older_mapping_version_behind_the_alias_is_refused() { + let db = sync_db().await; + let prefix = format!("test-{}-", Uuid::new_v4().simple()); + let older = format!("{prefix}messages-v{}", MAPPING_VERSION - 1); + let response = raw_client() + .indices() + .create(IndicesCreateParts::Index(&older)) + .body(serde_json::json!({ + "mappings": { "properties": { "content": { "type": "text" } } }, + "aliases": { format!("{prefix}messages"): {} } + })) + .send() + .await + .expect("create older index"); + assert!(response.status_code().is_success()); + let index = SearchIndex::new(&OpenSearchConfig { + url: opensearch_url(), + basic_auth: None, + aws_sigv4: None, + index_prefix: prefix.clone(), + }) + .expect("client"); + + let refused = index.ensure().await.expect_err("an older index is refused"); + assert!(refused.to_string().contains(&older), "{refused}"); + + raw_client() + .indices() + .delete(opensearch::indices::IndicesDeleteParts::Index(&[&older])) + .send() + .await + .expect("delete older index"); + index.ensure().await.expect("create this version's index"); + let community = search_suite::mk_community(db.pool(), "versioned.example").await; + db.insert_event(community, &message(&Keys::generate(), "versioned"), None) + .await + .expect("insert"); + Indexer::new(db.clone(), index.clone()) + .drain() + .await + .expect("drain"); + index.refresh().await.expect("refresh"); + let service = SearchService::with_opensearch(db.pool().clone(), index.clone()); + assert_eq!(find(&service, community, "versioned").await.len(), 1); + index.delete().await.expect("delete index"); +} + fn signed_at(event: &Event) -> chrono::DateTime { chrono::DateTime::from_timestamp(event.created_at.as_secs() as i64, 0).expect("timestamp") } diff --git a/crates/buzz-search/tests/search_suite/mod.rs b/crates/buzz-search/tests/search_suite/mod.rs index 5f840b67d4b..5cbf0aa1634 100644 --- a/crates/buzz-search/tests/search_suite/mod.rs +++ b/crates/buzz-search/tests/search_suite/mod.rs @@ -107,13 +107,22 @@ pub struct Searcher<'a> { impl Searcher<'_> { /// [`SearchService::search`], once the backend has caught up. pub async fn search(&self, query: &SearchQuery) -> Result { - if let Some((indexer, index)) = &self.fixture.opensearch { - indexer.drain().await.expect("drain the search outbox"); - index.refresh().await.expect("refresh the test index"); - } + self.catch_up().await; self.fixture.service.search(&self.routed(query)).await } + /// [`SearchService::search_scored`], once the backend has caught up. + pub async fn search_scored( + &self, + query: &SearchQuery, + ) -> Result { + self.catch_up().await; + self.fixture + .service + .search_scored(&self.routed(query)) + .await + } + /// `query` as the backend under test runs it. A search of every kind /// stays on Postgres, so on OpenSearch it names the indexed kinds: the /// same search there, since the index holds no other kind. @@ -124,6 +133,13 @@ impl Searcher<'_> { } query } + + async fn catch_up(&self) { + if let Some((indexer, index)) = &self.fixture.opensearch { + indexer.drain().await.expect("drain the search outbox"); + index.refresh().await.expect("refresh the test index"); + } + } } /// A new, empty message index of the calling test's own on the test cluster. diff --git a/docs/opensearch-search-deployment.md b/docs/opensearch-search-deployment.md index f0e3181a8f3..12c44248df5 100644 --- a/docs/opensearch-search-deployment.md +++ b/docs/opensearch-search-deployment.md @@ -122,13 +122,29 @@ provider is read at startup, so a change there takes a restart: BUZZ_FEATURE_FLAGS_PROVIDER=environment BUZZ_FEATURE_FLAG_SEARCH_BACKEND=1 just relay ``` -Prefix-mode searches, and searches that name a kind other than a message -kind (people search) or no kinds, stay on Postgres at every value. +Searches that name a kind other than a message kind (people search) or no +kinds stay on Postgres at every value. The backends differ on edited messages: Postgres matches the text a message -was stored with, and the index holds its latest edit. So shadow overlap -drops for searches that touch edited messages, and moving to `2` changes -their results. +was stored with, and the index holds its latest edit. OpenSearch +also matches words one or two typos away, when sorted by relevance. So shadow overlap drops for +searches that touch edited messages or misspell a word, and moving to `2` +changes their results. Prefix searches overlap less too: OpenSearch +completes a last word from 2 characters where Postgres needs 3 (a shorter +one finds nothing there), and the two rank prefix matches differently. + +A new message is searchable on OpenSearch only after the index refreshes: +every 30 seconds on a self-hosted cluster, on its own schedule on +Serverless. Postgres finds it as soon as it is stored. + +## Changing the mapping + +The index name carries its mapping version (`buzz-messages-v2`), and a relay +never writes into an index of another version: if the alias `buzz-messages` +points elsewhere, every indexing pass fails and the outbox grows. To move to +a new version, keep `search.backend` at `0` and delete the old index. The +relay creates the new index, clears the backfill progress and backfills +every community again. If `buzz_search_index_rejected_total` rises, investigate the rejection and fix the cause. The relay retries rejected rows automatically. A sustained