Skip to content

Commit 41529f2

Browse files
buzz-db: move the search pool and Postgres search SQL behind buzz-db
buzz-search built its own pool and ran its own SQL: the FTS and profile-name queries, the abandoned-search cancel, and the outbox gauge read. The indexer reached the writer pool through Db::pool(). - The FTS query module and its cancel logic move to buzz_db::search, unchanged except for the error type. A SearchStore owns the search pool. SearchStore::connect builds it the way the relay used to. - SearchService takes a SearchStore instead of a PgPool. buzz-search re-exports the query types, so callers keep their imports. - The indexer and the outbox gauges use Db::search_outbox_store(). The gauge read takes a Db, so the relay sampler no longer needs the writer pool. - SearchError::Db holds a DbError instead of sqlx::Error. buzz-search no longer uses sqlx in production, so it moves to its dev-dependencies. The search pool construction test moves from the relay to buzz-db. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: Luke Tornquist <tornquist@squareup.com>
1 parent a626713 commit 41529f2

41 files changed

Lines changed: 461 additions & 275 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎ARCHITECTURE.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,7 @@ buzz-admin (operator CLI: relay membership + key generation)
145145
buzz-test-client (integration test harness + manual CLI)
146146
```
147147

148-
**Key architectural principle:** The relay is the single source of truth. `buzz-relay` orchestrates all subsystems by calling them directly — it imports `buzz-db`, `buzz-auth`, `buzz-pubsub`, `buzz-search`, `buzz-audit`, and `buzz-workflow`. However, those subsystems are isolated from each other: `buzz-workflow` never calls `buzz-pubsub`, `buzz-search` never calls `buzz-db`, etc. The one sanctioned exception is `buzz-audit`, which stores its chain through `buzz_db::AuditLog`. `buzz-audit` computes and checks the hashes; `AuditLog` owns the audit pool and the chain's appends and reads. Cross-subsystem coordination happens only through the relay. In multi-community mode, the relay also owns propagation of `TenantContext`; service crates should receive community-scoped inputs rather than independently deriving tenancy from client-controlled event tags.
148+
**Key architectural principle:** The relay is the single source of truth. `buzz-relay` orchestrates all subsystems by calling them directly — it imports `buzz-db`, `buzz-auth`, `buzz-pubsub`, `buzz-search`, `buzz-audit`, and `buzz-workflow`. However, those subsystems are isolated from each other: `buzz-workflow` never calls `buzz-pubsub`, etc. The one sanctioned exception is `buzz-audit`, which stores its chain through `buzz_db::AuditLog`. `buzz-audit` computes and checks the hashes; `AuditLog` owns the audit pool and the chain's appends and reads. Every crate reaches Postgres only through `buzz-db`. Cross-subsystem coordination happens only through the relay. In multi-community mode, the relay also owns propagation of `TenantContext`; service crates should receive community-scoped inputs rather than independently deriving tenancy from client-controlled event tags.
149149

150150
---
151151

@@ -585,7 +585,8 @@ kind 30180 (custom emoji entries) until an operator runs the updated maintenance
585585
script, which must happen before the emoji migration rollout.
586586

587587
**Key behaviors:**
588-
- `SearchService::new(pool)` wraps a `PgPool`; `search(&SearchQuery)` runs a
588+
- `SearchService::new(store)` wraps a `buzz_db::SearchStore`, which owns the
589+
search pool and the FTS SQL (`buzz_db::search`); `search(&SearchQuery)` runs a
589590
parameterized FTS query against the `events.search_tsv` GIN index and returns
590591
`SearchResult` (candidate `SearchHit`s). Prefix-mode relevance (outside
591592
profile search) ranks only the newest 1000 matches, which Postgres may read

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,7 @@ pub use store::{
104104
event, feed, git_repo, group_discovery, leader_lock, media, membership_snapshot, moderation,
105105
nip_fi_binding, operator_listener, partition, personal_read, pins, product_feedback, push,
106106
reaction, read_state, relay_admin_actions, relay_invite, relay_members, relay_operators,
107-
reminder, replaceable, search_backfill, search_outbox, storage_accounting, thread,
107+
reminder, replaceable, search, search_backfill, search_outbox, storage_accounting, thread,
108108
thread_window, user, user_deletion, user_deletion_fences, workflow,
109109
};
110110

@@ -124,6 +124,7 @@ pub use leader_lock::SessionLeader;
124124
pub use nip_fi_binding::{NipFiBindingRecord, NipFiUnbind, RowCapExceeded};
125125
pub use reaction::ReactionEventInsertOutcome;
126126
pub use reminder::DueReminder;
127+
pub use search::SearchStore;
127128
pub use store::{ArtifactSnapshot, SnapshotDenied};
128129

129130
/// A value read from the database, with when its reading connection was

‎crates/buzz-db/src/store/mod.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,8 @@ pub mod relay_operators;
8888
pub mod reminder;
8989
/// Replaceable-event persistence and coordinate locking.
9090
pub mod replaceable;
91+
/// Postgres full-text message and profile search.
92+
pub mod search;
9193
/// Queuing events stored before the search index existed.
9294
pub mod search_backfill;
9395
/// The durable queue between event admission and the search index.
Lines changed: 99 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,81 @@
88
//!
99
//! See conformance row 50.
1010
11+
use sqlx::postgres::PgPoolOptions;
1112
use sqlx::{PgPool, QueryBuilder, Row};
1213
use uuid::Uuid;
1314

1415
use buzz_core::CommunityId;
1516
use buzz_datastore_tracing::datastore_span;
1617

17-
use crate::error::SearchError;
18+
use crate::{DbConfig, DbPoolStats, Result};
19+
20+
pub mod cancel;
21+
22+
/// Options for the search pool: every new connection's session
23+
/// `statement_timeout` is lowered to the event-read deadline
24+
/// ([`crate::event::READ_STATEMENT_TIMEOUT`]) unless it is already tighter.
25+
/// Searches cancel their statement when abandoned (see [`cancel`]); this
26+
/// bounds the ones a cancel cannot reach.
27+
pub fn pool_options() -> PgPoolOptions {
28+
PgPoolOptions::new().after_connect(|conn, _meta| {
29+
Box::pin(crate::event::tighten_session_read_statement_timeout(conn))
30+
})
31+
}
32+
33+
/// Handle to Postgres full-text message and profile search, over its own
34+
/// pool. Clone is cheap.
35+
///
36+
/// The search pool is separate from the serving pools, so slow searches
37+
/// cannot take connections that event reads and writes need.
38+
#[derive(Debug, Clone)]
39+
pub struct SearchStore {
40+
pool: PgPool,
41+
}
42+
43+
impl SearchStore {
44+
/// Build the search pool from [`pool_options`]: on the reader when
45+
/// `config` has one, else the writer, with the writer's acquire timeout,
46+
/// so a dead reader fails a search within the same bound. The pool
47+
/// connects lazily: this never dials.
48+
pub fn connect(config: &DbConfig) -> Result<Self> {
49+
let url = config
50+
.read_database_url
51+
.as_deref()
52+
.unwrap_or(&config.database_url);
53+
let pool = pool_options()
54+
.acquire_timeout(std::time::Duration::from_secs(config.acquire_timeout_secs))
55+
.connect_lazy(url)?;
56+
Ok(Self { pool })
57+
}
58+
59+
/// Create a handle over an existing pool. For tests.
60+
pub fn from_pool(pool: PgPool) -> Self {
61+
Self { pool }
62+
}
63+
64+
/// Pool utilisation, for the relay's pool metrics.
65+
pub fn pool_stats(&self) -> DbPoolStats {
66+
DbPoolStats::from_pool(&self.pool)
67+
}
68+
69+
/// See [`search`].
70+
pub async fn search(&self, query: &SearchQuery) -> Result<SearchResult> {
71+
search(&self.pool, query).await
72+
}
73+
74+
/// See [`search_profile_names`].
75+
pub async fn search_profile_names(
76+
&self,
77+
community: CommunityId,
78+
q: &str,
79+
verified_by: Option<[u8; 32]>,
80+
page: u32,
81+
per_page: u32,
82+
) -> Result<SearchResult> {
83+
search_profile_names(&self.pool, community, q, verified_by, page, per_page).await
84+
}
85+
}
1886

1987
/// Channel-scope filter for a community-scoped FTS query.
2088
///
@@ -188,7 +256,7 @@ pub struct ScoreParts {
188256
/// A hit with the parts of its score.
189257
#[derive(Debug, Clone)]
190258
pub struct ScoredHit {
191-
/// The hit, as [`SearchService::search`](crate::SearchService::search)
259+
/// The hit, as `buzz_search::SearchService::search`
192260
/// returns it.
193261
pub hit: SearchHit,
194262
/// How its rank was made.
@@ -316,17 +384,18 @@ fn push_tsquery(
316384
}
317385
/// The page a [`SearchQuery`] asks for, clamped the same way by every
318386
/// backend.
319-
pub(crate) struct PageBounds {
387+
pub struct PageBounds {
320388
/// 1-indexed page, at most [`PAGE_MAX`].
321-
pub(crate) page: u32,
389+
pub page: u32,
322390
/// Hits per page: `per_page` clamped to `1..=PER_PAGE_MAX`, or the
323391
/// default when it is 0.
324-
pub(crate) per_page: u32,
392+
pub per_page: u32,
325393
/// Hits before this page.
326-
pub(crate) offset: i64,
394+
pub offset: i64,
327395
}
328396

329-
pub(crate) fn page_bounds(query: &SearchQuery) -> PageBounds {
397+
/// The page `query` asks for, clamped; see [`PageBounds`].
398+
pub fn page_bounds(query: &SearchQuery) -> PageBounds {
330399
let per_page = if query.per_page == 0 {
331400
PER_PAGE_DEFAULT
332401
} else {
@@ -340,7 +409,9 @@ pub(crate) fn page_bounds(query: &SearchQuery) -> PageBounds {
340409
}
341410
}
342411

343-
pub(crate) fn normalized_search_text(q: &str) -> Option<String> {
412+
/// The search text every backend matches: trimmed, NUL bytes replaced, and
413+
/// capped in length; `None` when nothing is left to search.
414+
pub fn normalized_search_text(q: &str) -> Option<String> {
344415
let trimmed = q.trim();
345416
if trimmed.is_empty() {
346417
return None;
@@ -381,7 +452,7 @@ pub(crate) fn normalized_search_text(q: &str) -> Option<String> {
381452
/// `community_id = $ctx` is the first predicate and is non-negotiable. There
382453
/// is no code path through this function that omits it.
383454
#[datastore_span(name = "search", system = "postgresql", pool = "search")]
384-
pub async fn search(pool: &PgPool, query: &SearchQuery) -> Result<SearchResult, SearchError> {
455+
pub async fn search(pool: &PgPool, query: &SearchQuery) -> Result<SearchResult> {
385456
let profile_only = query.kinds.as_deref() == Some(&[0][..]);
386457
let Some(search_text) = normalized_search_text(&query.q) else {
387458
return Ok(SearchResult {
@@ -538,7 +609,7 @@ pub async fn search(pool: &PgPool, query: &SearchQuery) -> Result<SearchResult,
538609

539610
// Not a cached prepared statement: after five runs Postgres may switch a
540611
// cached statement to a generic plan, which cannot see the tsquery.
541-
let rows = crate::cancel::fetch_all(pool, conn, qb.build().persistent(false)).await?;
612+
let rows = cancel::fetch_all(pool, conn, qb.build().persistent(false)).await?;
542613

543614
let mut hits = Vec::with_capacity(rows.len());
544615
for row in rows {
@@ -605,7 +676,7 @@ pub async fn search_profile_names(
605676
verified_by: Option<[u8; 32]>,
606677
page: u32,
607678
per_page: u32,
608-
) -> Result<SearchResult, SearchError> {
679+
) -> Result<SearchResult> {
609680
let page = page.clamp(1, PAGE_MAX);
610681
let Some(search_text) = normalized_search_text(q) else {
611682
return Ok(SearchResult {
@@ -712,7 +783,7 @@ pub async fn search_profile_names(
712783
people.person, ev.kind",
713784
);
714785

715-
let rows = crate::cancel::fetch_all(pool, pool.acquire().await?, qb.build()).await?;
786+
let rows = cancel::fetch_all(pool, pool.acquire().await?, qb.build()).await?;
716787
let mut hits = Vec::with_capacity(rows.len());
717788
for row in rows {
718789
let id_bytes: Vec<u8> = row.try_get("id")?;
@@ -830,6 +901,22 @@ fn push_name_columns(qb: &mut QueryBuilder<sqlx::Postgres>, fields: &[&str]) {
830901
mod tests {
831902
use super::*;
832903

904+
#[tokio::test]
905+
async fn search_pool_is_lazy_prefers_the_reader_and_bounds_acquire() {
906+
// Unroutable per RFC 5737 TEST-NET-1: construction must not dial it.
907+
let config = DbConfig {
908+
read_database_url: Some("postgres://u:p@192.0.2.1:5432/none".to_owned()), // sadscan:disable np.postgres.1
909+
..DbConfig::default()
910+
};
911+
let store = SearchStore::connect(&config).expect("lazy construction must not dial");
912+
assert_eq!(store.pool.connect_options().get_host(), "192.0.2.1");
913+
assert_eq!(
914+
store.pool.options().get_acquire_timeout(),
915+
std::time::Duration::from_secs(config.acquire_timeout_secs),
916+
"a dead reader must fail a search within the writer's acquire bound"
917+
);
918+
}
919+
833920
#[test]
834921
fn normalized_search_text_trims_and_rejects_empty() {
835922
assert_eq!(
Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
//! connection instead. The abandoned connection stays checked out until the
1818
//! task is done, so its backend cannot start another caller's statement
1919
//! before the signal lands. A cancel that cannot reach the backend leaves the
20-
//! statement to the pool's statement timeout ([`crate::pool_options`]).
20+
//! statement to the pool's statement timeout ([`super::pool_options`]).
2121
2222
use std::time::Duration;
2323

@@ -121,7 +121,7 @@ async fn cancel(pool: &PgPool, (pid, started_us): (i32, i64)) -> &'static str {
121121
let mut conn = match tokio::time::timeout(CANCEL_ACQUIRE_TIMEOUT, pool.acquire()).await {
122122
Ok(Ok(conn)) => conn,
123123
Ok(Err(e)) => {
124-
tracing::warn!(error_kind = %buzz_db::error::sqlx_error_kind(&e), pid, "search cancel could not get a connection");
124+
tracing::warn!(error_kind = %crate::error::sqlx_error_kind(&e), pid, "search cancel could not get a connection");
125125
return "error";
126126
}
127127
Err(_) => return "pool_busy",
@@ -135,7 +135,7 @@ async fn cancel(pool: &PgPool, (pid, started_us): (i32, i64)) -> &'static str {
135135
Ok(None) => elsewhere.push(conn),
136136
Ok(Some(signalled)) => return signal_outcome(signalled),
137137
Err(e) => {
138-
tracing::warn!(error_kind = %buzz_db::error::sqlx_error_kind(&e), pid, "search cancel failed");
138+
tracing::warn!(error_kind = %crate::error::sqlx_error_kind(&e), pid, "search cancel failed");
139139
return "error";
140140
}
141141
}

‎crates/buzz-db/src/store/search_outbox.rs‎

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -753,6 +753,101 @@ pub async fn parked_counts(pool: &PgPool) -> Result<Vec<(CommunityId, u64)>> {
753753
.collect())
754754
}
755755

756+
/// One reading of the active (unparked) queue, from
757+
/// [`SearchOutboxStore::stats`].
758+
#[derive(Debug, Clone, Copy, PartialEq)]
759+
pub struct OutboxStats {
760+
/// Queued rows, at most the cap passed to [`SearchOutboxStore::stats`].
761+
pub depth: i64,
762+
/// Age of the oldest queued row; zero when the queue is empty.
763+
pub lag: std::time::Duration,
764+
}
765+
766+
/// The search indexer's handle to the queue and its backfill, over the
767+
/// writer pool. Clone is cheap.
768+
#[derive(Debug, Clone)]
769+
pub struct SearchOutboxStore {
770+
pool: PgPool,
771+
}
772+
773+
impl crate::Db {
774+
/// The search outbox and backfill, for the search indexer.
775+
pub fn search_outbox_store(&self) -> SearchOutboxStore {
776+
SearchOutboxStore {
777+
pool: self.pool.clone(),
778+
}
779+
}
780+
}
781+
782+
impl SearchOutboxStore {
783+
/// See [`claim_batch_share`].
784+
pub async fn claim_batch_share(
785+
&self,
786+
limit: i64,
787+
skip: &[CommunityId],
788+
workers: usize,
789+
) -> Result<Option<SearchOutboxBatch>> {
790+
claim_batch_share(&self.pool, limit, skip, workers).await
791+
}
792+
793+
/// See [`claim_parked_batch`].
794+
pub async fn claim_parked_batch(
795+
&self,
796+
limit: i64,
797+
cooldown: std::time::Duration,
798+
skip: &[CommunityId],
799+
) -> Result<Option<SearchOutboxBatch>> {
800+
claim_parked_batch(&self.pool, limit, cooldown, skip).await
801+
}
802+
803+
/// See [`parked_counts`].
804+
pub async fn parked_counts(&self) -> Result<Vec<(CommunityId, u64)>> {
805+
parked_counts(&self.pool).await
806+
}
807+
808+
/// The active queue's depth, counted up to `depth_cap` rows so a long
809+
/// outage cannot make the count itself slow, and the age of its oldest
810+
/// row, read through the queue's `created_at` index.
811+
pub async fn stats(&self, depth_cap: i64) -> Result<OutboxStats> {
812+
let (depth, lag_seconds): (i64, Option<f64>) = sqlx::query_as(
813+
"SELECT \
814+
(SELECT count(*) FROM (SELECT 1 FROM search_outbox WHERE parked_at IS NULL LIMIT $1) AS capped), \
815+
(SELECT EXTRACT(EPOCH FROM now() - min(created_at))::float8 FROM search_outbox WHERE parked_at IS NULL)",
816+
)
817+
.bind(depth_cap)
818+
.fetch_one(&self.pool)
819+
.await?;
820+
Ok(OutboxStats {
821+
depth,
822+
lag: std::time::Duration::from_secs_f64(lag_seconds.unwrap_or(0.0).max(0.0)),
823+
})
824+
}
825+
826+
/// See [`crate::search_backfill::outbox_below`].
827+
pub async fn backfill_outbox_below(&self, bound: i64) -> Result<bool> {
828+
crate::search_backfill::outbox_below(&self.pool, bound).await
829+
}
830+
831+
/// See [`crate::search_backfill::step`].
832+
pub async fn backfill_step(
833+
&self,
834+
limit: i64,
835+
skip: &[CommunityId],
836+
) -> Result<Option<crate::search_backfill::BackfillStep>> {
837+
crate::search_backfill::step(&self.pool, limit, skip).await
838+
}
839+
840+
/// See [`crate::search_backfill::remaining`].
841+
pub async fn backfill_remaining(&self) -> Result<u64> {
842+
crate::search_backfill::remaining(&self.pool).await
843+
}
844+
845+
/// See [`crate::search_backfill::reset`].
846+
pub async fn backfill_reset(&self) -> Result<u64> {
847+
crate::search_backfill::reset(&self.pool).await
848+
}
849+
}
850+
756851
fn bytes32(bytes: Vec<u8>) -> Result<[u8; 32]> {
757852
<[u8; 32]>::try_from(bytes.as_slice())
758853
.map_err(|_| crate::DbError::InvalidData(format!("expected 32 bytes, got {}", bytes.len())))

0 commit comments

Comments
 (0)