Skip to content

Commit dfda5fc

Browse files
salman1993claude
andauthored
feat(search): pick the search backend per relay and shadow-compare OpenSearch (#9863)
## Summary Follows #9838 and #9862 (indexing, deletes, edits, backfill, workers), both merged. After those two, OpenSearch holds a full copy of the message index but nothing reads it. This PR adds the switch that picks a search backend for the whole relay, and a shadow mode that compares the two without users seeing it. **The switch.** An integer feature flag, `search.backend`, holds one value for the whole relay. It is evaluated for the relay process, not for the searched community, so a relay never serves some communities from Postgres and others from OpenSearch. With LaunchDarkly a change applies within seconds and is the rollback; with the environment provider it takes a restart. | Value | Behavior | | --- | --- | | 0 (default) | Postgres answers. OpenSearch is not queried. | | 1 | Postgres answers. The same query also runs on OpenSearch, off the response path. | | 2 | OpenSearch answers. | At value 2 a failure returns an error, and a timeout returns the same `query timed out` reason and 503 as a Postgres timeout. A search is bounded at 15 seconds, below Postgres's 20, and the bound is sent to OpenSearch too. It does not fall back to Postgres, so a broken cluster is visible and not hidden behind slow searches. In every mode the relay re-reads hits from Postgres and re-checks access before it returns them. **Shadow mode.** The shadow search runs alongside the Postgres search, off the response path: the response never waits for it. It has a 2 second deadline and at most 32 OpenSearch queries run at once; beyond that they are dropped and counted. Only first pages are compared. The result is the overlap of the two top-10 lists, recorded in `buzz_search_shadow_overlap_ratio` and in one log line, "search shadow comparison". The log line carries no query text. **Metrics.** `buzz_search_requests_total{backend,role,outcome}` (a search that ran out of time counts as `timeout`, apart from `error`), `buzz_search_duration_seconds`, `buzz_search_opensearch_skipped_total{setting,reason}` and `buzz_search_backend_flag_invalid_total`. The relay holding the indexer lease also samples `buzz_search_outbox_depth` and `buzz_search_index_lag_seconds` every 15 seconds, so the fleet reads the queue once per interval. **Only searches the index can answer go to it.** The index holds five message kinds. At values 1 and 2 a search goes to OpenSearch only when it names kinds and all of them are indexed. Any other search runs on Postgres and is not shadowed; `buzz_search_opensearch_skipped_total` counts it with the reason `unindexed_kinds`. Prefix searches (`unsupported_mode`) and full-text searches with a `"phrase"`, a `-word` exclusion or `or` (`unsupported_syntax`) also stay on Postgres: the index matches plain words only, so it would match a phrase's words anywhere and require an excluded word. Worth knowing: - A search that names no kinds stays on Postgres at every value. - The desktop app sends full-text searches only for phrases and exclusions, and prefix searches otherwise, so both stay on Postgres. Until the index serves them, shadow mode compares mostly CLI, HTTP bridge and agent searches. - Postgres search does not see edits; OpenSearch indexes the edited text. This lowers overlap for edited messages and is a visible change at value 2. - A new message is searchable in OpenSearch only after the index refresh, up to 30 seconds. - The environment flag provider reads the value at startup, so a change needs a restart. - Relevance in this PR is still the plain match from #9838. The next PR in the stack replaces it. ### Related issue N/A. ### Testing A real relay built from this branch, with its own database and an OpenSearch 2.19.3 container, started with `BUZZ_FEATURE_FLAGS_PROVIDER=environment BUZZ_FEATURE_FLAG_SEARCH_BACKEND=<n>`. Each value was checked through a NIP-50 `REQ` and through the HTTP bridge (`buzz messages search`), counting queries with OpenSearch's `query_total`: - **0:** Postgres results; OpenSearch received no query. - **1:** Postgres results; each search added one OpenSearch query and one "search shadow comparison" line (overlap 1.0 once the index had refreshed). No log line held the search word. `/metrics` showed the duration and overlap histograms, request counts for both backends, and the outbox gauges. - **2:** After an edit, a search for a word only the edited text has found the message, so OpenSearch answered. With OpenSearch stopped, NIP-50 returned `CLOSED` (`error: search failed`) and the bridge returned HTTP 500. - **99:** Postgres results with OpenSearch stopped; `buzz_search_backend_flag_invalid_total` counted each search. - **No `BUZZ_OPENSEARCH_URL`:** Postgres results and Postgres request metrics; no OpenSearch or outbox metrics. - **Two relays:** only the lease holder reported the outbox gauges. After it stopped, the other took the lease and began reporting them. Relay tests also cover: timeouts (a hanging cluster, and `timed_out: true`) counted as `timeout` at 1 and 2 and closed as `query timed out` at 2, verified to fail when timeouts count as errors; prefix, phrase, exclusion and `or` searches served by Postgres at 1 and 2 without contacting the cluster, verified to fail without the syntax rule; a removed member, a document of another community, and a deleted message left in the index, all dropped at 2. Not tested: a remote flag provider (LaunchDarkly), and production traffic. 🤖 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 634673b commit dfda5fc

18 files changed

Lines changed: 1781 additions & 53 deletions

‎Cargo.lock‎

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎crates/buzz-relay/src/api/mod.rs‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -56,13 +56,14 @@ pub(crate) fn db_read_error(
5656
read_error(context, e.is_statement_cancelled(), e.kind())
5757
}
5858

59-
/// [`db_read_error`] for a search: a search cancelled by the search pool's
60-
/// statement timeout gets the same 503 `query timed out`.
59+
/// [`db_read_error`] for a search: a search that ran out of time (the
60+
/// Postgres statement timeout or an OpenSearch timeout) gets the same 503
61+
/// `query timed out`.
6162
pub(crate) fn search_read_error(
6263
context: &str,
6364
e: &buzz_search::SearchError,
6465
) -> (StatusCode, Json<serde_json::Value>) {
65-
read_error(context, e.is_statement_cancelled(), e.kind())
66+
read_error(context, e.is_timeout(), e.kind())
6667
}
6768

6869
/// Only the error kind is logged: DB error text can repeat a bound value.

‎crates/buzz-relay/src/feature_flags.rs‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,12 @@ impl FeatureFlags {
140140
self.evaluator.as_ref()
141141
}
142142

143+
/// A handle to the shared evaluator, for consumers that outlive a borrow
144+
/// (the search service reads `search.backend` on every search).
145+
pub fn shared_evaluator(&self) -> Arc<dyn FlagEvaluator> {
146+
Arc::clone(&self.evaluator)
147+
}
148+
143149
/// Report provider health after a round of evaluations: log malformed
144150
/// environment values once each, and publish whether the provider has
145151
/// initialized (`buzz_feature_flags_ready`). It does not track the

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,8 @@ pub mod report;
6767
pub mod report_resolution;
6868
/// REQ handler — subscribe, deliver historical events, then EOSE.
6969
pub mod req;
70+
#[cfg(test)]
71+
mod search_backend_postgres_tests;
7072
/// NIP-29 and NIP-25 side-effect handlers.
7173
pub mod side_effects;
7274
mod solo_member_role;

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

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1887,11 +1887,12 @@ fn history_read_closed_reason(e: &buzz_db::DbError) -> &'static str {
18871887
/// (e.g. the read replica it queries is down).
18881888
pub(crate) const SEARCH_FAILED_CLOSED: &str = "error: search failed";
18891889

1890-
/// CLOSED reason for a failed NIP-50 search: a search cancelled by the search
1891-
/// pool's statement timeout gets the stable timeout reason, like any other
1892-
/// cancelled read; anything else is the retryable [`SEARCH_FAILED_CLOSED`].
1890+
/// CLOSED reason for a failed NIP-50 search: a search that ran out of time
1891+
/// (the Postgres statement timeout or an OpenSearch timeout) gets the stable
1892+
/// timeout reason, like any other cancelled read; anything else is the
1893+
/// retryable [`SEARCH_FAILED_CLOSED`].
18931894
fn search_closed_reason(e: &buzz_search::SearchError) -> &'static str {
1894-
if e.is_statement_cancelled() {
1895+
if e.is_timeout() {
18951896
QUERY_TIMED_OUT_CLOSED
18961897
} else {
18971898
SEARCH_FAILED_CLOSED

0 commit comments

Comments
 (0)