Skip to content

Commit c711136

Browse files
salman1993claude
andauthored
feat(search): OpenSearch relevance with typos, prefixes, phrases and recency (#9864)
## Summary Stacked on #9863; #9838, #9862 and #9947 are merged. The earlier PRs fill an OpenSearch message index and add a relay-wide switch with a shadow mode. Until now the OpenSearch query was a plain word match, so shadow results could not be judged. This PR adds the relevance model: typos, partial words, rare words, phrases and recency. Search for users is unchanged while the flag stays at 0. **Mapping version 2 (`buzz-messages-v2`).** Message text is indexed three ways: whole words (with accents folded and compound words split), stems, and prefixes of 2 to 10 characters. A partial word longer than 10 characters is cut to 10 at query time, so it still matches. **Query.** It lives in `crates/buzz-search/src/opensearch/relevance.rs`: - Exact words score highest. A stem match counts 0.4 and a typo match 0.3. Typos keep the first letter fixed. In prefix mode the unfinished last word also matches with a typo once it has 4 characters; a shorter one is a single edit from too many other words. - Newest-first sort matches no typos and computes no scores. For a short word most typo matches are other words (`log` and `lag`), and with time as the only order they pushed exact matches out: on a million messages `log` matched 390 messages exactly and 1,623 with typos. Scoring made a newest-first search for a common word about six times slower (13 ms against 2 ms). - The query is split at `_`, `.` and case changes like the indexed text, so part of an identifier finds it (`snake_case` of `snake_case_name`, `OutboxBatch` of `SearchOutboxBatch`, `BUZZ_OPEN` of a longer variable name). `foo_bar` therefore also finds a message holding `foo` and `bar` apart. - Sorted by relevance, a query of three or more words needs most of them, not all (`2<75%`). Sorted by newest it needs every word, and in prefix mode the word being typed is always required. - A query keeps its words up to 64 parts (identifiers split at `_`, `.` and case changes) and matches typos only up to 16, so a pasted line stays under OpenSearch's 1,024-clause limit. - Full-text searches with a `"phrase"`, a `-word` or `or` stay on Postgres (`unsupported_syntax`). - The top 1,000 hits are rescored. A phrase or near-phrase match gets a bonus, and the score is scaled by age: `0.2 + 0.8 × 0.5^(age / 30 days)`. An old message keeps at least a fifth of its score. - Relevance results end at the rescore window. Paging past it would repeat hits, so the window is tied at compile time to the largest page the relay scans (1,000). **Upgrade.** `ensure()` refuses to start indexing when the alias points at an index with another mapping version, and searches fail rather than read it. Rows stay queued. The fix is in `docs/opensearch-search-deployment.md`: with the flag at 0 and every relay upgraded, delete the old index, and the relay creates the new one, clears the backfill progress and rebuilds it. The same doc now covers edits, the refresh delay and lag after an outage. Worth knowing: - The prefix field is the main cost. On 1 million synthetic messages the index was about 1.6 KB per message, and prefixes were about half of it. That is why the cap is 10 characters and not 20. OpenSearch's built-in `index_prefixes` came out larger than edge n-grams. - Bulk indexing on this mapping was about 3.8k documents per second on a laptop, roughly a quarter of the rate without the prefix field. Rebuild time is the number to watch. - A full rebuild of 1 million messages through the relay ran at about 1.3k, 2.1k, 2.9k and 3.0k documents per second at 1, 2, 4 and 8 workers. Scaling stops at 4 because the backfill and the drain take turns. Live messages were indexed with a median lag under 1 second during the rebuild. - The index is created with the default single shard. - The weights are first values. Shadow mode exists to tune them. ### Related issue N/A. Stacked on #9863; only the top commit is this PR. ### Testing On a laptop with local Postgres and OpenSearch 2.19.3 (512 MiB heap), 1 million synthetic messages: - Query p50 was 4, 6 and 10 ms for queries that match 10k, 100k and 790k messages. - A real relay with the flag at 1 ran prefix and typo searches; each wrote a shadow comparison line with OpenSearch hits. - A leftover version 1 index was refused and rows stayed queued. The documented rebuild brought the index up at version 2. - `relevance_pages_tile_one_order_up_to_the_rescore_window` checks that pages do not repeat or skip hits. Not measured: Amazon OpenSearch Serverless, production-shaped data, and relevance quality against real queries. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Salman Mohammed <smohammed@squareup.com> Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
1 parent 13bd36a commit c711136

10 files changed

Lines changed: 1567 additions & 192 deletions

File tree

‎crates/buzz-relay/src/handlers/search_backend_postgres_tests.rs‎

Lines changed: 78 additions & 83 deletions
Original file line numberDiff line numberDiff line change
@@ -885,87 +885,78 @@ async fn outbox_gauges_follow_a_paused_and_resumed_indexer() {
885885
.await;
886886
}
887887

888-
/// Prefix mode and full-text search syntax (a phrase, an exclusion, `or`),
889-
/// which OpenSearch does not serve yet, stay on Postgres at every value and
890-
/// are counted: shadow skips the comparison, and 2 serves them from
891-
/// Postgres, so an exclusion still excludes. Not a fallback: OpenSearch is
892-
/// never tried.
893-
/// Mutation: route prefix searches like word searches → RED. Drop the syntax
894-
/// check → RED (the cluster is contacted, and at 2 the search fails).
888+
/// Prefix mode follows the flag like word searches: at 1 Postgres serves
889+
/// and OpenSearch shadows it, at 2 OpenSearch serves.
890+
/// Mutation: keep prefix searches on Postgres → RED (no shadow search at 1,
891+
/// and at 2 the OpenSearch-only word finds nothing).
895892
#[tokio::test(flavor = "current_thread")]
896-
#[ignore = "requires Postgres and Redis"]
897-
async fn searches_the_index_cannot_parse_stay_on_postgres() {
893+
#[ignore = "requires Postgres, Redis and OpenSearch"]
894+
async fn prefix_searches_follow_the_flag() {
898895
let recorder = DebuggingRecorder::new();
899896
let _metrics = metrics::set_default_local_recorder(&recorder);
900897
let mut recorded = Recorded::new(&recorder);
901-
let cluster = FakeCluster::start(Answer::Error).await;
902-
let f = Fixture::new(cluster.index.clone(), Duration::from_secs(1)).await;
898+
let f = Fixture::on_opensearch().await;
903899
let c = f.community().await;
904-
let needle = word("prefixed");
905-
let excluded = word("excluded");
906-
let message = f.post(&c, c.private, &needle).await;
907-
let other = f.post(&c, c.private, &format!("{needle} {excluded}")).await;
908-
let mut both = vec![message.id.to_bytes(), other.id.to_bytes()];
909-
both.sort();
910-
let only = vec![message.id.to_bytes()];
911-
let query = |q: String, mode: buzz_search::SearchMode| buzz_search::SearchQuery {
900+
901+
// Postgres holds `pg_word`; the index holds the message under `os_word`.
902+
// Both stay short enough for the index to keep their prefixes.
903+
let pg_word = word("prefixpg")[..16].to_owned();
904+
let os_word = word("prefixos")[..16].to_owned();
905+
let message = f.post(&c, c.private, &pg_word).await;
906+
f.index_as(&c, &message, &os_word, c.private).await;
907+
let query = |word: &str| buzz_search::SearchQuery {
912908
community: c.tenant.community(),
913-
q,
909+
q: word[..12].to_owned(),
914910
channel_scope: buzz_search::ChannelScope::Channels(vec![c.private]),
915911
kinds: Some(vec![9]),
916912
authors: None,
917913
since: None,
918914
until: None,
919915
page: 1,
920916
per_page: 10,
921-
mode,
917+
mode: buzz_search::SearchMode::Prefix,
922918
sort: buzz_search::SearchSort::Relevance,
923919
};
924-
let prefix = buzz_search::SearchMode::Prefix;
925-
let words = buzz_search::SearchMode::FullText;
926-
let searches = [
927-
(query(needle[..12].to_owned(), prefix), &both),
928-
(query(format!("{needle} -{excluded}"), words), &only),
929-
(query(format!("\"{needle}\" -{excluded}"), words), &only),
930-
(
931-
query(format!("-{excluded} {needle} OR missing"), words),
932-
&only,
933-
),
934-
];
920+
let found = |hits: buzz_search::SearchResult| {
921+
hits.hits.iter().map(|hit| hit.event_id).collect::<Vec<_>>()
922+
};
935923

936-
for (value, setting) in [(1, "shadow"), (2, "opensearch")] {
937-
f.set_backend(value);
938-
for (query, expected) in &searches {
939-
let hits = f.state.search.search(query).await.expect("search");
940-
let mut ids: Vec<[u8; 32]> = hits.hits.iter().map(|hit| hit.event_id).collect();
941-
ids.sort();
942-
assert_eq!(&ids, *expected, "{setting} {}", query.q);
943-
}
944-
recorded.collect();
945-
for (reason, count) in [("unsupported_mode", 1), ("unsupported_syntax", 3)] {
946-
assert_eq!(
947-
recorded.counter(
948-
"buzz_search_opensearch_skipped_total",
949-
&[("setting", setting), ("reason", reason)]
950-
),
951-
count,
952-
"{setting} {reason}"
953-
);
954-
}
955-
recorded.counters.clear();
956-
}
957-
tokio::time::sleep(Duration::from_millis(200)).await;
958-
assert_eq!(cluster.connections(), 0);
924+
f.set_backend(1);
925+
let hits = f
926+
.state
927+
.search
928+
.search(&query(&pg_word))
929+
.await
930+
.expect("search");
931+
assert_eq!(found(hits), vec![message.id.to_bytes()], "Postgres serves");
932+
recorded.wait_for_shadows(1).await;
933+
assert_eq!(recorded.requests("opensearch", "shadow", "zero_results"), 1);
934+
935+
f.set_backend(2);
936+
let hits = f
937+
.state
938+
.search
939+
.search(&query(&os_word))
940+
.await
941+
.expect("search");
942+
assert_eq!(
943+
found(hits),
944+
vec![message.id.to_bytes()],
945+
"OpenSearch serves"
946+
);
947+
recorded.collect();
948+
assert_eq!(recorded.requests("opensearch", "primary", "hits"), 1);
949+
f.delete().await;
959950
}
960951

961-
/// The index holds only message kinds, so a search that names another kind,
962-
/// mixes one in, or names no kinds stays on Postgres at 1 and 2, is not
963-
/// shadowed, and counts as skipped with `unindexed_kinds`. That rule comes
964-
/// before the mode rule, so a people search (kind 0, in prefix mode as
965-
/// clients send it) counts there too. A message-kind search at 2 still
966-
/// reaches the cluster.
967-
/// Mutation: drop the kind check from routing → RED (the cluster is
968-
/// contacted and fails the word searches at 2).
952+
/// The index holds only message kinds, so a search that names another kind
953+
/// (a people search for kind 0, in prefix mode as clients send it), mixes
954+
/// one in, or names no kinds stays on Postgres at 1 and 2, is not shadowed,
955+
/// and counts as skipped. So does a full-text search with a phrase, an
956+
/// exclusion or `or`, which only Postgres reads as such. A message-kind
957+
/// search at 2 still reaches the cluster.
958+
/// Mutation: drop the kind or syntax check from routing → RED (the cluster
959+
/// is contacted and fails the searches at 2).
969960
#[tokio::test(flavor = "current_thread")]
970961
#[ignore = "requires Postgres and Redis"]
971962
async fn searches_of_unindexed_kinds_stay_on_postgres() {
@@ -987,10 +978,7 @@ async fn searches_of_unindexed_kinds_stay_on_postgres() {
987978
.expect("store the profile");
988979
let query = |kinds: Option<Vec<i32>>, mode: buzz_search::SearchMode| buzz_search::SearchQuery {
989980
community: c.tenant.community(),
990-
q: match mode {
991-
buzz_search::SearchMode::FullText => needle.clone(),
992-
buzz_search::SearchMode::Prefix => needle[..12].to_owned(),
993-
},
981+
q: needle[..12].to_owned(),
994982
channel_scope: buzz_search::ChannelScope::ChannelsOrChannelLess(vec![c.private]),
995983
kinds,
996984
authors: None,
@@ -1018,45 +1006,52 @@ async fn searches_of_unindexed_kinds_stay_on_postgres() {
10181006
};
10191007
let mut both = vec![message.id.to_bytes(), profile.id.to_bytes()];
10201008
both.sort();
1021-
let words = buzz_search::SearchMode::FullText;
10221009
let prefix = buzz_search::SearchMode::Prefix;
10231010

10241011
f.set_backend(2);
1025-
assert_eq!(
1026-
found(query(Some(vec![0]), words)).await,
1027-
vec![profile.id.to_bytes()]
1028-
);
1029-
assert_eq!(found(query(Some(vec![9, 0]), words)).await, both);
1030-
assert_eq!(found(query(None, words)).await, both);
10311012
assert_eq!(
10321013
found(query(Some(vec![0]), prefix)).await,
10331014
vec![profile.id.to_bytes()]
10341015
);
1016+
assert_eq!(found(query(Some(vec![9, 0]), prefix)).await, both);
1017+
assert_eq!(found(query(None, prefix)).await, both);
10351018
f.set_backend(1);
1036-
assert_eq!(found(query(Some(vec![9, 0]), words)).await, both);
1019+
assert_eq!(found(query(Some(vec![9, 0]), prefix)).await, both);
1020+
f.set_backend(2);
1021+
for q in [
1022+
format!("\"{needle}\""),
1023+
format!("{needle} -absent"),
1024+
format!("{needle} or absent"),
1025+
] {
1026+
let syntax = buzz_search::SearchQuery {
1027+
q,
1028+
..query(Some(vec![9]), buzz_search::SearchMode::FullText)
1029+
};
1030+
assert_eq!(found(syntax).await, vec![message.id.to_bytes()]);
1031+
}
10371032

10381033
tokio::time::sleep(Duration::from_millis(200)).await;
10391034
assert_eq!(cluster.connections(), 0, "OpenSearch was contacted");
10401035
recorded.collect();
1041-
let skipped = |setting: &str, reason: &str| {
1036+
let skipped = |setting: &str| {
10421037
recorded.counter(
10431038
"buzz_search_opensearch_skipped_total",
1044-
&[("setting", setting), ("reason", reason)],
1039+
&[("setting", setting), ("reason", "unindexed_kinds")],
10451040
)
10461041
};
1042+
assert_eq!((skipped("opensearch"), skipped("shadow")), (3, 1));
10471043
assert_eq!(
1048-
(
1049-
skipped("opensearch", "unindexed_kinds"),
1050-
skipped("shadow", "unindexed_kinds"),
1051-
skipped("opensearch", "unsupported_mode"),
1044+
recorded.counter(
1045+
"buzz_search_opensearch_skipped_total",
1046+
&[("setting", "opensearch"), ("reason", "unsupported_syntax")],
10521047
),
1053-
(4, 1, 0)
1048+
3
10541049
);
10551050

10561051
f.set_backend(2);
10571052
f.state
10581053
.search
1059-
.search(&query(Some(vec![9]), words))
1054+
.search(&query(Some(vec![9]), prefix))
10601055
.await
10611056
.expect_err("a message search at 2 goes to the failing cluster");
10621057
}

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

Lines changed: 30 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,12 @@
1212
//! the other. It is read on every search, so a provider that changes values
1313
//! while the relay runs switches it without a restart.
1414
//!
15-
//! Searches the index cannot answer stay on Postgres at every setting:
16-
//! prefix mode, full-text search syntax (a `"phrase"`, a `-word` exclusion
17-
//! or `or`), and any search that names a kind outside
18-
//! [`buzz_db::search_outbox::SEARCHABLE_KINDS`] or names no kinds. That is
19-
//! a routing rule known before the search runs, not a fallback: an
15+
//! A search that names a kind outside
16+
//! [`buzz_db::search_outbox::SEARCHABLE_KINDS`], or names no kinds, stays on
17+
//! Postgres at every setting: the index would silently drop those results.
18+
//! So does a full-text search using syntax the index does not parse (a
19+
//! `"phrase"`, a `-word` exclusion or `or`). That is a routing rule known
20+
//! before the search runs, not a fallback: an
2021
//! OpenSearch failure at setting 2 still fails the search.
2122
//!
2223
//! Metrics and the shadow log line never carry query text.
@@ -162,22 +163,21 @@ impl OpenSearchBackend {
162163
self.shadow_deadline = deadline;
163164
}
164165

166+
/// The index serving `query`, if the setting is OpenSearch and the
167+
/// index can serve it.
168+
pub(crate) fn serving(&self, query: &SearchQuery) -> Option<&SearchIndex> {
169+
(self.selection.setting() == BackendSetting::OpenSearch && postgres_only(query).is_none())
170+
.then_some(&self.index)
171+
}
172+
165173
/// Decide where `query` runs, starting the shadow search if it gets one.
166174
pub(crate) fn route(&self, query: &SearchQuery) -> Route<'_> {
167175
let setting = self.selection.setting();
168176
if setting == BackendSetting::Postgres {
169177
return Route::Postgres;
170178
}
171-
if !index_holds_kinds(query) {
172-
skipped(setting, "unindexed_kinds");
173-
return Route::Postgres;
174-
}
175-
if query.mode != SearchMode::FullText {
176-
skipped(setting, "unsupported_mode");
177-
return Route::Postgres;
178-
}
179-
if uses_search_syntax(&query.q) {
180-
skipped(setting, "unsupported_syntax");
179+
if let Some(reason) = postgres_only(query) {
180+
skipped(setting, reason);
181181
return Route::Postgres;
182182
}
183183
if setting == BackendSetting::OpenSearch {
@@ -204,12 +204,24 @@ impl OpenSearchBackend {
204204
}
205205
}
206206

207+
/// Why `query` must run on Postgres whatever the setting, if it must.
208+
fn postgres_only(query: &SearchQuery) -> Option<&'static str> {
209+
if !index_holds_kinds(query) {
210+
Some("unindexed_kinds")
211+
} else if query.mode == SearchMode::FullText && uses_search_syntax(&query.q) {
212+
Some("unsupported_syntax")
213+
} else {
214+
None
215+
}
216+
}
217+
207218
/// Whether `text` uses syntax that Postgres' `websearch_to_tsquery` reads
208-
/// and the index's plain word match does not: a `"` (a phrase), a word that
219+
/// and the index's word match does not: a `"` (a phrase), a word that
209220
/// starts with `-` (an exclusion), or a standalone `or`. The index would
210221
/// match the words of a phrase anywhere and require an excluded word, so
211-
/// these searches stay on Postgres. It errs toward Postgres: a `-` that
212-
/// Postgres reads as part of a word still counts.
222+
/// these full-text searches stay on Postgres. It errs toward Postgres: a
223+
/// `-` that Postgres reads as part of a word still counts. Prefix searches
224+
/// read no syntax on either backend.
213225
fn uses_search_syntax(text: &str) -> bool {
214226
text.contains('"')
215227
|| text

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

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,8 +50,8 @@ pub use backend::{BackendSetting, SEARCH_BACKEND_FLAG};
5050
pub use buzz_core::CommunityId;
5151
pub use error::SearchError;
5252
pub use query::{
53-
search, search_profile_names, ChannelScope, SearchHit, SearchMode, SearchQuery, SearchResult,
54-
SearchSort, PROFILE_NAMES_PER_PAGE_MAX,
53+
search, search_profile_names, ChannelScope, ScoreParts, ScoredHit, ScoredResult, SearchHit,
54+
SearchMode, SearchQuery, SearchResult, SearchSort, PROFILE_NAMES_PER_PAGE_MAX,
5555
};
5656

5757
use std::sync::Arc;
@@ -162,6 +162,20 @@ impl SearchService {
162162
}
163163
}
164164

165+
/// [`SearchService::search`] with each hit's score parts, for tests and
166+
/// ranking evaluation. It asks the backend that would serve the search,
167+
/// Postgres while the relay shadows, and records no metrics.
168+
pub async fn search_scored(&self, query: &SearchQuery) -> Result<ScoredResult, SearchError> {
169+
match self
170+
.opensearch
171+
.as_ref()
172+
.and_then(|opensearch| opensearch.serving(query))
173+
{
174+
Some(index) => index.search_scored(query, opensearch::SEARCH_TIMEOUT).await,
175+
None => query::search(&self.pool, query).await.map(Into::into),
176+
}
177+
}
178+
165179
/// Find people by profile name, and by verified profile names signed by
166180
/// `verified_by`; see [`search_profile_names`].
167181
pub async fn search_profile_names(

0 commit comments

Comments
 (0)