diff --git a/.env.example b/.env.example index be1c6308ce..b180396006 100644 --- a/.env.example +++ b/.env.example @@ -188,6 +188,7 @@ BUZZ_PUSH_GATEWAY_DELIVERY_URL=https://push.buzz.xyz/v1/deliveries/apns # BUZZ_OPENSEARCH_USERNAME= # BUZZ_OPENSEARCH_PASSWORD= # BUZZ_OPENSEARCH_PREVIEW=true +# BUZZ_SEARCH_INDEXER_WORKERS=1 # Optional relay-owned KLIPY key. When set, NIP-11 advertises GIF search and # authenticated desktop clients use this relay as the metadata/search proxy. diff --git a/Cargo.lock b/Cargo.lock index cf294d2878..74f1b02270 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1553,15 +1553,18 @@ dependencies = [ name = "buzz-search" version = "0.1.0" dependencies = [ + "axum", "buzz-core", "buzz-datastore-tracing", "buzz-db", "chrono", "hex", "metrics", + "metrics-exporter-prometheus", "nostr 0.44.7", "opensearch", "rand 0.10.1", + "reqwest 0.13.4", "serde_json", "sqlx", "thiserror 2.0.18", diff --git a/crates/buzz-db/src/lib.rs b/crates/buzz-db/src/lib.rs index 61f3efa6c4..2a213ea7c2 100644 --- a/crates/buzz-db/src/lib.rs +++ b/crates/buzz-db/src/lib.rs @@ -99,8 +99,8 @@ pub use store::{ git_repo, leader_lock, media, membership_snapshot, moderation, nip_fi_binding, operator_listener, partition, personal_read, pins, product_feedback, push, reaction, read_state, relay_admin_actions, relay_invite, relay_members, relay_operators, reminder, - replaceable, search_outbox, storage_accounting, thread, thread_window, user, user_deletion, - user_deletion_fences, workflow, + replaceable, search_backfill, search_outbox, storage_accounting, thread, thread_window, user, + user_deletion, user_deletion_fences, workflow, }; pub use allowlist::AllowlistEntry; diff --git a/crates/buzz-db/src/runtime/migration.rs b/crates/buzz-db/src/runtime/migration.rs index 10efbae978..a7714211f8 100644 --- a/crates/buzz-db/src/runtime/migration.rs +++ b/crates/buzz-db/src/runtime/migration.rs @@ -50,7 +50,7 @@ pub(crate) async fn run_migrations_through(pool: &PgPool, target: i64) -> Result /// Migrations that only add a tenant table, applied after the fence /// retirement (0090). Append each new one here. #[cfg(test)] -const TENANT_TABLE_MIGRATIONS_AFTER_FENCE_RETIREMENT: [i64; 1] = [106]; +const TENANT_TABLE_MIGRATIONS_AFTER_FENCE_RETIREMENT: [i64; 2] = [106, 107]; /// Create the tenant tables added since the fence retirement, without /// recording their migrations. For tests that stop before the retirement but @@ -1029,11 +1029,17 @@ mod postgres_tests { } /// Where `file`, a path under `schema/`, breaks docs/database.md Rules 1, - /// 2 and 4: only `tables/public/`, `types/`, `partitions/` and `seeds/` - /// hold schema files, and no file declares a trigger, function, + /// 2 and 4: only `tables/public/`, `types/`, `sequences/`, `partitions/` + /// and `seeds/` hold schema files, and no file declares a trigger, function, /// procedure, rule or foreign key. fn desired_state_file_violations(file: &str, text: &str) -> Vec { - let allowed = ["tables/public/", "types/", "partitions/", "seeds/"]; + let allowed = [ + "tables/public/", + "types/", + "sequences/", + "partitions/", + "seeds/", + ]; let misplaced = (file != "schema.sql" && !allowed.iter().any(|dir| file.starts_with(dir))) .then(|| { format!( @@ -1056,7 +1062,13 @@ mod postgres_tests { let mut migrations: Vec<_> = MIGRATOR.iter().collect(); migrations.sort_by_key(|migration| migration.version); - assert_eq!(migrations.len(), 106); + assert_eq!(migrations.len(), 108); + assert_eq!(migrations[107].version, 108); + assert!(strip_sql_comments(migrations[107].sql.as_str()) + .contains("CREATE SEQUENCE search_index_version")); + assert_eq!(migrations[106].version, 107); + assert!(strip_sql_comments(migrations[106].sql.as_str()) + .contains("CREATE TABLE search_backfill")); assert_eq!(migrations[105].version, 106); assert!( strip_sql_comments(migrations[105].sql.as_str()).contains("CREATE TABLE search_outbox") @@ -1734,6 +1746,7 @@ mod postgres_tests { "media_uploaders", "media_publications", "search_outbox", + "search_backfill", ]; for table in crate::deletion::EXPECTED_SCOPED_TABLES .iter() @@ -2469,6 +2482,11 @@ mod postgres_tests { "CREATE TYPE widget_kind AS ENUM ('a');", 0, ), + ( + "sequences/widget_number.sql", + "CREATE SEQUENCE widget_number AS BIGINT;", + 0, + ), ("schema.sql", "\\i tables/public/widgets.sql", 0), ]; for (file, text, expected) in cases { @@ -3527,6 +3545,7 @@ mod postgres_tests { "workflow_runs", "push_gateway_installations", "search_outbox", + "search_backfill", ] { assert_eq!( columns(&desired, table).await, @@ -4503,7 +4522,7 @@ mod postgres_tests { .expect_err("deletion refuses a catalog missing later tenant tables") .to_string(); assert!( - drift.contains("(missing=search_outbox, unknown=)"), + drift.contains("(missing=search_backfill,search_outbox, unknown=)"), "deletion must accept the pre-retirement fences: {drift}" ); run_migrations(&pool).await.expect("apply all migrations"); @@ -4590,7 +4609,7 @@ mod postgres_tests { .expect_err("deletion refuses a catalog missing later tenant tables") .to_string(); assert!( - drift.contains("(missing=search_outbox, unknown=)"), + drift.contains("(missing=search_backfill,search_outbox, unknown=)"), "deletion must accept the catalog before the drop: {drift}" ); run_migrations(&pool).await.expect("apply all migrations"); diff --git a/crates/buzz-db/src/store/deletion.rs b/crates/buzz-db/src/store/deletion.rs index 7f6421266d..d0d1a0fccc 100644 --- a/crates/buzz-db/src/store/deletion.rs +++ b/crates/buzz-db/src/store/deletion.rs @@ -120,6 +120,7 @@ pub const EXPECTED_SCOPED_TABLES: &[&str] = &[ "relay_invites", "relay_members", "scheduled_workflow_fires", + "search_backfill", "search_outbox", "thread_metadata", "users", @@ -162,7 +163,6 @@ pub const PENDING_SCOPED_TABLES: &[&str] = &[ "identity_retirement_actions", "identity_retirement_holds", "identity_retirement_workflows", - "search_backfill", "thread_heads", ]; @@ -209,6 +209,7 @@ pub const PURGE_SCOPED_TABLES: &[&str] = &[ "scheduled_workflow_fires", "workflow_runs", "push_wake_outbox", + "search_backfill", "search_outbox", "join_policy_acceptances", "media_uploaders", @@ -9720,8 +9721,10 @@ DROP FUNCTION protect_community_deletion_manifest_keys(); } /// Once a community is fenced for deletion, admission refuses its writes - /// (and so its outbox rows) and claims skip it; the purge removes its - /// outbox rows and keeps another community's. + /// (and so its outbox rows), claims and backfill skip it, and its rows do + /// not count against the backfill bound; the purge + /// removes its outbox rows and backfill progress and keeps another + /// community's. #[tokio::test] #[ignore = "requires Postgres"] async fn search_outbox_is_fenced_and_purged() { @@ -9760,11 +9763,56 @@ DROP FUNCTION protect_community_deletion_manifest_keys(); } }; + let backfill = |owner: CommunityId| { + let pool = db.pool.clone(); + async move { + sqlx::query_scalar::<_, i64>( + "SELECT count(*) FROM search_backfill WHERE community_id = $1", + ) + .bind(owner.as_uuid()) + .fetch_one(&pool) + .await + .expect("count backfill rows") + } + }; + let others: Vec = + sqlx::query_scalar::<_, Uuid>("SELECT id FROM communities WHERE id <> $1") + .bind(community.as_uuid()) + .fetch_all(&db.pool) + .await + .expect("other communities") + .into_iter() + .map(CommunityId::from_uuid) + .collect(); + let step = crate::search_backfill::step(&db.pool, 1, &others) + .await + .expect("backfill step") + .expect("the community's backfill"); + assert_eq!((step.community, step.queued), (community, 1)); + assert_eq!(queued(community).await, 2); + let token = fence_and_drain(&store, &request, &inventory).await; db.insert_event(community, &message("after fence"), None) .await .expect_err("a fenced community admits no writes"); - assert_eq!(queued(community).await, 1); + assert_eq!(queued(community).await, 2); + let mut skip = others.clone(); + skip.retain(|other| *other != bystander); + let step = crate::search_backfill::step(&db.pool, 10, &skip) + .await + .expect("backfill step") + .expect("the bystander's backfill"); + assert_eq!( + step.community, bystander, + "backfill skips a fenced community" + ); + assert_eq!( + crate::search_backfill::step(&db.pool, 10, &skip) + .await + .expect("backfill step"), + None + ); + assert_eq!(backfill(community).await, 1); let batch = crate::search_outbox::claim_batch(&db.pool, 10, &[]) .await .expect("claim") @@ -9775,11 +9823,19 @@ DROP FUNCTION protect_community_deletion_manifest_keys(); "claims skip a fenced community" ); drop(batch); + // The fenced community's rows cannot drain before the purge, so they + // do not count against the backfill bound of the others. + assert_eq!(queued(bystander).await, 2); + assert!(crate::search_backfill::outbox_below(&db.pool, 3) + .await + .expect("outbox depth")); let deleted = store.purge_postgres(&token).await.expect("purge postgres"); - assert_eq!(deleted.get("search_outbox"), Some(&1)); + assert_eq!(deleted.get("search_outbox"), Some(&2)); + assert_eq!(deleted.get("search_backfill"), Some(&1)); assert_eq!(queued(community).await, 0); - assert_eq!(queued(bystander).await, 1); + assert_eq!(backfill(community).await, 0); + assert_eq!(backfill(bystander).await, 1); } /// Approve, claim, fence, drain and remove bindings, leaving the request diff --git a/crates/buzz-db/src/store/event_deletion.rs b/crates/buzz-db/src/store/event_deletion.rs index af6fd783c8..e5c78c0191 100644 --- a/crates/buzz-db/src/store/event_deletion.rs +++ b/crates/buzz-db/src/store/event_deletion.rs @@ -500,6 +500,7 @@ pub(crate) async fn soft_delete_event_and_update_thread_in_tx( let deleted = purged > 0 || result.rows_affected() > 0; if deleted { + crate::search_outbox::enqueue_in_transaction(tx, event_id, created_at, kind).await?; sqlx::query("UPDATE artifact_heads SET modified_at=clock_timestamp() WHERE community_id=$1 AND artifact_id=(SELECT artifact_id FROM artifact_revisions WHERE community_id=$1 AND event_id=$2) AND event_id=$2") .bind(community_id.as_uuid()).bind(event_id).execute(tx.conn()).await?; if let Some(pid) = parent_event_id { diff --git a/crates/buzz-db/src/store/media.rs b/crates/buzz-db/src/store/media.rs index 9f5551ab2e..9c605b719c 100644 --- a/crates/buzz-db/src/store/media.rs +++ b/crates/buzz-db/src/store/media.rs @@ -23,7 +23,9 @@ fn edit_governed_kinds_sql() -> String { .join(",") } -fn edit_target(alias: &str) -> String { +/// The id the message edit aliased `alias` targets, in the exact spelling +/// `idx_events_media_edit_target` indexes. +pub(crate) fn edit_target(alias: &str) -> String { MEDIA_EDIT_TARGET_SQL.replacen("(tags,", &format!("({alias}.tags,"), 1) } diff --git a/crates/buzz-db/src/store/mod.rs b/crates/buzz-db/src/store/mod.rs index 4345416f4c..26726c0815 100644 --- a/crates/buzz-db/src/store/mod.rs +++ b/crates/buzz-db/src/store/mod.rs @@ -84,6 +84,8 @@ pub mod relay_operators; pub mod reminder; /// Replaceable-event persistence and coordinate locking. pub mod replaceable; +/// Queuing events stored before the search index existed. +pub mod search_backfill; /// The durable queue between event admission and the search index. pub mod search_outbox; #[cfg(test)] diff --git a/crates/buzz-db/src/store/search_backfill.rs b/crates/buzz-db/src/store/search_backfill.rs new file mode 100644 index 0000000000..a26a618730 --- /dev/null +++ b/crates/buzz-db/src/store/search_backfill.rs @@ -0,0 +1,211 @@ +//! Search backfill: queues the keys of events stored before the search index +//! existed, so they reach it through the same outbox as live writes. +//! +//! Each community's `search_backfill` row holds a cursor that moves in the +//! same transaction as the batch it queues, so a restart resumes from the +//! last committed batch. A community without a row starts from its newest +//! event: deleting the row is how an operator backfills again. Queuing an +//! indexed event again only rewrites its document. + +use buzz_core::CommunityId; +use chrono::{DateTime, Utc}; +use sqlx::{PgPool, Row}; +use uuid::Uuid; + +use crate::search_outbox::SEARCHABLE_KINDS; +use crate::Result; + +/// Communities a step may pass over because their deletion fenced them +/// between candidate selection and admission. +const STEP_COMMUNITY_CANDIDATES: usize = 8; + +/// What one [`step`] queued for a community, and where its backfill stands. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct BackfillStep { + /// The community the step backfilled. + pub community: CommunityId, + /// Event keys this step queued. + pub queued: u64, + /// Event keys queued since the community's backfill started. + pub total_queued: i64, + /// Creation time of the oldest event queued so far: everything newer has + /// been queued. + pub cursor: Option>, + /// Whether no older event is left to queue. + pub completed: bool, +} + +/// Whether the outbox holds fewer than `bound` rows the indexer can drain. +/// Rows of a community fenced for deletion are left out: claims skip them +/// until the purge removes them, so counting them could hold back every +/// other community's backfill for as long as the deletion takes. Reads at +/// most `bound` rows, so it stays cheap however large the queue grows. +pub async fn outbox_below(pool: &PgPool, bound: i64) -> Result { + let depth: i64 = sqlx::query_scalar( + "SELECT count(*) FROM ( \ + SELECT 1 FROM search_outbox o \ + JOIN communities c ON c.id = o.community_id \ + WHERE c.deletion_state = 'active' AND c.deleted_at IS NULL \ + LIMIT $1 \ + ) AS bounded", + ) + .bind(bound) + .fetch_one(pool) + .await?; + Ok(depth < bound) +} + +/// Every active community and whether its backfill has queued all of its +/// stored events. +pub async fn progress(pool: &PgPool) -> Result> { + let rows: Vec<(Uuid, bool)> = sqlx::query_as( + "SELECT c.id, b.completed_at IS NOT NULL FROM communities c \ + LEFT JOIN search_backfill b ON b.community_id = c.id \ + WHERE c.deletion_state = 'active' AND c.deleted_at IS NULL", + ) + .fetch_all(pool) + .await?; + Ok(rows + .into_iter() + .map(|(id, completed)| (CommunityId::from_uuid(id), completed)) + .collect()) +} + +/// Forget every community's backfill progress, so each is backfilled again +/// from its newest event, and return how many rows were removed. Before +/// creating a new, empty index: the progress described the index it +/// replaces. Deleting rows +/// needs no community admission: it only removes rows that a community +/// deletion's purge removes too. +pub async fn reset(pool: &PgPool) -> Result { + let reset = sqlx::query("DELETE FROM search_backfill") + .execute(pool) + .await?; + Ok(reset.rows_affected()) +} + +/// Queue up to `limit` more event keys for the active community not in +/// `skip` whose backfill is incomplete and least recently advanced, newest +/// events first, and advance its cursor. +/// +/// Returns `None` when every active community's backfill is complete. +/// Communities take turns, one batch each, so a large one does not hold +/// back the rest. +pub async fn step(pool: &PgPool, limit: i64, skip: &[CommunityId]) -> Result> { + let mut refused: Vec = skip.iter().map(|community| *community.as_uuid()).collect(); + for _ in 0..STEP_COMMUNITY_CANDIDATES { + let candidate: Option = sqlx::query_scalar( + "SELECT c.id FROM communities c \ + LEFT JOIN search_backfill b ON b.community_id = c.id \ + WHERE c.deletion_state = 'active' AND c.deleted_at IS NULL \ + AND b.completed_at IS NULL AND c.id <> ALL($1) \ + ORDER BY b.updated_at NULLS FIRST, c.id LIMIT 1", + ) + .bind(&refused) + .fetch_optional(pool) + .await?; + let Some(id) = candidate else { + return Ok(None); + }; + let community = CommunityId::from_uuid(id); + let Some(mut tx) = crate::begin_community_sweep_transaction( + pool, + community, + crate::observability::WriterOperation::Maintenance, + ) + .await? + else { + refused.push(id); + continue; + }; + let marker = sqlx::query( + "SELECT cursor_created_at, cursor_event_id, completed_at FROM search_backfill \ + WHERE community_id = $1 FOR UPDATE", + ) + .bind(id) + .fetch_optional(tx.conn()) + .await?; + let mut cursor: Option<(DateTime, Vec)> = None; + if let Some(marker) = marker { + if marker + .try_get::>, _>("completed_at")? + .is_some() + { + // Completed since the candidate read. + refused.push(id); + continue; + } + let at: Option> = marker.try_get("cursor_created_at")?; + let event: Option> = marker.try_get("cursor_event_id")?; + cursor = at.zip(event); + } + + // The events primary key (community_id, created_at, id), scanned + // backwards from the cursor; other kinds are skipped as it goes. + let below_cursor = if cursor.is_some() { + "AND (e.created_at, e.id) < ($4, $5)" + } else { + "" + }; + let sql = format!( + "WITH batch AS ( \ + SELECT e.id, e.created_at FROM events e \ + WHERE e.community_id = $1 AND e.kind = ANY($2) AND e.deleted_at IS NULL \ + {below_cursor} \ + ORDER BY e.created_at DESC, e.id DESC LIMIT $3 \ + ), queued AS ( \ + INSERT INTO search_outbox (community_id, event_id, event_created_at) \ + SELECT $1, id, created_at FROM batch \ + RETURNING event_id, event_created_at \ + ) \ + SELECT count(*) AS queued, \ + min(event_created_at) AS oldest_at, \ + (array_agg(event_id ORDER BY event_created_at, event_id))[1] AS oldest_id \ + FROM queued" + ); + let mut query = sqlx::query(sqlx::AssertSqlSafe(sql)) + .bind(id) + .bind(SEARCHABLE_KINDS.as_slice()) + .bind(limit); + if let Some((at, event)) = &cursor { + query = query.bind(at).bind(event); + } + let row = query.fetch_one(tx.conn()).await?; + let queued: i64 = row.try_get("queued")?; + let oldest_at: Option> = row.try_get("oldest_at")?; + let oldest_id: Option> = row.try_get("oldest_id")?; + let completed = queued < limit; + + let progress = sqlx::query( + "INSERT INTO search_backfill \ + (community_id, cursor_created_at, cursor_event_id, enqueued, completed_at) \ + VALUES ($1, $2, $3, $4, CASE WHEN $5 THEN now() END) \ + ON CONFLICT (community_id) DO UPDATE SET \ + cursor_created_at = COALESCE(EXCLUDED.cursor_created_at, \ + search_backfill.cursor_created_at), \ + cursor_event_id = COALESCE(EXCLUDED.cursor_event_id, \ + search_backfill.cursor_event_id), \ + enqueued = search_backfill.enqueued + EXCLUDED.enqueued, \ + completed_at = EXCLUDED.completed_at, \ + updated_at = now() \ + RETURNING enqueued, cursor_created_at", + ) + .bind(id) + .bind(oldest_at) + .bind(oldest_id) + .bind(queued) + .bind(completed) + .fetch_one(tx.conn()) + .await?; + let step = BackfillStep { + community, + queued: u64::try_from(queued).unwrap_or_default(), + total_queued: progress.try_get("enqueued")?, + cursor: progress.try_get("cursor_created_at")?, + completed, + }; + tx.commit().await?; + return Ok(Some(step)); + } + Ok(None) +} diff --git a/crates/buzz-db/src/store/search_outbox.rs b/crates/buzz-db/src/store/search_outbox.rs index ef2efb6d03..a0151510a6 100644 --- a/crates/buzz-db/src/store/search_outbox.rs +++ b/crates/buzz-db/src/store/search_outbox.rs @@ -1,15 +1,23 @@ -//! The search outbox: the durable queue between event admission and the -//! search index. +//! The search outbox: the durable queue between Postgres and the search +//! index. //! //! When [`enable`] has been called (the relay does so when it is configured -//! with an OpenSearch address), every admitted insert of a -//! [`SEARCHABLE_KINDS`] event writes a `search_outbox` row in the same -//! transaction, so a stored message always has its index change queued and a -//! rolled-back write never does. The write makes no call to the search -//! engine. +//! with an OpenSearch address; account deletion calls [`enable_if_indexed`] +//! instead), every write that changes what search should return queues a +//! `search_outbox` row in the same transaction, so a change always has its +//! index update queued and a rolled-back write never does. The write makes +//! no call to the search engine. //! //! The indexer re-reads `events` for every row it claims, so duplicate or //! out-of-order rows for one event are harmless. +//! +//! Each event belongs to one of [`CLAIM_PARTITIONS`] partitions of its +//! community, and a batch locks every partition it claims from until it +//! commits. So two batches never hold states of one message at once, and +//! an older state is never written after a newer one. +//! +//! Purging a community's documents is not queued here: the purge deletes +//! the community's rows, this queue included. use std::sync::atomic::{AtomicBool, Ordering}; @@ -20,7 +28,7 @@ use uuid::Uuid; use crate::{AdmittedTx, Result}; -/// Event kinds the search index holds; no other kind is ever queued. They +/// Event kinds the search index holds; no other kind is ever indexed. They /// are the message kinds an edit can replace, so the list has one owner. pub const SEARCHABLE_KINDS: [i32; EDIT_GOVERNED_KINDS.len()] = { let mut kinds = [0; EDIT_GOVERNED_KINDS.len()]; @@ -32,52 +40,170 @@ pub const SEARCHABLE_KINDS: [i32; EDIT_GOVERNED_KINDS.len()] = { kinds }; +/// A message edit: its content replaces the text of the message its first +/// valid `e` tag names, in the same channel. +const KIND_MESSAGE_EDIT: i32 = buzz_core::kind::KIND_STREAM_MESSAGE_EDIT as i32; + /// Communities a claim may pass over because their deletion fenced them -/// between candidate selection and admission, or another worker holds all -/// their rows. +/// between candidate selection and admission, or another worker is +/// indexing a batch of theirs. const CLAIM_COMMUNITY_CANDIDATES: usize = 8; +/// Partitions of a community's queue. An event's partition is the first +/// byte of its id modulo this, so it never changes. Batches of one +/// community run at once only on disjoint partitions, so this caps the +/// workers one community can use. A power of two dividing 256 keeps the +/// partitions equal. +pub const CLAIM_PARTITIONS: i32 = 64; + +/// First key of the transaction advisory lock a batch holds on each +/// partition it claims from; the second is a hash of the community id and +/// partition. Two-key advisory locks never collide with single-key ones such +/// as the indexer lease, and a hash collision only makes a claim pass over a +/// free partition. +const CLAIM_LOCK_CLASS: i32 = 0x5345_4152; + static ENABLED: AtomicBool = AtomicBool::new(false); /// Start writing outbox rows on admission, for the life of the process. /// /// Process-wide because the outbox follows every event insert path. Call it /// once at startup, before serving writes, when a search index is configured. -/// Fails, leaving the outbox off, if migrations have not created the table: -/// enabled without it, every searchable insert would fail. +/// Fails, leaving the outbox off, if migrations have not created the table +/// and the version sequence: enabled without the table, every searchable +/// insert would fail, and without the sequence, every batch. pub async fn enable(pool: &PgPool) -> Result<()> { - let exists: bool = sqlx::query_scalar("SELECT to_regclass('public.search_outbox') IS NOT NULL") - .fetch_one(pool) - .await?; + let exists: bool = sqlx::query_scalar( + "SELECT to_regclass('public.search_outbox') IS NOT NULL \ + AND to_regclass('public.search_index_version') IS NOT NULL", + ) + .fetch_one(pool) + .await?; if !exists { return Err(crate::DbError::InvalidData( - "the search_outbox table is missing; run migrations before enabling search indexing" + "the search_outbox table or search_index_version sequence is missing; \ + run migrations before enabling search indexing" .into(), )); } + // Mark the index as maintained for `enable_if_indexed`: a sequence that + // has handed out a value stays that way when both queues are empty. + sqlx::query("SELECT nextval('search_index_version')") + .execute(pool) + .await?; ENABLED.store(true, Ordering::Relaxed); Ok(()) } -/// Queue `event_id` for indexing in the admitted transaction that inserted it. +/// Turn the outbox on, for the life of the process, if this database's +/// search index is maintained, and return whether it is on. For processes +/// other than the relay that change searchable events (account deletion), +/// which have no OpenSearch address of their own. +pub async fn enable_if_indexed(conn: &mut sqlx::PgConnection) -> Result { + if ENABLED.load(Ordering::Relaxed) { + return Ok(true); + } + let maintained = index_maintained(conn).await?; + if maintained { + ENABLED.store(true, Ordering::Relaxed); + } + Ok(maintained) +} + +/// Whether an indexing relay has ever run against this database: [`enable`] +/// took a value from the version sequence, or (for a relay older than that) +/// the outbox or the backfill holds rows. The sequence keeps its state while +/// both tables are empty, as they are before the first backfill and after an +/// operator resets it. A deployment that never had an indexer has none of +/// the three, so nothing is queued that no one would drain. +pub(crate) async fn index_maintained(conn: &mut sqlx::PgConnection) -> Result { + let tables: bool = sqlx::query_scalar( + "SELECT to_regclass('public.search_outbox') IS NOT NULL \ + AND to_regclass('public.search_backfill') IS NOT NULL \ + AND to_regclass('public.search_index_version') IS NOT NULL", + ) + .fetch_one(&mut *conn) + .await?; + if !tables { + return Ok(false); + } + Ok(sqlx::query_scalar( + "SELECT (SELECT is_called FROM search_index_version) \ + OR EXISTS (SELECT 1 FROM search_outbox) \ + OR EXISTS (SELECT 1 FROM search_backfill)", + ) + .fetch_one(conn) + .await?) +} + +/// Queue the index change for an event this admitted transaction inserted, +/// soft-deleted or otherwise changed: the event itself when it is +/// searchable, or the message it edits when it is a message edit. +/// +/// Call while the event's row still exists, before any physical delete in the +/// same transaction. pub(crate) async fn enqueue_in_transaction( tx: &mut AdmittedTx, event_id: &[u8], created_at: DateTime, kind: i32, ) -> Result<()> { - if !ENABLED.load(Ordering::Relaxed) || !SEARCHABLE_KINDS.contains(&kind) { + if !ENABLED.load(Ordering::Relaxed) { + return Ok(()); + } + if SEARCHABLE_KINDS.contains(&kind) { + let community = tx.community(); + sqlx::query( + "INSERT INTO search_outbox (community_id, event_id, event_created_at) \ + VALUES ($1, $2, $3)", + ) + .bind(community.as_uuid()) + .bind(event_id) + .bind(created_at) + .execute(tx.conn()) + .await?; + } else if kind == KIND_MESSAGE_EDIT { + enqueue_events_in_transaction(tx, &[event_id.to_vec()], &[created_at]).await?; + } + Ok(()) +} + +/// [`enqueue_in_transaction`] for events named by key whose kinds the caller +/// does not hold. Events of other kinds are skipped. +pub(crate) async fn enqueue_events_in_transaction( + tx: &mut AdmittedTx, + event_ids: &[Vec], + created_at: &[DateTime], +) -> Result<()> { + if !ENABLED.load(Ordering::Relaxed) || event_ids.is_empty() { return Ok(()); } let community = tx.community(); - sqlx::query( - "INSERT INTO search_outbox (community_id, event_id, event_created_at) VALUES ($1, $2, $3)", - ) - .bind(community.as_uuid()) - .bind(event_id) - .bind(created_at) - .execute(tx.conn()) - .await?; + // An edit queues the message it targets in its own channel. + let sql = format!( + "INSERT INTO search_outbox (community_id, event_id, event_created_at) \ + SELECT $1, e.id, e.created_at \ + FROM unnest($2::bytea[], $3::timestamptz[]) AS k(id, created_at) \ + JOIN events e ON e.community_id = $1 AND e.created_at = k.created_at AND e.id = k.id \ + WHERE e.kind = ANY($4) \ + UNION ALL \ + SELECT $1, original.id, original.created_at \ + FROM unnest($2::bytea[], $3::timestamptz[]) AS k(id, created_at) \ + JOIN events edit \ + ON edit.community_id = $1 AND edit.created_at = k.created_at AND edit.id = k.id \ + JOIN events original \ + ON original.community_id = $1 AND original.channel_id = edit.channel_id \ + AND original.id = {target} \ + WHERE edit.kind = {KIND_MESSAGE_EDIT} AND original.kind = ANY($4)", + target = crate::store::media::edit_target("edit"), + ); + sqlx::query(sqlx::AssertSqlSafe(sql)) + .bind(community.as_uuid()) + .bind(event_ids) + .bind(created_at) + .bind(SEARCHABLE_KINDS.as_slice()) + .execute(tx.conn()) + .await?; Ok(()) } @@ -114,12 +240,20 @@ pub struct SearchDocument { #[must_use = "dropping a batch leaves its rows queued; call complete()"] pub struct SearchOutboxBatch { tx: AdmittedTx, - row_ids: Vec, + /// Claimed rows and the events they name. + rows: Vec<(Uuid, [u8; 32])>, /// Events to write to the index. pub documents: Vec, /// Queued events that are gone, deleted or not searchable: their /// documents must be removed from the index. pub removed: Vec<[u8; 32]>, + /// The next value of the `search_index_version` sequence, read while + /// the batch holds its partitions. A later batch of the same event can + /// only be claimed once this one ends, so it reads a later state and, + /// since the sequence does not repeat values while Postgres runs, a + /// larger version: the index keeps the newest write by this external + /// version, even when an older batch's request lands after it. + pub version: i64, } impl SearchOutboxBatch { @@ -130,11 +264,24 @@ impl SearchOutboxBatch { /// Delete the claimed rows and commit. Call once the index holds the /// batch. - pub async fn complete(mut self) -> Result<()> { + pub async fn complete(self) -> Result<()> { + self.complete_except(&[]).await + } + + /// Delete the claimed rows except those naming an event in `retry`, and + /// commit. Call once the index holds every other event of the batch; the + /// kept rows are claimed again by a later batch. + pub async fn complete_except(mut self, retry: &[[u8; 32]]) -> Result<()> { let community = self.tx.community(); + let done: Vec = self + .rows + .iter() + .filter(|(_, event)| !retry.contains(event)) + .map(|(id, _)| *id) + .collect(); sqlx::query("DELETE FROM search_outbox WHERE community_id = $1 AND id = ANY($2)") .bind(community.as_uuid()) - .bind(&self.row_ids) + .bind(&done) .execute(self.tx.conn()) .await?; self.tx.commit().await @@ -142,8 +289,10 @@ impl SearchOutboxBatch { } /// Claim up to `limit` of the oldest queued rows of one community not in -/// `skip`, skipping rows another worker holds, and read their events' current -/// state. +/// `skip` and not being indexed by another worker, and read their events' +/// current state. The batch may take every free partition of the +/// community's queue head, so this suits a single worker; see +/// [`claim_batch_share`]. /// /// Returns `None` when no other active community has unclaimed rows. pub async fn claim_batch( @@ -151,6 +300,24 @@ pub async fn claim_batch( limit: i64, skip: &[CommunityId], ) -> Result> { + claim_batch_share(pool, limit, skip, 1).await +} + +/// [`claim_batch`] for one of `workers` workers: the batch locks at most +/// `ceil(64 / workers)` of the community's partitions, picked at random +/// among the free ones holding its oldest rows, and claims only their rows, +/// so the other workers can index the same community at the same time. +/// Every row of one event is in one partition, and the partition stays +/// locked until the batch completes, so no two batches in flight hold rows +/// of the same event. +pub async fn claim_batch_share( + pool: &PgPool, + limit: i64, + skip: &[CommunityId], + workers: usize, +) -> Result> { + let workers = i32::try_from(workers.max(1)).unwrap_or(CLAIM_PARTITIONS); + let share = (CLAIM_PARTITIONS + workers - 1) / workers; let mut refused: Vec = skip.iter().map(|community| *community.as_uuid()).collect(); for _ in 0..CLAIM_COMMUNITY_CANDIDATES { // Exclude fenced communities so they cannot occupy the queue head. @@ -178,47 +345,95 @@ pub async fn claim_batch( refused.push(id); continue; }; + // Lock up to `share` free partitions among those of the community's + // oldest rows, so no other batch claims a row of their events until + // this one completes. The head is two batches per worker, since the + // oldest rows are mostly in flight; picking from it keeps claims + // oldest-first and off empty partitions. A worker that has run ahead + // of the others can find every partition of the head held, so it + // looks once more over a head sixteen times as long: otherwise its + // claim comes back empty while rows remain, and the drain retires it. + // The shuffle is fenced with `OFFSET 0`, so the lock call runs on + // shuffled partitions one at a time and stops at the limit; + // flattened, the planner would lock every candidate before sorting. + // The locks end with the batch's transaction. + let head = limit.saturating_mul(2 * i64::from(workers)); + let mut partitions: Vec = Vec::new(); + for window in [head, head.saturating_mul(16)] { + partitions = sqlx::query_scalar( + "SELECT p FROM ( \ + SELECT p FROM ( \ + SELECT DISTINCT get_byte(event_id, 0) % $3 AS p FROM ( \ + SELECT event_id FROM search_outbox WHERE community_id = $2 \ + ORDER BY created_at LIMIT $5 \ + ) head \ + ) candidates ORDER BY random() OFFSET 0 \ + ) shuffled \ + WHERE pg_try_advisory_xact_lock($1, hashtext($2::text || '/' || p)) \ + LIMIT $4", + ) + .bind(CLAIM_LOCK_CLASS) + .bind(id) + .bind(CLAIM_PARTITIONS) + .bind(share) + .bind(window) + .fetch_all(tx.conn()) + .await?; + if !partitions.is_empty() { + break; + } + } + if partitions.is_empty() { + refused.push(id); + continue; + } let rows = sqlx::query( "SELECT id, event_id, event_created_at FROM search_outbox \ - WHERE community_id = $1 \ + WHERE community_id = $1 AND get_byte(event_id, 0) % $3 = ANY($4) \ ORDER BY created_at \ FOR UPDATE SKIP LOCKED \ LIMIT $2", ) .bind(community.as_uuid()) .bind(limit) + .bind(CLAIM_PARTITIONS) + .bind(&partitions) .fetch_all(tx.conn()) .await?; if rows.is_empty() { - // Another worker holds every row of this community. + // Other workers hold every partition with rows, or the rows + // were completed since the candidate read. refused.push(id); continue; } - let mut row_ids = Vec::with_capacity(rows.len()); + let mut claimed = Vec::with_capacity(rows.len()); let mut queued = std::collections::BTreeMap::<[u8; 32], DateTime>::new(); for row in &rows { - row_ids.push(row.try_get("id")?); - queued.insert( - bytes32(row.try_get("event_id")?)?, - row.try_get("event_created_at")?, - ); + let event = bytes32(row.try_get("event_id")?)?; + claimed.push((row.try_get("id")?, event)); + queued.insert(event, row.try_get("event_created_at")?); } let documents = read_documents(&mut tx, &queued).await?; + let version: i64 = sqlx::query_scalar("SELECT nextval('search_index_version')") + .fetch_one(tx.conn()) + .await?; for document in &documents { queued.remove(&document.event_id); } let removed = queued.into_keys().collect(); return Ok(Some(SearchOutboxBatch { tx, - row_ids, + rows: claimed, documents, removed, + version, })); } Ok(None) } -/// Read the current state of each live, searchable queued event. +/// Read the current state of each live, searchable queued event, with the +/// text of its latest live edit in place of its own. async fn read_documents( tx: &mut AdmittedTx, queued: &std::collections::BTreeMap<[u8; 32], DateTime>, @@ -227,9 +442,12 @@ async fn read_documents( let ids: Vec<&[u8]> = queued.keys().map(|id| id.as_slice()).collect(); let created: Vec> = queued.values().copied().collect(); // The (created_at, id) pair is the events key, so each lookup prunes to - // one partition. - let rows = sqlx::query( - "SELECT e.id, e.kind, e.pubkey, e.channel_id, e.created_at, e.content, \ + // one partition. The latest edit is the one clients show (see + // `media::latest_message_edit_sql`), read through the partial + // `idx_events_media_edit_target`, whose predicate needs the literal kind. + let sql = format!( + "SELECT e.id, e.kind, e.pubkey, e.channel_id, e.created_at, \ + COALESCE(edit.content, e.content) AS content, \ c.channel_type::text AS channel_type, \ (u.agent_owner_pubkey IS NOT NULL) AS author_is_agent, \ t.root_event_id, \ @@ -239,19 +457,28 @@ async fn read_documents( FROM unnest($2::bytea[], $3::timestamptz[]) AS k(id, created_at) \ JOIN events e \ ON e.community_id = $1 AND e.created_at = k.created_at AND e.id = k.id \ + LEFT JOIN LATERAL ( \ + SELECT ed.content FROM events ed \ + WHERE ed.community_id = e.community_id AND ed.channel_id = e.channel_id \ + AND ed.kind = {KIND_MESSAGE_EDIT} AND ed.deleted_at IS NULL \ + AND {target} = e.id \ + ORDER BY ed.created_at DESC, ed.id DESC LIMIT 1 \ + ) edit ON true \ LEFT JOIN channels c ON c.community_id = e.community_id AND c.id = e.channel_id \ LEFT JOIN users u ON u.community_id = e.community_id AND u.pubkey = e.pubkey \ LEFT JOIN thread_metadata t \ ON t.community_id = e.community_id \ AND t.event_created_at = e.created_at AND t.event_id = e.id \ WHERE e.deleted_at IS NULL AND e.kind = ANY($4)", - ) - .bind(community.as_uuid()) - .bind(&ids) - .bind(&created) - .bind(SEARCHABLE_KINDS.as_slice()) - .fetch_all(tx.conn()) - .await?; + target = crate::store::media::edit_target("ed"), + ); + let rows = sqlx::query(sqlx::AssertSqlSafe(sql)) + .bind(community.as_uuid()) + .bind(&ids) + .bind(&created) + .bind(SEARCHABLE_KINDS.as_slice()) + .fetch_all(tx.conn()) + .await?; let mut documents = Vec::with_capacity(rows.len()); for row in rows { documents.push(SearchDocument { @@ -284,3 +511,24 @@ fn bytes32(bytes: Vec) -> Result<[u8; 32]> { <[u8; 32]>::try_from(bytes.as_slice()) .map_err(|_| crate::DbError::InvalidData(format!("expected 32 bytes, got {}", bytes.len()))) } +#[cfg(test)] +mod tests { + use super::*; + + /// Replacing a replaceable or addressable event soft-deletes its previous + /// version without queuing a row. That is correct only while no such kind + /// is searchable or a message edit; adding one needs the replacement paths + /// to queue the superseded version too. + #[test] + fn searchable_kinds_are_regular_events() { + for kind in SEARCHABLE_KINDS.into_iter().chain([KIND_MESSAGE_EDIT]) { + let nostr_kind = nostr::Kind::from(kind as u16); + assert!( + !nostr_kind.is_replaceable() + && !nostr_kind.is_addressable() + && !nostr_kind.is_ephemeral(), + "kind {kind} is replaceable, addressable or ephemeral" + ); + } + } +} diff --git a/crates/buzz-db/src/store/search_outbox_postgres_tests.rs b/crates/buzz-db/src/store/search_outbox_postgres_tests.rs index 49360d4f3c..0616decaff 100644 --- a/crates/buzz-db/src/store/search_outbox_postgres_tests.rs +++ b/crates/buzz-db/src/store/search_outbox_postgres_tests.rs @@ -235,12 +235,38 @@ async fn disabled_outbox_queues_nothing() { assert_eq!(queued(pool, community).await, 0); } -/// Enabling fails, and leaves admission unchanged, while the table is missing. +/// Account deletion queues index changes once an indexing relay has started, +/// even while the outbox and the backfill are both empty. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn the_index_counts_as_maintained_once_a_relay_enabled_it() { + let db = connect().await; + let pool = db.pool(); + let mut conn = pool.acquire().await.expect("connect"); + assert!(!search_outbox::index_maintained(&mut conn) + .await + .expect("read before enabling")); + // Mutation: drop the sequence check from index_maintained → RED. + search_outbox::enable(pool).await.expect("enable outbox"); + assert!(search_outbox::index_maintained(&mut conn) + .await + .expect("read after enabling")); +} + +/// Enabling fails, and leaves admission unchanged, while the version +/// sequence or the table is missing. #[tokio::test] #[ignore = "requires Postgres"] async fn enable_requires_the_table() { let db = connect().await; let pool = db.pool(); + sqlx::query("DROP SEQUENCE search_index_version") + .execute(pool) + .await + .expect("drop sequence"); + search_outbox::enable(pool) + .await + .expect_err("enable refuses a database without the version sequence"); sqlx::query("DROP TABLE search_outbox") .execute(pool) .await @@ -299,3 +325,138 @@ async fn claim_passes_over_skipped_and_held_communities() { .expect("claim") .is_none()); } + +/// Two workers can claim one community at once, but never rows of the same +/// event. A message changed or deleted while a batch holds its earlier row +/// gets a new row that no concurrent batch can claim; it is claimed, with the +/// newer state, only once the holding batch completes. So a stale state +/// never overwrites a newer one, and a delete is never followed by a stale +/// write. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn concurrent_claims_of_one_community_never_share_an_event() { + let db = connect().await; + let pool = db.pool(); + search_outbox::enable(pool).await.expect("enable outbox"); + let community = create_community(pool).await; + let keys = Keys::generate(); + for n in 0..200 { + db.insert_event( + community, + &signed(&keys, 9, &format!("message {n}"), vec![]), + None, + ) + .await + .expect("insert"); + } + + let first = search_outbox::claim_batch_share(pool, 1000, &[], 2) + .await + .expect("claim") + .expect("a batch"); + let changed = first.documents[0].event_id; + let deleted = first.documents[1].event_id; + // What an edit and a deletion queue while the first batch is in flight. + for event in [changed, deleted] { + sqlx::query( + "INSERT INTO search_outbox (community_id, event_id, event_created_at) \ + SELECT community_id, id, created_at FROM events \ + WHERE community_id = $1 AND id = $2", + ) + .bind(community.as_uuid()) + .bind(event.as_slice()) + .execute(pool) + .await + .expect("queue a change"); + } + sqlx::query("UPDATE events SET deleted_at = now() WHERE community_id = $1 AND id = $2") + .bind(community.as_uuid()) + .bind(deleted.as_slice()) + .execute(pool) + .await + .expect("delete"); + + let second = search_outbox::claim_batch_share(pool, 1000, &[], 2) + .await + .expect("claim") + .expect("a concurrent batch of the same community"); + assert_eq!(second.community(), community); + let events = + |batch: &search_outbox::SearchOutboxBatch| -> std::collections::BTreeSet<[u8; 32]> { + batch + .documents + .iter() + .map(|document| document.event_id) + .chain(batch.removed.iter().copied()) + .collect() + }; + let (held, concurrent) = (events(&first), events(&second)); + assert!(!concurrent.is_empty()); + assert!( + held.is_disjoint(&concurrent), + "two batches in flight hold the same event" + ); + drop(second); + first.complete().await.expect("complete"); + + // Only now are the changes claimed, with their current state. + let after = search_outbox::claim_batch(pool, 1000, &[]) + .await + .expect("claim") + .expect("a batch"); + assert!(after + .documents + .iter() + .any(|document| document.event_id == changed)); + assert!(after.removed.contains(&deleted)); + assert!(after + .documents + .iter() + .all(|document| document.event_id != deleted)); + after.complete().await.expect("complete"); + assert_eq!(queued(pool, community).await, 0); +} + +/// A worker whose share of the queue head is held by another batch still +/// claims rows from the other partitions, instead of coming back empty and +/// leaving the drain while rows remain. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn a_claim_looks_past_a_held_queue_head() { + let db = connect().await; + let pool = db.pool(); + search_outbox::enable(pool).await.expect("enable outbox"); + let community = create_community(pool).await; + let keys = Keys::generate(); + let partition = + |event: &Event| i32::from(event.id.as_bytes()[0]) % search_outbox::CLAIM_PARTITIONS; + // With batches of 1 among 2 workers, the head is the oldest 4 rows. + let mut head = std::collections::BTreeSet::new(); + for n in 0..4 { + let event = signed(&keys, 9, &format!("head {n}"), vec![]); + head.insert(partition(&event)); + db.insert_event(community, &event, None) + .await + .expect("insert"); + } + let behind = (0..) + .map(|n| signed(&keys, 9, &format!("behind {n}"), vec![])) + .find(|event| !head.contains(&partition(event))) + .expect("an event outside the head's partitions"); + db.insert_event(community, &behind, None) + .await + .expect("insert"); + + let first = search_outbox::claim_batch_share(pool, 1, &[], 2) + .await + .expect("claim") + .expect("a batch"); + let second = search_outbox::claim_batch_share(pool, 1, &[], 2) + .await + .expect("claim") + .expect("a batch from past the held head"); + assert_eq!(second.documents.len(), 1); + assert_eq!(second.documents[0].event_id, *behind.id.as_bytes()); + drop(second); + drop(first); +} diff --git a/crates/buzz-db/src/store/user_deletion/content_batches/execute.rs b/crates/buzz-db/src/store/user_deletion/content_batches/execute.rs index d4752e0a4a..3ff459c791 100644 --- a/crates/buzz-db/src/store/user_deletion/content_batches/execute.rs +++ b/crates/buzz-db/src/store/user_deletion/content_batches/execute.rs @@ -146,6 +146,11 @@ pub(super) async fn execute_owned_batch( .await?; crate::deletion::guard_community_write(&mut tx, crate::CommunityId::from_uuid(community)) .await?; + // This runs outside the relay (`buzz-admin user-deletions`), where nothing + // else turns the outbox on. An indexer marks the database before it reads + // any message, and its reads wait for this lock, so checking here, per + // batch, also covers an indexer that starts mid-job. + crate::search_outbox::enable_if_indexed(&mut tx).await?; ownership::recheck(&mut tx, options, start).await?; if let Some((lease, stage_id)) = stage { let request = crate::store::entity_deletion::lock_owned(&mut tx, lease).await?; diff --git a/crates/buzz-db/src/store/user_deletion/content_batches/grouped.rs b/crates/buzz-db/src/store/user_deletion/content_batches/grouped.rs index ad3123f9e3..17731ad1da 100644 --- a/crates/buzz-db/src/store/user_deletion/content_batches/grouped.rs +++ b/crates/buzz-db/src/store/user_deletion/content_batches/grouped.rs @@ -194,6 +194,19 @@ async fn erase_events(tx: &mut AdmittedTx, number: i64) -> Result<()> { if referenced || !legacy.is_empty() { return Err(invalid("new surviving references appeared; current batch rolled back; rerun to classify delete versus scrub")); } + // Queue the index changes while every row and its edit target still exist. + let (changed, changed_at): (Vec>, Vec>) = + sqlx::query_as::<_, (Vec, DateTime)>( + "SELECT decode(row_key->>'id','hex'),(row_key->>'created_at')::timestamptz + FROM content_batch_work WHERE table_name='events' AND batch=$1 + AND action IN ('would_delete','would_scrub')", + ) + .bind(number) + .fetch_all(tx.conn()) + .await? + .into_iter() + .unzip(); + crate::search_outbox::enqueue_events_in_transaction(tx, &changed, &changed_at).await?; // Keep counters consistent in every committed prefix, including interruption. sqlx::query(include_str!("account.sql")) .bind(community) diff --git a/crates/buzz-db/src/store/user_deletion/content_batches/mod.rs b/crates/buzz-db/src/store/user_deletion/content_batches/mod.rs index e251daf999..30e90472fc 100644 --- a/crates/buzz-db/src/store/user_deletion/content_batches/mod.rs +++ b/crates/buzz-db/src/store/user_deletion/content_batches/mod.rs @@ -387,3 +387,6 @@ mod files_postgres_tests; #[cfg(test)] mod schedule_postgres_tests; + +#[cfg(test)] +mod search_postgres_tests; diff --git a/crates/buzz-db/src/store/user_deletion/content_batches/search_postgres_tests.rs b/crates/buzz-db/src/store/user_deletion/content_batches/search_postgres_tests.rs new file mode 100644 index 0000000000..4b3bd15f3f --- /dev/null +++ b/crates/buzz-db/src/store/user_deletion/content_batches/search_postgres_tests.rs @@ -0,0 +1,127 @@ +//! Account deletion queues search index changes in its own process. +//! +//! `buzz-admin user-deletions` never calls `search_outbox::enable`, so these +//! tests leave it off, as that process does. nextest runs each test in its +//! own process, so the flag one test turns on does not leak into the other. +use super::scrub_postgres_tests::{message, options, setup}; +use crate::user_deletion::ExecutionMode; + +/// When an indexing relay first runs against the database. +#[derive(PartialEq)] +enum Indexer { + Never, + BeforeTheJob, + /// After the job has planned its batches, before it runs them. + DuringTheJob, +} + +/// Job output that, once the job starts deleting, takes a value from the +/// version sequence as an indexing relay does when it starts. +struct IndexerStartsMidJob { + pool: sqlx::PgPool, + output: Vec, + started: bool, +} + +impl std::io::Write for IndexerStartsMidJob { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + self.output.extend_from_slice(buf); + Ok(buf.len()) + } + + fn flush(&mut self) -> std::io::Result<()> { + if !self.started && self.output.windows(12).any(|w| w == b"delete_start") { + self.started = true; + let pool = self.pool.clone(); + tokio::task::block_in_place(|| { + tokio::runtime::Handle::current() + .block_on(sqlx::query("SELECT nextval('search_index_version')").execute(&pool)) + }) + .map_err(std::io::Error::other)?; + } + Ok(()) + } +} + +/// Scrub one message (it has a reply from someone else) and erase another, +/// and return the queued event ids and the two messages' ids. +async fn delete_account(indexer: Indexer) -> (Vec>, [Vec; 2]) { + let (db, community, channel, alice, bob) = setup().await; + let root = message(&db, community, channel, &alice, "referenced", None).await; + message( + &db, + community, + channel, + &bob, + "reply", + Some((&root, &root, 1)), + ) + .await; + let alone = message(&db, community, channel, &alice, "alone", None).await; + if indexer == Indexer::BeforeTheJob { + // What an indexing relay's backfill leaves behind. + sqlx::query("INSERT INTO search_backfill (community_id, completed_at) VALUES ($1, now())") + .bind(community.as_uuid()) + .execute(db.pool()) + .await + .unwrap(); + } + let mut output = IndexerStartsMidJob { + pool: db.pool().clone(), + output: Vec::new(), + started: indexer != Indexer::DuringTheJob, + }; + let summary = db + .user_deletion_store() + .run_message_batches( + &options(community, &alice), + ExecutionMode::Delete, + None, + &mut output, + ) + .await + .unwrap(); + assert_eq!( + summary.scrubbed_events, 1, + "the replied-to root is scrubbed" + ); + let queued: Vec> = sqlx::query_scalar( + "SELECT event_id FROM search_outbox WHERE community_id = $1 ORDER BY event_id", + ) + .bind(community.as_uuid()) + .fetch_all(db.pool()) + .await + .unwrap(); + ( + queued, + [root.id.as_bytes().to_vec(), alone.id.as_bytes().to_vec()], + ) +} + +/// Once an indexer maintains this database, the scrubbed and the erased +/// message are queued, so their documents leave the index. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn account_deletion_queues_its_changes_when_an_index_is_maintained() { + let (queued, mut deleted) = delete_account(Indexer::BeforeTheJob).await; + deleted.sort(); + assert_eq!(queued, deleted.to_vec()); +} + +/// An indexer that starts while the job runs may already have indexed the +/// messages the job removes, so their changes are queued too. +#[tokio::test(flavor = "multi_thread")] +#[ignore = "requires Postgres"] +async fn account_deletion_queues_its_changes_when_indexing_starts_mid_job() { + let (queued, mut deleted) = delete_account(Indexer::DuringTheJob).await; + deleted.sort(); + assert_eq!(queued, deleted.to_vec()); +} + +/// Without an indexer nothing would drain the outbox, so nothing is queued. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn account_deletion_queues_nothing_without_an_index() { + let (queued, _) = delete_account(Indexer::Never).await; + assert!(queued.is_empty()); +} diff --git a/crates/buzz-db/tests/observability_source.rs b/crates/buzz-db/tests/observability_source.rs index 99df6ee01c..749505a096 100644 --- a/crates/buzz-db/tests/observability_source.rs +++ b/crates/buzz-db/tests/observability_source.rs @@ -4117,3 +4117,187 @@ fn every_production_single_table_guard_writer_preserves_its_invariants() { ); } } + +/// Whether `source` updates or deletes `events` rows (or a partition's), in +/// the same normalized forms [`inserts_events_row`] recognizes. +fn changes_events_rows(source: &str) -> bool { + let normalized = normalized_sql(source); + ["update ", "delete from "].iter().any(|verb| { + normalized.match_indices(verb).any(|(index, _)| { + let rest = &normalized[index + verb.len()..]; + let rest = rest.strip_prefix("public.").unwrap_or(rest); + let table_len = rest + .find(|ch: char| !(ch.is_ascii_alphanumeric() || ch == '_')) + .unwrap_or(rest.len()); + is_events_table(&rest[..table_len]) + }) + }) +} + +fn queues_search_outbox(function_source: &str) -> bool { + let code = mask_comments_and_literals(function_source); + code.contains("search_outbox::enqueue_in_transaction(") + || code.contains("search_outbox::enqueue_events_in_transaction(") +} + +/// Production functions that update or delete `events` rows without queuing a +/// search outbox row, as `file: header`, each because it only ever touches +/// kinds that are never searchable (or columns search never reads). A slice +/// runs to the next function, so a module-level SQL constant counts toward the +/// function above it. +const SEARCH_OUTBOX_EXEMPT_EVENT_WRITERS: [(&str, &str); 10] = [ + ( + "store/event.rs: pub async fn soft_delete_discovery_events(", + "NIP-29 discovery kinds 39000-39002", + ), + ( + "store/event_deletion.rs: pub(crate) async fn remove_coordinate_versions_in_tx(", + "addressable coordinates, plus the known-event SQL constants of \ + soft_delete_event_and_update_thread_in_tx, which queues", + ), + ( + "store/replaceable.rs: async fn replace_parameterized_event_in_transaction_impl(", + "replaceable and addressable kinds, plus the module's supersede macros", + ), + ( + "store/push.rs: pub async fn accept_lease_event(", + "push lease kind 30350", + ), + ( + "store/pins.rs: async fn delete_erased_command_records(", + "pin command kinds", + ), + ( + "store/reminder.rs: pub async fn claim_due_reminder_with_stamp(", + "reminder kind 30300 delivery stamp", + ), + ( + "store/reminder.rs: pub async fn release_due_reminder(", + "reminder kind 30300 delivery stamp", + ), + ( + "store/workflow/deletion.rs: async fn delete_workflow_in_transaction(", + "workflow definition kind", + ), + ( + "store/user_deletion/account_batches/memberships.rs: pub(super) async fn rebuild(", + "channel metadata kinds 39000-39002", + ), + ( + "store/user_deletion/profile_batches/events.rs: pub(super) async fn replace_snapshot(", + "profile and identity kinds", + ), +]; + +#[test] +fn search_outbox_policy_rejects_event_writers_without_the_hook() { + let source = r#" +pub(crate) async fn silent_delete(tx: &mut AdmittedTx) { + sqlx::query("UPDATE events SET deleted_at = NOW() WHERE id = $1"); +} +pub(crate) async fn silent_purge(tx: &mut AdmittedTx) { + sqlx::query("DELETE FROM \"public\".\"events_p2026_01\" WHERE id = $1"); +} +pub(crate) async fn queued_delete(tx: &mut AdmittedTx) { + sqlx::query("UPDATE events e SET content = '' WHERE id = $1"); + crate::search_outbox::enqueue_in_transaction(tx, id, created_at, kind).await?; +} +pub(crate) async fn other_table(tx: &mut AdmittedTx) { + sqlx::query("UPDATE event_mentions SET pubkey_hex = '' WHERE id = $1"); + sqlx::query("DELETE FROM events_outbox WHERE id = $1"); +} +pub(crate) async fn commented_hook(tx: &mut AdmittedTx) { + sqlx::query("UPDATE events SET content = '' WHERE id = $1"); + // crate::search_outbox::enqueue_in_transaction(tx, id, created_at, kind) +} +"#; + let violations: Vec<&str> = function_slices(source) + .into_iter() + .filter(|function| changes_events_rows(function) && !queues_search_outbox(function)) + .map(function_header) + .collect(); + assert_eq!( + violations, + [ + "pub(crate) async fn silent_delete(tx: &mut AdmittedTx) {", + "pub(crate) async fn silent_purge(tx: &mut AdmittedTx) {", + "pub(crate) async fn commented_hook(tx: &mut AdmittedTx) {", + ] + ); +} + +/// Every production write that changes or removes an `events` row queues a +/// search outbox row in its transaction, unless it is listed in +/// [`SEARCH_OUTBOX_EXEMPT_EVENT_WRITERS`]. A new delete, scrub or edit path +/// that skips the outbox would leave stale documents in the search index. +#[test] +fn every_production_event_change_queues_the_search_outbox() { + let src = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); + let files = production_event_writer_source_files(); + let mut queued = Vec::new(); + let mut unlisted = Vec::new(); + let mut exempt_seen = Vec::new(); + for path in files { + let source = std::fs::read_to_string(&path).expect("read source file"); + let production = strip_cfg_test_items(&source); + if !changes_events_rows(&production) { + continue; + } + let name = path + .strip_prefix(&src) + .map(|relative| relative.display().to_string()) + .unwrap_or_else(|_| path.display().to_string()); + for function in function_slices(&production) { + if !changes_events_rows(function) { + continue; + } + let key = format!("{name}: {}", function_header(function)); + if queues_search_outbox(function) { + queued.push(key); + } else if SEARCH_OUTBOX_EXEMPT_EVENT_WRITERS + .iter() + .any(|(exempt, _)| key.starts_with(exempt)) + { + exempt_seen.push(key); + } else { + unlisted.push(key); + } + } + } + assert!( + unlisted.is_empty(), + "these production functions update or delete `events` rows without queuing a \ + search_outbox row; call search_outbox::enqueue_in_transaction (or \ + enqueue_events_in_transaction) in the same transaction, or add the function to \ + SEARCH_OUTBOX_EXEMPT_EVENT_WRITERS with why it never touches searchable content: \ + {unlisted:?}" + ); + assert_eq!( + queued, + [ + "store/user_deletion/content_batches/grouped.rs: async fn erase_events(tx: &mut AdmittedTx, number: i64) -> Result<()> {" + ], + "the scan stopped seeing a queuing writer" + ); + // The shared soft delete (NIP-09, NIP-29 and moderation deletes) runs SQL + // constants defined above it, which the slice scan attributes to the + // function before them, so pin its hook by name. + let deletion = strip_cfg_test_items( + &std::fs::read_to_string(src.join("store/event_deletion.rs")).expect("read source"), + ); + let soft_delete = function_slices(&deletion) + .into_iter() + .find(|function| { + function_header(function) + .starts_with("pub(crate) async fn soft_delete_event_and_update_thread_in_tx(") + }) + .expect("the shared soft delete exists"); + assert!(soft_delete.contains("SOFT_DELETE_KNOWN_EVENT_SQL")); + assert!(queues_search_outbox(soft_delete)); + for (exempt, _) in SEARCH_OUTBOX_EXEMPT_EVENT_WRITERS { + assert!( + exempt_seen.iter().any(|key| key.starts_with(exempt)), + "stale exemption, no longer an events writer: {exempt}" + ); + } +} diff --git a/crates/buzz-relay/src/config.rs b/crates/buzz-relay/src/config.rs index f1c55a19d9..1e1a871a67 100644 --- a/crates/buzz-relay/src/config.rs +++ b/crates/buzz-relay/src/config.rs @@ -311,6 +311,12 @@ pub struct Config { /// indexer keeps the index up to date; searches still use Postgres. pub opensearch: Option, + /// Search indexer workers on the lease-holding instance + /// (`BUZZ_SEARCH_INDEXER_WORKERS`, default 1): how many bulk requests, + /// each holding a database connection, it keeps in flight. Workers can + /// share one community's queue. + pub search_indexer_workers: usize, + /// Allow NIP-OA owner attestation for relay membership. /// /// When `true` and `require_relay_membership` is also `true`, agents @@ -1036,6 +1042,9 @@ impl Config { parse_bool("BUZZ_OPENSEARCH_PREVIEW", false)?, ) .map_err(ConfigError::InvalidValue)?; + let search_indexer_workers = + parse_search_indexer_workers(optional_utf8_env("BUZZ_SEARCH_INDEXER_WORKERS")?) + .map_err(ConfigError::InvalidValue)?; if !operator_listener_delivery_urls.is_empty() && relay_operator_api_origin.is_none() { error!( "BUZZ_OPERATOR_LISTENERS is set but RELAY_OPERATOR_API_ORIGIN is not — operator-listener registration requests will reject every request until RELAY_OPERATOR_API_ORIGIN is set" @@ -1586,6 +1595,7 @@ impl Config { operator_listener_delivery_urls, storage_usage_delivery_url, opensearch, + search_indexer_workers, allow_nip_oa_auth, klipy, media, @@ -1661,12 +1671,26 @@ fn optional_utf8_env(name: &str) -> Result, ConfigError> { } } +/// Parse the search indexer worker count: a whole number from 1 to 32, +/// default 1. +fn parse_search_indexer_workers(value: Option) -> Result { + let Some(value) = value.filter(|value| !value.trim().is_empty()) else { + return Ok(1); + }; + value + .trim() + .parse::() + .ok() + .filter(|workers| (1..=32).contains(workers)) + .ok_or_else(|| "BUZZ_SEARCH_INDEXER_WORKERS must be a whole number from 1 to 32".into()) +} + /// Parse the OpenSearch settings: an HTTP(S) URL without credentials, query, /// or fragment, and basic credentials given both or neither. Empty values /// count as unset. /// -/// Deletes and edits don't reach the index yet, so a URL also needs the -/// `BUZZ_OPENSEARCH_PREVIEW` opt-in. +/// Deleting a community doesn't remove its documents from the index yet, so +/// a URL also needs the `BUZZ_OPENSEARCH_PREVIEW` opt-in. fn parse_opensearch_config( url: Option, username: Option, @@ -1685,7 +1709,7 @@ fn parse_opensearch_config( return Ok(None); }; if !preview { - return Err("BUZZ_OPENSEARCH_URL needs BUZZ_OPENSEARCH_PREVIEW=true: deleted messages stay in the index, so use it only on a relay without real data".into()); + return Err("BUZZ_OPENSEARCH_URL needs BUZZ_OPENSEARCH_PREVIEW=true: a deleted community's messages stay in the index, so use it only on a relay without real data".into()); } let parsed = url::Url::parse(raw.trim()) .map_err(|e| format!("BUZZ_OPENSEARCH_URL is not a valid URL: {e}"))?; @@ -1718,6 +1742,20 @@ fn parse_opensearch_config( mod tests { use super::*; + #[test] + fn search_indexer_workers_default_to_one_and_are_bounded() { + let some = |value: &str| Some(value.to_string()); + assert_eq!(parse_search_indexer_workers(None), Ok(1)); + assert_eq!(parse_search_indexer_workers(some(" ")), Ok(1)); + assert_eq!(parse_search_indexer_workers(some("4")), Ok(4)); + for invalid in ["0", "33", "-1", "two"] { + assert!( + parse_search_indexer_workers(some(invalid)).is_err(), + "{invalid}" + ); + } + } + #[test] fn opensearch_config_is_optional_and_validated() { let some = |value: &str| Some(value.to_string()); diff --git a/crates/buzz-relay/src/main.rs b/crates/buzz-relay/src/main.rs index 71ea6c20e0..12f56c6f1d 100644 --- a/crates/buzz-relay/src/main.rs +++ b/crates/buzz-relay/src/main.rs @@ -665,7 +665,10 @@ async fn run_relay_main(boot: BootTracker) -> anyhow::Result<()> { .await .map_err(|e| anyhow::anyhow!("search outbox: {e}"))?; info!(url = %opensearch.url, "search outbox enabled"); - Some(buzz_search::indexer::Indexer::new(db.clone(), index)) + Some( + buzz_search::indexer::Indexer::new(db.clone(), index) + .with_workers(config.search_indexer_workers), + ) } None => None, }; diff --git a/crates/buzz-search/Cargo.toml b/crates/buzz-search/Cargo.toml index 5cc2e50a28..61c1012fff 100644 --- a/crates/buzz-search/Cargo.toml +++ b/crates/buzz-search/Cargo.toml @@ -25,3 +25,6 @@ rand = { workspace = true } [dev-dependencies] nostr = { workspace = true } +axum = { workspace = true } +reqwest = { workspace = true } +metrics-exporter-prometheus = { workspace = true } diff --git a/crates/buzz-search/src/indexer.rs b/crates/buzz-search/src/indexer.rs index e615531065..b9d4b7c213 100644 --- a/crates/buzz-search/src/indexer.rs +++ b/crates/buzz-search/src/indexer.rs @@ -8,11 +8,17 @@ //! A batch holds its community's admission open for up to one request //! timeout. Community deletion's quiesce step waits for that batch, and once //! the community is quiescing no new batch for it can start. +//! +//! Only the lease holder backfills (see `buzz_db::search_backfill`), so a +//! fleet queues each stored event once, and only while the outbox has room, +//! so live rows wait behind a bounded number of backfill rows. -use std::time::Duration; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Arc; +use std::time::{Duration, Instant}; -use buzz_db::{search_outbox, Db, DbError}; -use tracing::{info, warn}; +use buzz_db::{search_backfill, search_outbox, Db, DbError}; +use tracing::{debug, error, info, warn}; use crate::opensearch::SearchIndex; use crate::SearchError; @@ -24,9 +30,19 @@ const INDEXER_LOCK_KEY: i64 = 0x4255_5A5A_5345_4152; /// Outbox rows per batch, and so documents per bulk request. const BATCH_SIZE: i64 = 500; +/// Backfill queues keys only while the outbox holds fewer rows than this. +const BACKFILL_OUTBOX_BOUND: i64 = 4 * BATCH_SIZE; + /// How often an idle leader checks the queue, and a follower the lease. const POLL_INTERVAL: Duration = Duration::from_secs(5); +/// How long after its creation a new index is left alone before the first +/// write, whichever relay holds the lease. On OpenSearch +/// Serverless a write sent within two seconds of creating an index that +/// replaces a deleted one can be acknowledged by the deleted index and lost, +/// under the same name or another, and requests can fail for ten seconds. +const NEW_INDEX_SETTLE: Duration = Duration::from_secs(30); + /// Longest wait after repeated failures. const MAX_BACKOFF: Duration = Duration::from_secs(60); @@ -39,6 +55,31 @@ pub enum IndexerError { /// The index write failed. #[error("index write: {}", .0.kind())] Index(#[from] SearchError), + /// OpenSearch throttled a write (HTTP 429). Not a failure: back off. + #[error("index write throttled")] + Throttled, +} + +/// What a drain indexed. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct DrainReport { + /// Bulk requests whose rows were completed. + pub batches: u64, + /// Documents written. + pub written: u64, + /// Documents removed. + pub removed: u64, + /// Items that failed; their rows stay queued. + pub failed: u64, +} + +impl DrainReport { + fn add(&mut self, other: DrainReport) { + self.batches += other.batches; + self.written += other.written; + self.removed += other.removed; + self.failed += other.failed; + } } /// Moves queued events from `search_outbox` into a [`SearchIndex`]. @@ -46,58 +87,334 @@ pub enum IndexerError { pub struct Indexer { db: Db, index: SearchIndex, + batch_size: i64, + backfill_bound: i64, + workers: usize, + new_index_settle: Duration, } impl Indexer { /// An indexer reading the outbox from `db` and writing `index`. pub fn new(db: Db, index: SearchIndex) -> Self { - Self { db, index } + Self { + db, + index, + batch_size: BATCH_SIZE, + backfill_bound: BACKFILL_OUTBOX_BOUND, + workers: 1, + new_index_settle: NEW_INDEX_SETTLE, + } } - /// Index batches until none is left to claim. A community whose batch - /// the cluster rejects is skipped for the rest of the pass and reported - /// once the others are done; any other failure ends the pass. - pub async fn drain(&self) -> Result<(), IndexerError> { - let mut skipped: Vec = Vec::new(); - let mut rejection = None; - while let Some(batch) = - search_outbox::claim_batch(self.db.pool(), BATCH_SIZE, &skipped).await? - { - let community = batch.community(); - match self - .index - .write(community, &batch.documents, &batch.removed) - .await - { - Ok(()) => batch.complete().await?, - Err(error @ SearchError::Rejected(_)) => { - warn!(%community, error = %error.kind(), "search index rejected a batch; its rows stay queued"); - skipped.push(community); - rejection.get_or_insert(error); + /// Leave a new index alone for `settle` after its creation instead of + /// [`NEW_INDEX_SETTLE`]. For tests on a cluster that needs no wait. + pub fn with_new_index_settle(mut self, settle: Duration) -> Self { + self.new_index_settle = settle; + self + } + + /// Run `workers` (at least one) batches at once when draining, of one + /// community or several. This also bounds the bulk requests in flight. + pub fn with_workers(mut self, workers: usize) -> Self { + self.workers = workers.max(1); + self + } + + /// Claim at most `rows` outbox rows per bulk request, and backfill as + /// many event keys per step (at least one). + pub fn with_batch_size(mut self, rows: i64) -> Self { + self.batch_size = rows.max(1); + self + } + + /// Backfill only while the outbox holds fewer than `rows` rows. + pub fn with_backfill_bound(mut self, rows: i64) -> Self { + self.backfill_bound = rows; + self + } + + /// Queue backfill batches, one community at a time in turn, while the + /// outbox holds fewer rows than the backfill bound. Returns the number of + /// event keys queued: zero when every community's backfill is complete + /// or the outbox is full. + /// + /// Call it only on the lease holder, as [`Indexer::run`] does, so a + /// fleet queues each stored event once. + pub async fn backfill(&self) -> Result { + let pool = self.db.pool(); + let mut queued = 0u64; + // With several workers, queue two batches per worker, so each has + // full batches and the serial backfill runs less often. + let bound = if self.workers > 1 { + self.backfill_bound + .max(2 * self.workers as i64 * self.batch_size) + } else { + self.backfill_bound + }; + while search_backfill::outbox_below(pool, bound).await? { + let Some(step) = search_backfill::step(pool, self.batch_size, &[]).await? else { + break; + }; + let community = step.community.to_string(); + metrics::counter!("buzz_search_backfill_queued_total", "community" => community.clone()) + .increment(step.queued); + if let Some(cursor) = step.cursor { + metrics::gauge!("buzz_search_backfill_cursor_timestamp_seconds", "community" => community.clone()) + .set(cursor.timestamp() as f64); + } + metrics::gauge!("buzz_search_backfill_complete", "community" => community) + .set(if step.completed { 1.0 } else { 0.0 }); + if step.completed { + info!(community = %step.community, queued = step.total_queued, "search backfill complete"); + } else { + debug!(community = %step.community, queued = step.queued, cursor = ?step.cursor, "search backfill step"); + } + queued += step.queued; + } + Ok(queued) + } + + /// Index batches with the configured number of workers until none is + /// left to claim. A community whose batch had a failed item is skipped + /// for the rest of the pass by that worker, unless every failure was a + /// refused item and the rest of the batch succeeded. Throttling stops every worker + /// and returns [`IndexerError::Throttled`]; another failure ends its + /// worker's drain and is returned once the others are done. Items the + /// cluster refuses for good are logged and counted, not returned. + /// + /// Ends with an info log of the documents written and removed and the + /// elapsed time, for measuring throughput. + pub async fn drain(&self) -> Result { + let started = Instant::now(); + let stop = Arc::new(AtomicBool::new(false)); + let mut report = DrainReport::default(); + let mut result = Ok(()); + let mut keep = |worker_report: DrainReport, outcome: Result<(), IndexerError>| { + report.add(worker_report); + // Keep the first failure; it outranks throttling. + if let Err(error) = outcome { + if !matches!( + result, + Err(IndexerError::Outbox(_) | IndexerError::Index(_)) + ) { + result = Err(error); + } + } + }; + if self.workers == 1 { + let mut worker_report = DrainReport::default(); + let outcome = self.drain_worker(&mut worker_report, &stop).await; + keep(worker_report, outcome); + } else { + let mut workers = tokio::task::JoinSet::new(); + for _ in 0..self.workers { + let (indexer, stop) = (self.clone(), Arc::clone(&stop)); + workers.spawn(async move { + let mut worker_report = DrainReport::default(); + let outcome = indexer.drain_worker(&mut worker_report, &stop).await; + (worker_report, outcome) + }); + } + while let Some(joined) = workers.join_next().await { + match joined { + Ok((worker_report, outcome)) => keep(worker_report, outcome), + Err(error) => keep( + DrainReport::default(), + Err(SearchError::Engine(format!("indexer worker ended: {error}")).into()), + ), } - Err(error) => return Err(error.into()), } } - rejection.map_or(Ok(()), |error| Err(error.into())) + if report.batches > 0 { + let elapsed = started.elapsed(); + let indexed = report.written + report.removed; + info!( + workers = self.workers, + batches = report.batches, + written = report.written, + removed = report.removed, + failed = report.failed, + elapsed_ms = elapsed.as_millis() as u64, + documents_per_second = + (indexed as f64 / elapsed.as_secs_f64().max(1e-3)).round() as u64, + "search indexer drained the outbox" + ); + } + result.map(|()| report) } - /// One leader pass: make sure the index exists, then drain. Checking - /// every pass (one request when the alias exists) recreates an index - /// that went away, and creating it here rather than at startup means an - /// unreachable cluster never delays serving. - async fn pass(&self) -> Result<(), IndexerError> { - self.index.ensure().await?; - self.drain().await + /// One worker's share of a drain. + async fn drain_worker( + &self, + report: &mut DrainReport, + stop: &AtomicBool, + ) -> Result<(), IndexerError> { + let mut skipped: Vec = Vec::new(); + let mut failure = None; + while !stop.load(Ordering::Relaxed) { + let Some(batch) = search_outbox::claim_batch_share( + self.db.pool(), + self.batch_size, + &skipped, + self.workers, + ) + .await? + else { + break; + }; + let community = batch.community(); + let outcome = match self + .index + .write(community, &batch.documents, &batch.removed, batch.version) + .await + { + Ok(outcome) => outcome, + Err(error @ SearchError::Rejected(_)) => { + // The whole request was refused; its rows stay queued. + warn!(%community, error = %error.kind(), "search index rejected a batch; its rows stay queued"); + metrics::counter!("buzz_search_index_rejected_total", "community" => community.to_string()) + .increment((batch.documents.len() + batch.removed.len()) as u64); + skipped.push(community); + continue; + } + Err(error) => return Err(error.into()), + }; + let items = (batch.documents.len() + batch.removed.len()) as u64; + let written = batch + .documents + .iter() + .filter(|document| !outcome.failed.contains(&document.event_id)) + .count() as u64; + let removed = batch + .removed + .iter() + .filter(|event| !outcome.failed.contains(event)) + .count() as u64; + batch.complete_except(&outcome.failed).await?; + let label = community.to_string(); + metrics::counter!("buzz_search_indexed_documents_total", "community" => label.clone(), "op" => "write") + .increment(written); + metrics::counter!("buzz_search_indexed_documents_total", "community" => label.clone(), "op" => "remove") + .increment(removed); + report.batches += 1; + report.written += written; + report.removed += removed; + if outcome.failed.is_empty() { + continue; + } + report.failed += outcome.failed.len() as u64; + let reason = outcome.reason.as_deref().unwrap_or("unknown"); + if outcome.throttled { + stop.store(true, Ordering::Relaxed); + return Err(IndexerError::Throttled); + } + if outcome.rejected > 0 { + metrics::counter!("buzz_search_index_rejected_total", "community" => label.clone()) + .increment(outcome.rejected as u64); + } + if outcome.conflicts > 0 { + // This batch is its events' newest writer, so the index can + // hold a newer version only if the version sequence handed + // out a value again, as after a Postgres crash or promoting + // an asynchronous replica. Keep the rows: the retry carries a later version + // once the sequence passes the one held. + error!(%community, items = outcome.conflicts, "search index holds a newer version than the batch writing it; the version sequence went back; its rows stay queued"); + metrics::counter!("buzz_search_index_version_conflicts_total", "community" => label) + .increment(outcome.conflicts as u64); + } + if outcome.rejected == outcome.failed.len() { + warn!(%community, items = outcome.rejected, reason, "search index rejected documents; their rows stay queued"); + // Refused items are claimed again with the next batch; keep + // going while the rest of each batch succeeds. + if written + removed == 0 && items > 0 { + skipped.push(community); + } + } else { + skipped.push(community); + failure.get_or_insert(SearchError::Engine(format!( + "{} bulk items failed ({reason})", + outcome.failed.len() + ))); + } + } + failure.map_or(Ok(()), |error| Err(error.into())) + } + + /// Set `buzz_search_backfill_complete` for every community from stored + /// progress. A backfill step sets it only for the community it advanced, + /// so a relay that takes the lease after a backfill finished would never + /// report it. + async fn publish_backfill_progress(&self) { + match search_backfill::progress(self.db.pool()).await { + Ok(progress) => { + for (community, completed) in progress { + metrics::gauge!("buzz_search_backfill_complete", "community" => community.to_string()) + .set(if completed { 1.0 } else { 0.0 }); + } + } + Err(error) => warn!(%error, "could not read search backfill progress"), + } + } + + /// One leader pass: make sure the index exists, top the outbox up with + /// backfill, then drain. Checking the index every pass (one request when + /// the alias exists) recreates an index that went away, and creating it + /// here rather than at startup means an unreachable cluster never delays + /// serving. Backfilling before draining keeps it going while a rejected + /// batch's rows stay queued. Returns whether backfill queued anything, in + /// which case the next pass should follow at once. + /// + /// `settled` is false until this lease holder has made sure the index is + /// at least the settle time old. + async fn pass(&self, settled: &mut bool) -> Result { + let mut created = false; + if self.index.missing().await? { + // A new index is empty, whatever the stored progress says (the + // old one was deleted or lost): backfill every community. Clear + // the progress before creating the index, so a crash between the + // two leaves the index missing and the next pass clears again. + let reset = search_backfill::reset(self.db.pool()).await?; + info!( + communities = reset, + "search index missing; backfilling every community again" + ); + // Also when no row was left to remove, as after a crash before + // the create, so no community still reports a complete backfill. + self.publish_backfill_progress().await; + *settled = false; + created = self.index.create().await?; + } + if created { + tokio::time::sleep(self.new_index_settle).await; + } else if !*settled { + // The relay that created the index may have lost the lease before + // its wait ended. Without the creation time, wait the whole time. + let age = self.index.age().await.unwrap_or_else(|error| { + warn!(error = %error.kind(), "could not read when the search index was created"); + Duration::ZERO + }); + tokio::time::sleep(self.new_index_settle.saturating_sub(age)).await; + } + *settled = true; + let backfilled = self.backfill().await?; + self.drain().await?; + Ok(backfilled > 0) } /// Hold the indexer lease and keep the index up to date, forever. Abort /// the task to stop; that closes the lease connection and lets another /// instance take over. + /// + /// Every wait is jittered, so instances restarted together spread their + /// lease attempts instead of polling Postgres in step. Failed lease + /// attempts and failed passes back off up to [`MAX_BACKOFF`]; so does + /// throttling, which is counted and logged apart from failures. pub async fn run(self) { - // Spread lease attempts of instances that start together. tokio::time::sleep(POLL_INTERVAL.mul_f64(rand::random::())).await; let mut leader: Option = None; + let mut settled = false; let mut failures = 0u32; + let mut throttled = 0u32; loop { if let Some(guard) = leader.as_mut() { if !guard.is_live().await { @@ -110,31 +427,50 @@ impl Indexer { Ok(Some(acquired)) => { info!("acquired the search indexer lease"); leader = Some(acquired); + settled = false; + failures = 0; + self.publish_backfill_progress().await; + } + Ok(None) => failures = 0, + Err(error) => { + failures = failures.saturating_add(1); + warn!(%error, failures, "search indexer lease attempt failed"); } - Ok(None) => {} - Err(error) => warn!(%error, "search indexer lease attempt failed"), } } + let mut backfilling = false; if leader.is_some() { - match self.pass().await { - Ok(()) => failures = 0, + match self.pass(&mut settled).await { + Ok(more) => { + failures = 0; + throttled = 0; + backfilling = more; + } + Err(IndexerError::Throttled) => { + throttled = throttled.saturating_add(1); + metrics::counter!("buzz_search_indexer_throttled_total").increment(1); + info!(throttled, "search index throttled the indexer; backing off"); + } Err(error) => { failures = failures.saturating_add(1); warn!(%error, failures, "search indexing failed; rows stay queued"); } } } - tokio::time::sleep(backoff(failures)).await; + if backfilling { + // Next backfill batch now, after re-checking the lease. + tokio::task::yield_now().await; + continue; + } + tokio::time::sleep(backoff(failures.max(throttled))).await; } } } /// The wait before the next attempt: the poll interval, doubled per -/// consecutive failure up to [`MAX_BACKOFF`], with jitter after a failure. +/// consecutive failure up to [`MAX_BACKOFF`], scaled by a random factor +/// between one half and one. fn backoff(failures: u32) -> Duration { - if failures == 0 { - return POLL_INTERVAL; - } let ceiling = POLL_INTERVAL .saturating_mul(1 << failures.min(4)) .min(MAX_BACKOFF); @@ -146,8 +482,15 @@ mod tests { use super::*; #[test] - fn backoff_grows_to_a_cap() { - assert_eq!(backoff(0), POLL_INTERVAL); + fn backoff_grows_to_a_cap_with_jitter() { + let idle: Vec = (0..64).map(|_| backoff(0)).collect(); + assert!(idle + .iter() + .all(|wait| *wait >= POLL_INTERVAL / 2 && *wait <= POLL_INTERVAL)); + assert!( + idle.iter().any(|wait| *wait != idle[0]), + "idle waits are jittered: {idle:?}" + ); for failures in 1..10 { let wait = backoff(failures); assert!(wait <= MAX_BACKOFF, "{failures}: {wait:?}"); diff --git a/crates/buzz-search/src/opensearch.rs b/crates/buzz-search/src/opensearch.rs index 8a35d89b4c..487242beac 100644 --- a/crates/buzz-search/src/opensearch.rs +++ b/crates/buzz-search/src/opensearch.rs @@ -10,6 +10,7 @@ //! relay re-reads every hit from Postgres, so the index holds only what search //! needs. +use std::ops::Range; use std::time::Duration; use buzz_core::CommunityId; @@ -19,7 +20,10 @@ use opensearch::http::response::Response; use opensearch::http::transport::{SingleNodeConnectionPool, TransportBuilder}; use opensearch::http::Url; use opensearch::indices::IndicesRefreshParts; -use opensearch::indices::{IndicesCreateParts, IndicesDeleteParts, IndicesExistsParts}; +use opensearch::indices::{ + IndicesCreateParts, IndicesDeleteParts, IndicesExistsParts, IndicesGetSettingsParts, +}; +use opensearch::params::VersionType; use opensearch::{BulkOperation, BulkParts, OpenSearch, SearchParts}; use serde_json::{json, Value}; @@ -38,6 +42,44 @@ pub const DEFAULT_INDEX_PREFIX: &str = "buzz-"; /// Bound on every request, so a stalled cluster cannot hold an indexer batch /// (and its admitted transaction) or a search open. const REQUEST_TIMEOUT: Duration = Duration::from_secs(30); +/// Bound on a bulk write, which is slower than a search: the first writes +/// into a new Serverless index took 20 seconds. A write that times out is +/// sent again while the first may still be applied late. +const BULK_TIMEOUT: Duration = Duration::from_secs(60); + +/// The status OpenSearch throttles with, notably Serverless while it scales. +const THROTTLED: u16 = 429; +/// Item status when the index holds the document at a newer version. +const VERSION_CONFLICT: u64 = 409; + +/// Most bytes of documents sent in one bulk request. A batch over it goes +/// out as several requests: OpenSearch refuses a request above its +/// `http.max_content_length` (10 MiB on the smallest AWS domains) with HTTP +/// 413, and a refused request would keep its community's queue from moving. +const MAX_BULK_BYTES: usize = 8 * 1024 * 1024; +/// Bytes allowed for one item's action line, and for a whole delete. +const BULK_ITEM_OVERHEAD: usize = 256; + +/// What a bulk write did, item by item. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct BulkOutcome { + /// Events whose item failed: their outbox rows stay queued. + pub failed: Vec<[u8; 32]>, + /// How many of those OpenSearch refused for good (HTTP 400 or 413): + /// retrying them fails the same way until the document or mapping + /// changes. + pub rejected: usize, + /// How many of those the index already held at this version or a newer + /// one (HTTP 409). A request applied after its batch ended has no one + /// reading its response, and a live batch holds its events' partitions, + /// so it is their newest writer: its conflict means the version source + /// went back or repeated, and its newer state must stay queued. + pub conflicts: usize, + /// Whether OpenSearch throttled the request or any item (HTTP 429). + pub throttled: bool, + /// The first failure's error type: a fixed description, never content. + pub reason: Option, +} /// OpenSearch's default `index.max_result_window`: `from + size` beyond it is /// rejected, so pages past it are empty. @@ -106,10 +148,31 @@ impl SearchIndex { } /// Create the versioned index behind the alias unless the alias exists. - pub async fn ensure(&self) -> Result<(), SearchError> { - if self.alias_exists().await? { - return Ok(()); + /// Returns whether this call created it. For tests and tools: the + /// indexer clears the backfill progress between `missing` and `create`. + pub async fn ensure(&self) -> Result { + if !self.missing().await? { + return Ok(false); } + self.create().await + } + + /// Whether the cluster answers that neither the alias nor the versioned + /// 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? { + return Ok(false); + } + if self.exists(&self.index).await? { + return Err(SearchError::Engine("index exists without its alias".into())); + } + Ok(true) + } + + /// Create the versioned index with its alias. Returns whether this call + /// created it: false when another relay created it first. + pub(crate) async fn create(&self) -> Result { let response = self .client .indices() @@ -122,25 +185,55 @@ 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.alias_exists().await? { - return Ok(()); + if self.exists(&self.alias).await? { + return Ok(false); } return Err(SearchError::Engine("index exists without its alias".into())); } return Err(SearchError::Engine("index creation rejected".into())); } - checked(response).await.map(drop) + checked(response).await.map(|_| true) } - async fn alias_exists(&self) -> Result { + /// Whether `name`, an index or alias, exists: true on 200, false on 404, + /// an error on any other status. + async fn exists(&self, name: &str) -> Result { let response = self .client .indices() - .exists(IndicesExistsParts::Index(&[&self.alias])) + .exists(IndicesExistsParts::Index(&[name])) .send() .await .map_err(transport_error)?; - Ok(response.status_code().is_success()) + match response.status_code().as_u16() { + 200 => Ok(true), + 404 => Ok(false), + status => Err(SearchError::Engine(format!("HTTP {status}"))), + } + } + + /// 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 { + let response = self + .client + .indices() + .get_settings(IndicesGetSettingsParts::IndexName( + &[&self.index], + &["index.creation_date"], + )) + .send() + .await + .map_err(transport_error)?; + let body = checked(response).await?; + let created = body[self.index.as_str()]["settings"]["index"]["creation_date"] + .as_str() + .and_then(|millis| millis.parse().ok()) + .ok_or_else(|| SearchError::Engine("index creation date missing".into()))?; + let created = std::time::UNIX_EPOCH + Duration::from_millis(created); + Ok(std::time::SystemTime::now() + .duration_since(created) + .unwrap_or_default()) } /// Delete the versioned index. For tests and tools. @@ -171,19 +264,92 @@ impl SearchIndex { checked(response).await.map(drop) } - /// Upsert `documents` and delete `removed` for one community, in one - /// bulk request through the alias. Fails unless every item succeeded; - /// deleting a document that is not there succeeds. The request requires + /// Upsert `documents` and delete `removed` for one community through the + /// alias, and report each item's result. A batch of more than + /// [`MAX_BULK_BYTES`] goes out as several bulk requests, one after the + /// other; once one is throttled or fails the rest are not sent and count + /// as failed. After the first, a failed request's items count as failed + /// and a refused one's as rejected, so the items of the requests already + /// applied still count as written. + /// Deleting a document that is not there succeeds. The request requires /// the alias, so a missing index fails the write instead of being created /// with a dynamic mapping. + /// + /// Every item carries `version` as an external version, so the cluster + /// keeps the newest state of each document: a request it applies after + /// its writer gave up cannot undo a later write. An item the index + /// already holds at this version or a newer one fails as a conflict. + /// + /// A throttled request (HTTP 429) comes back as an outcome in which every + /// item failed; any other failed first request is an error. pub async fn write( &self, community: CommunityId, documents: &[SearchDocument], removed: &[[u8; 32]], - ) -> Result<(), SearchError> { + version: i64, + ) -> Result { + let sizes = documents + .iter() + .map(|document| document_bytes(community, document)) + .chain(removed.iter().map(|_| BULK_ITEM_OVERHEAD)); + let mut outcome = BulkOutcome::default(); + let mut stopped = false; + for range in request_ranges(sizes, MAX_BULK_BYTES) { + let (documents, removed) = split_items(documents, removed, &range); + if outcome.throttled || stopped { + // Not sent: the cluster asked for less, or is failing. + outcome + .failed + .extend(documents.iter().map(|document| document.event_id)); + outcome.failed.extend(removed); + continue; + } + let part = match self + .write_request(community, documents, removed, version) + .await + { + Ok(part) => part, + // Earlier requests were applied: report this one's items as + // failed, so the rows of the applied ones are completed. + Err(error) if range.start > 0 => { + let refused = matches!(error, SearchError::Rejected(_)); + stopped = !refused; + let failed: Vec<[u8; 32]> = documents + .iter() + .map(|document| document.event_id) + .chain(removed.iter().copied()) + .collect(); + BulkOutcome { + rejected: if refused { failed.len() } else { 0 }, + failed, + reason: Some(error.kind()), + ..BulkOutcome::default() + } + } + Err(error) => return Err(error), + }; + outcome.failed.extend(part.failed); + outcome.rejected += part.rejected; + outcome.conflicts += part.conflicts; + outcome.throttled = part.throttled; + if outcome.reason.is_none() { + outcome.reason = part.reason; + } + } + Ok(outcome) + } + + /// One bulk request of [`SearchIndex::write`]. + async fn write_request( + &self, + community: CommunityId, + documents: &[SearchDocument], + removed: &[[u8; 32]], + version: i64, + ) -> Result { if documents.is_empty() && removed.is_empty() { - return Ok(()); + return Ok(BulkOutcome::default()); } let index = &self.alias; let mut operations: Vec> = @@ -193,6 +359,8 @@ impl SearchIndex { BulkOperation::index(document_source(community, document)) .id(document_id(community, &document.event_id)) .index(index) + .version(version) + .version_type(VersionType::External) .into(), ); } @@ -200,44 +368,72 @@ impl SearchIndex { operations.push( BulkOperation::delete(document_id(community, event_id)) .index(index) + .version(version) + .version_type(VersionType::External) .into(), ); } + // Items come back in request order. + let events: Vec<[u8; 32]> = documents + .iter() + .map(|document| document.event_id) + .chain(removed.iter().copied()) + .collect(); let response = self .client .bulk(BulkParts::None) .require_alias(true) + .request_timeout(BULK_TIMEOUT) .body(operations) .send() .await .map_err(transport_error)?; + if response.status_code().as_u16() == THROTTLED { + return Ok(BulkOutcome { + failed: events, + rejected: 0, + conflicts: 0, + throttled: true, + reason: Some(format!("HTTP {THROTTLED}")), + }); + } let body = checked(response).await?; if body["errors"] != true { - return Ok(()); + return Ok(BulkOutcome::default()); } - let failed = body["items"] - .as_array() - .into_iter() - .flatten() - .filter_map(|item| item.as_object()?.values().next()) - .filter(|result| result.get("error").is_some()) - .collect::>(); - let reason = failed - .first() - .and_then(|result| result["error"]["type"].as_str()) - .unwrap_or("unknown"); - let description = format!("{} bulk items failed ({reason})", failed.len()); - // Only a batch whose every failure is the documents' own fault is - // rejected; anything else may succeed on a retry. - let rejected = !failed.is_empty() - && failed - .iter() - .all(|result| result["status"].as_u64().is_some_and(rejects)); - Err(if rejected { - SearchError::Rejected(description) - } else { - SearchError::Engine(description) - }) + let items = body["items"].as_array().map(Vec::as_slice).unwrap_or(&[]); + if items.len() != events.len() { + return Err(SearchError::Engine( + "bulk response items do not match the request".into(), + )); + } + let mut outcome = BulkOutcome::default(); + for (event, item) in events.into_iter().zip(items) { + let Some(result) = item.as_object().and_then(|item| item.values().next()) else { + return Err(SearchError::Engine("malformed bulk response item".into())); + }; + if result.get("error").is_none() { + continue; + } + let status = result["status"].as_u64().unwrap_or(0); + if status == VERSION_CONFLICT { + outcome.conflicts += 1; + } + outcome.throttled |= status == u64::from(THROTTLED); + if rejects(status) { + outcome.rejected += 1; + } + if outcome.reason.is_none() { + outcome.reason = Some( + result["error"]["type"] + .as_str() + .unwrap_or("unknown") + .to_string(), + ); + } + outcome.failed.push(event); + } + Ok(outcome) } /// Run a message search against the alias. @@ -313,6 +509,44 @@ fn document_id(community: CommunityId, event_id: &[u8; 32]) -> String { format!("{}:{}", community.as_uuid(), hex::encode(event_id)) } +/// The bytes `document` takes in a bulk request. +fn document_bytes(community: CommunityId, document: &SearchDocument) -> usize { + BULK_ITEM_OVERHEAD + + serde_json::to_vec(&document_source(community, document)).map_or(0, |source| source.len()) +} + +/// Split items of the given sizes, in order, into runs of at most `limit` +/// bytes each. An item over the limit gets a run of its own. +fn request_ranges(sizes: impl Iterator, limit: usize) -> Vec> { + let mut ranges = Vec::new(); + let (mut start, mut end, mut bytes) = (0, 0, 0usize); + for size in sizes { + if end > start && bytes + size > limit { + ranges.push(start..end); + (start, bytes) = (end, 0); + } + bytes += size; + end += 1; + } + if end > start { + ranges.push(start..end); + } + ranges +} + +/// The part of a batch, counted documents first, that `range` covers. +fn split_items<'a>( + documents: &'a [SearchDocument], + removed: &'a [[u8; 32]], + range: &Range, +) -> (&'a [SearchDocument], &'a [[u8; 32]]) { + let count = documents.len(); + ( + &documents[range.start.min(count)..range.end.min(count)], + &removed[range.start.saturating_sub(count)..range.end.saturating_sub(count)], + ) +} + fn document_source(community: CommunityId, document: &SearchDocument) -> Value { json!({ "community": community.as_uuid().to_string(), @@ -441,3 +675,87 @@ fn transport_error(error: opensearch::Error) -> SearchError { SearchError::Engine("request failed".into()) } } + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::Arc; + + fn large_document(byte: u8) -> SearchDocument { + SearchDocument { + event_id: [byte; 32], + kind: 9, + pubkey: [0; 32], + channel_id: None, + created_at: chrono::DateTime::from_timestamp(0, 0).expect("epoch"), + content: "x".repeat(MAX_BULK_BYTES * 5 / 8), + channel_type: None, + author_is_agent: false, + thread_root: None, + mentions: Vec::new(), + } + } + + /// When a batch goes out as several requests and a later one fails, the + /// items the cluster already applied are reported as written, so their + /// rows are completed instead of being sent again forever. + #[tokio::test] + async fn a_failed_later_request_keeps_the_items_already_applied() { + let requests = Arc::new(AtomicUsize::new(0)); + let app = axum::Router::new() + .fallback({ + let requests = Arc::clone(&requests); + move |_body: axum::body::Bytes| async move { + match requests.fetch_add(1, Ordering::SeqCst) { + 0 => ( + axum::http::StatusCode::OK, + json!({ "errors": false, "items": [] }).to_string(), + ), + _ => ( + axum::http::StatusCode::INTERNAL_SERVER_ERROR, + "{}".to_string(), + ), + } + } + }) + .layer(axum::extract::DefaultBodyLimit::disable()); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("bind"); + let url = format!("http://{}", listener.local_addr().expect("address")); + let server = tokio::spawn(async move { axum::serve(listener, app).await }); + let index = SearchIndex::new(&OpenSearchConfig { + url, + basic_auth: None, + index_prefix: DEFAULT_INDEX_PREFIX.into(), + }) + .expect("client"); + let documents = [large_document(1), large_document(2), large_document(3)]; + + let outcome = index + .write( + CommunityId::from_uuid(uuid::Uuid::nil()), + &documents, + &[], + 1, + ) + .await + .expect("the first request was applied"); + server.abort(); + + // Mutation: propagate a later request's error → RED. + assert_eq!(outcome.failed, [[2; 32], [3; 32]]); + assert_eq!(outcome.rejected, 0); + assert_eq!(requests.load(Ordering::SeqCst), 2, "the rest is not sent"); + } + + #[test] + fn a_batch_over_the_request_limit_is_split_in_order() { + // Mutation: never start a new run → RED. + assert_eq!( + request_ranges([4, 4, 4, 9, 1].into_iter(), 8), + [0..2, 2..3, 3..4, 4..5] + ); + } +} diff --git a/crates/buzz-search/tests/postgres_opensearch_consistency.rs b/crates/buzz-search/tests/postgres_opensearch_consistency.rs new file mode 100644 index 0000000000..eebab78816 --- /dev/null +++ b/crates/buzz-search/tests/postgres_opensearch_consistency.rs @@ -0,0 +1,1555 @@ +//! Randomized consistency of the OpenSearch index under interleaving. +//! +//! Each seed writes a random mix of messages, edits, deletions and account +//! deletions while indexers drain and backfill, a proxy injects cluster +//! faults, and the driver crashes indexers mid-batch. After everything +//! drains, the index must hold exactly one document, with its current text, +//! for every searchable message Postgres holds, and nothing else. +//! +//! The seed fixes the plan, not the thread interleaving, so a failing seed +//! may need a few runs to reproduce. Every run clears and checks the whole +//! outbox, so it runs only through `scripts/postgres-test-run.sh`, which +//! gives it a database of its own. Settings: +//! +//! - `BUZZ_TEST_CONSISTENCY_SEEDS`: a seed (`7`) or an inclusive range +//! (`1-300`); default `1-3`; +//! - `BUZZ_TEST_CONSISTENCY_OPS`: operations per writer; default 20; +//! - `BUZZ_TEST_CONSISTENCY_LATE_APPLY=1`: a request stalled when its +//! indexer crashes reaches the cluster after a newer write; +//! - `BUZZ_TEST_CONSISTENCY_SEQUENCE_BACK=1`: the version sequence is set +//! back now and then, as promoting a lagging replica would. + +#[allow(unused_macros, unused_imports)] +mod search_suite; + +use std::collections::{BTreeMap, BTreeSet}; +use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +use buzz_core::CommunityId; +use buzz_db::channel::{ChannelType, ChannelVisibility}; +use buzz_db::event::ThreadMetadataParams; +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; +use buzz_search::opensearch::{OpenSearchConfig, SearchIndex}; +use nostr::{Event, EventBuilder, Keys, Kind, Tag, Timestamp}; +use rand::rngs::StdRng; +use rand::{RngExt, SeedableRng}; +use serde_json::{json, Value}; +use uuid::Uuid; + +/// Searchable kinds written by the writers. +const KINDS: [u16; 2] = [9, 40002]; +const EDIT: u16 = 40003; + +fn opensearch_url() -> String { + std::env::var("BUZZ_TEST_OPENSEARCH_URL").unwrap_or_else(|_| "http://localhost:9200".into()) +} + +fn env_or(name: &str, default: &str) -> String { + std::env::var(name).unwrap_or_else(|_| default.into()) +} + +fn seeds() -> Vec { + let spec = env_or("BUZZ_TEST_CONSISTENCY_SEEDS", "1-3"); + match spec.split_once('-') { + Some((from, to)) => { + (from.trim().parse().expect("seed")..=to.trim().parse().expect("seed")).collect() + } + None => vec![spec.trim().parse().expect("seed")], + } +} + +// --------------------------------------------------------------------------- +// Fault proxy +// --------------------------------------------------------------------------- + +/// Fault odds for one run, in percent per bulk request. +#[derive(Debug, Clone, Copy)] +struct Faults { + throttle: u32, + item_failures: u32, + lost_response: u32, + stall: u32, + late_apply: bool, + /// Whether the driver sets the version sequence back now and then. + sequence_back: bool, +} + +struct ProxyState { + upstream: String, + client: reqwest::Client, + rng: Mutex, + faults: Mutex>, + outage_until: Mutex>, + crash: tokio::sync::watch::Sender, + /// Stalled requests not yet forwarded or dropped. + pending: AtomicUsize, + /// Requests forwarded after their client had gone. + late_applied: AtomicUsize, + /// Of those, the ones forwarded after a later request wrote one of + /// their documents. + late_after_newer: AtomicUsize, + bulks: AtomicUsize, + /// For each document id, the number of the last bulk request the + /// cluster accepted a write of it from. + written: Mutex>, + /// Bulk requests the cluster has answered, counting from 1. + answered: AtomicU64, + /// Wakes requests waiting in `written`. + write_seen: tokio::sync::Notify, +} + +struct Proxy { + url: String, + state: Arc, + server: tokio::task::JoinHandle<()>, +} + +impl Proxy { + async fn start(seed: u64) -> Self { + let (crash, _) = tokio::sync::watch::channel(0); + let state = Arc::new(ProxyState { + upstream: opensearch_url(), + client: reqwest::Client::new(), + rng: Mutex::new(StdRng::seed_from_u64(seed ^ 0x5e_ed0f_9a0c)), + faults: Mutex::new(None), + outage_until: Mutex::new(None), + crash, + pending: AtomicUsize::new(0), + late_applied: AtomicUsize::new(0), + late_after_newer: AtomicUsize::new(0), + bulks: AtomicUsize::new(0), + written: Mutex::new(BTreeMap::new()), + answered: AtomicU64::new(0), + write_seen: tokio::sync::Notify::new(), + }); + let app = axum::Router::new() + .fallback(proxy_request) + .with_state(state.clone()); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("bind proxy"); + let url = format!("http://{}", listener.local_addr().expect("proxy address")); + let server = tokio::spawn(async move { + axum::serve(listener, app).await.expect("serve proxy"); + }); + Self { url, state, server } + } + + fn index(&self, prefix: &str) -> SearchIndex { + SearchIndex::new(&OpenSearchConfig { + url: self.url.clone(), + basic_auth: None, + index_prefix: prefix.into(), + }) + .expect("proxied client") + } + + fn set_faults(&self, faults: Option) { + *self.state.faults.lock().expect("faults") = faults; + if faults.is_none() { + *self.state.outage_until.lock().expect("outage") = None; + } + } + + fn outage(&self, length: Duration) { + *self.state.outage_until.lock().expect("outage") = Some(Instant::now() + length); + } + + /// The indexer whose requests are stalled has crashed. + fn crash(&self) { + self.state.crash.send_modify(|generation| *generation += 1); + } +} + +impl Drop for Proxy { + fn drop(&mut self) { + self.server.abort(); + } +} + +fn reply(status: u16, body: Value) -> axum::response::Response { + axum::response::Response::builder() + .status(status) + .header("content-type", "application/json") + .body(axum::body::Body::from(body.to_string())) + .expect("response") +} + +async fn forward( + state: &ProxyState, + method: axum::http::Method, + path: &str, + content_type: Option, + body: axum::body::Bytes, +) -> Result<(u16, Option, axum::body::Bytes), String> { + let mut request = state + .client + .request(method, format!("{}{path}", state.upstream)) + .body(body); + if let Some(content_type) = content_type { + request = request.header("content-type", content_type); + } + let response = request.send().await.map_err(|error| error.to_string())?; + let status = response.status().as_u16(); + let content_type = response.headers().get("content-type").cloned(); + let bytes = response.bytes().await.map_err(|error| error.to_string())?; + if status == 200 + && path + .split('?') + .next() + .is_some_and(|path| path.ends_with("/_bulk")) + { + record_writes(state, &bytes); + } + Ok((status, content_type, bytes)) +} + +/// Note the documents a bulk response says the cluster wrote. +fn record_writes(state: &ProxyState, response: &[u8]) { + let Ok(response) = serde_json::from_slice::(response) else { + return; + }; + let number = state.answered.fetch_add(1, Ordering::SeqCst) + 1; + let mut written = state.written.lock().expect("written"); + for item in response["items"].as_array().into_iter().flatten() { + let Some(result) = item.as_object().and_then(|item| item.values().next()) else { + continue; + }; + let accepted = result["status"].as_u64().is_some_and(|status| status < 300); + if let (true, Some(id)) = (accepted, result["_id"].as_str()) { + written.insert(id.to_string(), number); + } + } + drop(written); + state.write_seen.notify_waiters(); +} + +/// Wait until a bulk request answered after this call writes one of `ids`, +/// for at most `bound`. Whether one did. +async fn newer_write(state: &ProxyState, ids: &[String], bound: Duration) -> bool { + let since = state.answered.load(Ordering::SeqCst); + let deadline = tokio::time::Instant::now() + bound; + loop { + let seen = state.write_seen.notified(); + tokio::pin!(seen); + seen.as_mut().enable(); + { + let written = state.written.lock().expect("written"); + if ids + .iter() + .any(|id| written.get(id).is_some_and(|number| *number > since)) + { + return true; + } + } + if tokio::time::timeout_at(deadline, seen).await.is_err() { + return false; + } + } +} + +/// The item actions of an NDJSON bulk body: each action line and, for an +/// index action, its source line. +fn bulk_items(body: &[u8]) -> Vec<(Value, Option)> { + let text = std::str::from_utf8(body).expect("utf-8 bulk body"); + let mut lines = text.lines().filter(|line| !line.trim().is_empty()); + let mut items = Vec::new(); + while let Some(action) = lines.next() { + let action: Value = serde_json::from_str(action).expect("bulk action"); + let source = if action.get("delete").is_some() { + None + } else { + Some(lines.next().expect("bulk source").to_string()) + }; + items.push((action, source)); + } + items +} + +async fn proxy_request( + axum::extract::State(state): axum::extract::State>, + request: axum::extract::Request, +) -> axum::response::Response { + let (parts, body) = request.into_parts(); + let body = axum::body::to_bytes(body, usize::MAX) + .await + .expect("request body"); + let path = parts + .uri + .path_and_query() + .map_or("/".to_string(), |path| path.as_str().to_string()); + let content_type = parts.headers.get("content-type").cloned(); + let faults = *state.faults.lock().expect("faults"); + let bulk = parts.uri.path().ends_with("/_bulk"); + let Some(faults) = faults.filter(|_| bulk) else { + return match forward(&state, parts.method, &path, content_type, body).await { + Ok((status, content_type, bytes)) => { + let mut builder = axum::response::Response::builder().status(status); + if let Some(content_type) = content_type { + builder = builder.header("content-type", content_type); + } + builder + .body(axum::body::Body::from(bytes)) + .expect("response") + } + Err(error) => reply(502, json!({ "error": error })), + }; + }; + state.bulks.fetch_add(1, Ordering::Relaxed); + if state + .outage_until + .lock() + .expect("outage") + .is_some_and(|until| Instant::now() < until) + { + return reply(503, json!({ "error": "injected outage", "status": 503 })); + } + // One draw per decision, all from the run's seeded generator. + let (roll, stall_ms, late_ms, failing) = { + let mut rng = state.rng.lock().expect("rng"); + let roll = rng.random_range(0..100u32); + let stall_ms = rng.random_range(5..400u64); + let late_ms = rng.random_range(0..1500u64); + let items = bulk_items(&body).len(); + let mut failing: Vec<(usize, u16)> = Vec::new(); + for i in 0..items { + if rng.random_bool(0.3) { + failing.push((i, [429, 500, 503, 400][rng.random_range(0..4)])); + } + } + (roll, stall_ms, late_ms, failing) + }; + let mut threshold = faults.throttle; + if roll < threshold { + return reply( + 429, + json!({ "error": { "type": "too_many_requests" }, "status": 429 }), + ); + } + threshold += faults.item_failures; + if roll < threshold && !failing.is_empty() { + return partial_failure(&state, parts.method, &path, content_type, &body, &failing).await; + } + threshold += faults.lost_response; + if roll < threshold { + // The cluster applies the request; its response never arrives. + let _ = forward(&state, parts.method, &path, content_type, body).await; + return reply(502, json!({ "error": "injected lost response" })); + } + threshold += faults.stall; + if roll < threshold { + return stall( + state, + parts.method, + path, + content_type, + body, + stall_ms, + late_ms, + faults.late_apply, + ) + .await; + } + match forward(&state, parts.method, &path, content_type, body).await { + Ok((status, content_type, bytes)) => { + let mut builder = axum::response::Response::builder().status(status); + if let Some(content_type) = content_type { + builder = builder.header("content-type", content_type); + } + builder + .body(axum::body::Body::from(bytes)) + .expect("response") + } + Err(error) => reply(502, json!({ "error": error })), + } +} + +/// Forward all but the `failing` items and answer as the cluster would had +/// those items failed with their statuses. +async fn partial_failure( + state: &ProxyState, + method: axum::http::Method, + path: &str, + content_type: Option, + body: &[u8], + failing: &[(usize, u16)], +) -> axum::response::Response { + let items = bulk_items(body); + let failed: BTreeMap = failing.iter().copied().collect(); + let mut kept = String::new(); + for (i, (action, source)) in items.iter().enumerate() { + if failed.contains_key(&i) { + continue; + } + kept.push_str(&action.to_string()); + kept.push('\n'); + if let Some(source) = source { + kept.push_str(source); + kept.push('\n'); + } + } + let mut upstream_items = Vec::new(); + if !kept.is_empty() { + match forward(state, method, path, content_type, kept.into()).await { + Ok((200, _, bytes)) => { + let body: Value = serde_json::from_slice(&bytes).expect("bulk response"); + upstream_items = body["items"].as_array().cloned().unwrap_or_default(); + } + Ok((status, _, bytes)) => { + return reply( + status, + serde_json::from_slice(&bytes).unwrap_or(json!({ "status": status })), + ) + } + Err(error) => return reply(502, json!({ "error": error })), + } + } + let mut upstream_items = upstream_items.into_iter(); + let mut answer = Vec::with_capacity(items.len()); + for (i, (action, _)) in items.iter().enumerate() { + let op = if action.get("delete").is_some() { + "delete" + } else { + "index" + }; + match failed.get(&i) { + Some(status) => answer.push(json!({ op: { + "_id": action[op]["_id"], + "status": status, + "error": { "type": "injected_item_failure", "reason": "injected" } + }})), + None => answer.push(upstream_items.next().expect("upstream item")), + } + } + reply(200, json!({ "took": 1, "errors": true, "items": answer })) +} + +/// Hold the request for `stall_ms`, then forward it. If its indexer +/// crashes meanwhile, the client gets an error and the request reaches the +/// cluster only with `late_apply`, otherwise never: once a later request +/// has written one of its documents, or after `late_ms`. A detached task +/// owns the request, so it outlives a client that hangs up. +#[allow(clippy::too_many_arguments)] +async fn stall( + state: Arc, + method: axum::http::Method, + path: String, + content_type: Option, + body: axum::body::Bytes, + stall_ms: u64, + late_ms: u64, + late_apply: bool, +) -> axum::response::Response { + let (respond, response) = tokio::sync::oneshot::channel(); + let mut crashed = state.crash.subscribe(); + state.pending.fetch_add(1, Ordering::SeqCst); + let owner = state.clone(); + tokio::spawn(async move { + let state = owner; + let orphaned = tokio::select! { + _ = tokio::time::sleep(Duration::from_millis(stall_ms)) => false, + _ = crashed.changed() => true, + }; + if orphaned || respond.is_closed() { + let _ = respond.send(reply(502, json!({ "error": "injected crash" }))); + if late_apply { + let ids: Vec = bulk_items(&body) + .iter() + .filter_map(|(action, _)| { + ["index", "delete"] + .iter() + .find_map(|op| action[*op]["_id"].as_str()) + .map(str::to_string) + }) + .collect(); + let after_newer = newer_write(&state, &ids, Duration::from_millis(late_ms)).await; + let _ = forward(&state, method, &path, content_type, body).await; + state.late_applied.fetch_add(1, Ordering::SeqCst); + if after_newer { + state.late_after_newer.fetch_add(1, Ordering::SeqCst); + } + } + } else { + let response = match forward(&state, method, &path, content_type, body).await { + Ok((status, _, bytes)) => reply( + status, + serde_json::from_slice(&bytes).unwrap_or(json!({ "status": status })), + ), + Err(error) => reply(502, json!({ "error": error })), + }; + let _ = respond.send(response); + } + state.pending.fetch_sub(1, Ordering::SeqCst); + }); + response + .await + .unwrap_or_else(|_| reply(502, json!({ "error": "stalled request dropped" }))) +} + +// --------------------------------------------------------------------------- +// Model of what was written +// --------------------------------------------------------------------------- + +#[derive(Debug, Clone)] +struct Edit { + event: Event, + token: String, + deleted: bool, +} + +#[derive(Debug, Clone)] +struct Message { + community: usize, + channel: Uuid, + event: Event, + author: usize, + token: String, + parent: Option<[u8; 32]>, + root: Option<[u8; 32]>, + mentions: Vec, + edits: Vec, + deleted: bool, +} + +impl Message { + fn id(&self) -> [u8; 32] { + *self.event.id.as_bytes() + } + + /// The token of the text search should match: the latest live edit's, + /// or the message's own. + fn current_token(&self) -> &str { + self.edits + .iter() + .filter(|edit| !edit.deleted) + .max_by_key(|edit| (edit.event.created_at, edit.event.id)) + .map_or(&self.token, |edit| &edit.token) + } + + fn tokens(&self) -> impl Iterator { + std::iter::once(self.token.as_str()) + .chain(self.edits.iter().map(|edit| edit.token.as_str())) + } +} + +struct Author { + keys: Keys, + community: usize, +} + +struct World { + run: u64, + communities: Vec, + channels: Vec>, + authors: Vec, + messages: Mutex>, + /// Signing time of the next event, one second apart, so edits order. + clock: AtomicI64, + tokens: AtomicI64, +} + +impl World { + fn tick(&self) -> Timestamp { + Timestamp::from(self.clock.fetch_add(1, Ordering::SeqCst) as u64) + } + + fn token(&self) -> String { + format!( + "zq{}t{}", + self.run, + self.tokens.fetch_add(1, Ordering::SeqCst) + ) + } +} + +fn signed_at(event: &Event) -> chrono::DateTime { + chrono::DateTime::from_timestamp(event.created_at.as_secs() as i64, 0).expect("timestamp") +} + +fn sign(keys: &Keys, kind: u16, content: &str, tags: Vec>, at: Timestamp) -> Event { + EventBuilder::new(Kind::Custom(kind), content) + .tags(tags.into_iter().map(|tag| Tag::parse(tag).expect("tag"))) + .custom_created_at(at) + .sign_with_keys(keys) + .expect("sign") +} + +/// Write a new message or reply by `author`; returns it once stored, or +/// `None` when a reply is refused because its parent was erased meanwhile. +async fn write_message( + db: &Db, + world: &World, + rng: &mut StdRng, + author: usize, + parent: Option, +) -> Option { + let community = world.authors[author].community; + let keys = &world.authors[author].keys; + let channel = match &parent { + Some(parent) => parent.channel, + None => world.channels[community][rng.random_range(0..world.channels[community].len())], + }; + let token = world.token(); + let kind = KINDS[rng.random_range(0..KINDS.len())]; + let mut tags = vec![vec!["h".to_string(), channel.to_string()]]; + let mut mentions = Vec::new(); + if rng.random_bool(0.3) { + let others: Vec<&Author> = world + .authors + .iter() + .enumerate() + .filter(|(i, other)| other.community == community && *i != author) + .map(|(_, other)| other) + .collect(); + let mentioned = others[rng.random_range(0..others.len())] + .keys + .public_key() + .to_hex(); + tags.push(vec!["p".into(), mentioned.clone()]); + mentions.push(mentioned); + } + let root = parent + .as_ref() + .map(|parent| parent.root.unwrap_or(parent.id())); + if let Some(parent) = &parent { + let root_hex = hex::encode(root.expect("root")); + tags.push(vec!["e".into(), root_hex, String::new(), "root".into()]); + tags.push(vec![ + "e".into(), + parent.event.id.to_hex(), + String::new(), + "reply".into(), + ]); + } + let event = sign(keys, kind, &format!("{token} chatter"), tags, world.tick()); + let community_id = world.communities[community]; + match &parent { + None => { + db.insert_event(community_id, &event, Some(channel)) + .await + .expect("insert message"); + } + Some(parent) => { + let messages = world.messages.lock().expect("model").clone(); + let created = |id: [u8; 32]| { + messages + .iter() + .find(|message| message.id() == id) + .map(|message| signed_at(&message.event)) + .expect("known message") + }; + let root = root.expect("root"); + let stored = db + .insert_event_with_thread_metadata( + community_id, + &event, + Some(channel), + Some(ThreadMetadataParams { + event_id: event.id.as_bytes(), + event_created_at: signed_at(&event), + channel_id: channel, + parent_event_id: Some(parent.event.id.as_bytes()), + parent_event_created_at: Some(signed_at(&parent.event)), + root_event_id: Some(&root), + root_event_created_at: Some(created(root)), + depth: if parent.root.is_some() { 2 } else { 1 }, + broadcast: false, + }), + ) + .await; + match stored { + Ok(_) => {} + Err(buzz_db::DbError::InvalidData(reason)) + if reason.contains("parent disappeared") => + { + return None + } + Err(error) => panic!("insert reply: {error}"), + } + } + } + mentions.sort(); + Some(Message { + community, + channel, + event, + author, + token, + parent: parent.as_ref().map(Message::id), + root, + mentions, + edits: Vec::new(), + deleted: false, + }) +} + +#[allow(clippy::too_many_arguments)] +async fn delete_event( + db: &Db, + world: &World, + author: usize, + community: usize, + channel: Uuid, + target: &Event, + parent: Option<[u8; 32]>, + root: Option<[u8; 32]>, +) { + let keys = &world.authors[author].keys; + let deletion = sign( + keys, + 5, + "", + vec![ + vec!["h".into(), channel.to_string()], + vec!["e".into(), target.id.to_hex()], + ], + world.tick(), + ); + db.insert_deletion_event( + world.communities[community], + &deletion, + Some(channel), + None, + &[DeletionTarget { + event_id: target.id.as_bytes(), + created_at: signed_at(target), + parent_event_id: parent.as_ref().map(|id| id.as_slice()), + root_event_id: root.as_ref().map(|id| id.as_slice()), + }], + &Keys::generate(), + ) + .await + .expect("insert deletion"); +} + +/// Delete every message of `author`'s account, rerunning while concurrent +/// replies make a batch roll back, as the product asks. +async fn delete_account(db: &Db, world: &World, author: usize) { + let community = world.authors[author].community; + let options = ContentBatchOptions { + community: *world.communities[community].as_uuid(), + pubkey: world.authors[author].keys.public_key().to_hex(), + relay_pubkey: None, + batch_size: 7, + max_items: 100_000, + }; + let mut last = None; + for _ in 0..100 { + match db + .user_deletion_store() + .run_message_batches(&options, ExecutionMode::Delete, None, &mut Vec::new()) + .await + { + Ok(_) => return, + Err(error) => { + last = Some(error.to_string()); + tokio::time::sleep(Duration::from_millis(5)).await; + } + } + } + panic!("account deletion never completed: {last:?}"); +} + +/// One writer: owns `author`, so the model of its messages is exact. +async fn writer(db: Db, world: Arc, author: usize, seed: u64, ops: usize) { + let mut rng = StdRng::seed_from_u64(seed); + let community = world.authors[author].community; + for _ in 0..ops { + tokio::time::sleep(Duration::from_millis(rng.random_range(0..8))).await; + let roll = rng.random_range(0..100u32); + let snapshot = world.messages.lock().expect("model").clone(); + let own_live: Vec = snapshot + .iter() + .enumerate() + .filter(|(_, message)| message.author == author && !message.deleted) + .map(|(i, _)| i) + .collect(); + let peers: Vec<&Message> = snapshot + .iter() + .filter(|message| message.community == community && !message.deleted) + .collect(); + if roll < 40 || own_live.is_empty() { + let message = write_message(&db, &world, &mut rng, author, None).await; + world.messages.lock().expect("model").extend(message); + } else if roll < 55 && !peers.is_empty() { + let parent = peers[rng.random_range(0..peers.len())].clone(); + let message = write_message(&db, &world, &mut rng, author, Some(parent)).await; + world.messages.lock().expect("model").extend(message); + } else if roll < 78 { + let target = own_live[rng.random_range(0..own_live.len())]; + let message = &snapshot[target]; + let token = world.token(); + let edit = sign( + &world.authors[author].keys, + EDIT, + &format!("{token} edited"), + vec![ + vec!["h".into(), message.channel.to_string()], + vec!["e".into(), message.event.id.to_hex()], + ], + world.tick(), + ); + db.insert_event(world.communities[community], &edit, Some(message.channel)) + .await + .expect("insert edit"); + world.messages.lock().expect("model")[target] + .edits + .push(Edit { + event: edit, + token, + deleted: false, + }); + } else if roll < 90 { + let target = own_live[rng.random_range(0..own_live.len())]; + let message = &snapshot[target]; + delete_event( + &db, + &world, + author, + community, + message.channel, + &message.event, + message.parent, + message.root, + ) + .await; + world.messages.lock().expect("model")[target].deleted = true; + } else if roll < 96 { + let edits: Vec<(usize, usize)> = own_live + .iter() + .flat_map(|&m| { + snapshot[m] + .edits + .iter() + .enumerate() + .filter(|(_, edit)| !edit.deleted) + .map(move |(e, _)| (m, e)) + }) + .collect(); + if let Some(&(m, e)) = edits.get(rng.random_range(0..edits.len().max(1))) { + let message = &snapshot[m]; + delete_event( + &db, + &world, + author, + community, + message.channel, + &message.edits[e].event, + None, + None, + ) + .await; + world.messages.lock().expect("model")[m].edits[e].deleted = true; + } + } else { + delete_account(&db, &world, author).await; + let mut messages = world.messages.lock().expect("model"); + for message in messages + .iter_mut() + .filter(|message| message.author == author) + { + message.deleted = true; + for edit in &mut message.edits { + edit.deleted = true; + } + } + } + } +} + +// --------------------------------------------------------------------------- +// The run +// --------------------------------------------------------------------------- + +async fn connect() -> Db { + // A run clears the whole outbox and completes every backfill, so it never + // falls back to the development database. + let database_url = std::env::var("BUZZ_TEST_DATABASE_URL") + .expect("Postgres wrapper must provide an isolated database URL"); + assert_eq!( + std::env::var("BUZZ_TEST_SCHEMA_MODE").as_deref(), + Ok("desired"), + "run through scripts/postgres-test-run.sh, which gives each test a database of its own" + ); + let (pool, _) = search_suite::setup().await; + pool.close().await; + let db = Db::new(&DbConfig { + database_url, + max_connections: 48, + ..DbConfig::default() + }) + .await + .expect("connect database layer"); + search_outbox::enable(db.pool()) + .await + .expect("enable outbox"); + db +} + +/// Leave nothing of an earlier, failed run for this one to index. +async fn reset(db: &Db) { + sqlx::query("DELETE FROM search_outbox") + .execute(db.pool()) + .await + .expect("clear outbox"); + sqlx::query( + "INSERT INTO search_backfill (community_id, enqueued, completed_at) \ + SELECT id, 0, now() FROM communities \ + ON CONFLICT (community_id) DO UPDATE SET completed_at = now()", + ) + .execute(db.pool()) + .await + .expect("complete earlier backfills"); +} + +async fn setup_world(db: &Db, rng: &mut StdRng, seed: u64) -> World { + let mut communities = Vec::new(); + let mut channels = Vec::new(); + let mut authors = Vec::new(); + let community_count = rng.random_range(2..4usize); + for c in 0..community_count { + let community = search_suite::mk_community( + db.pool(), + &format!("c{c}-{}.consistency.example", Uuid::new_v4().simple()), + ) + .await; + let author_count = rng.random_range(2..4usize); + let mut community_authors = Vec::new(); + for _ in 0..author_count { + let keys = Keys::generate(); + db.ensure_user(community, keys.public_key().as_bytes()) + .await + .expect("ensure user"); + community_authors.push(keys); + } + // One author is an agent, so author_is_agent is checked both ways. + // Its owner never writes: deleting the owner's account deletes the + // agent's messages too, concurrently with the agent's own writer. + let owner = Keys::generate(); + db.ensure_user(community, owner.public_key().as_bytes()) + .await + .expect("ensure owner"); + db.set_agent_owner( + community, + community_authors[0].public_key().as_bytes(), + owner.public_key().as_bytes(), + ) + .await + .expect("agent owner"); + let mut community_channels = Vec::new(); + for _ in 0..rng.random_range(1..3usize) { + community_channels.push( + db.create_channel( + community, + &format!("ch-{}", Uuid::new_v4().simple()), + ChannelType::Stream, + ChannelVisibility::Open, + None, + community_authors[0].public_key().as_bytes(), + None, + ) + .await + .expect("create channel") + .id, + ); + } + communities.push(community); + channels.push(community_channels); + authors.extend( + community_authors + .into_iter() + .map(|keys| Author { keys, community: c }), + ); + } + World { + run: seed, + communities, + channels, + authors, + messages: Mutex::new(Vec::new()), + clock: AtomicI64::new(Timestamp::now().as_secs() as i64 - 300), + tokens: AtomicI64::new(0), + } +} + +/// Messages stored before the index existed: written, edited and deleted, +/// then their outbox rows dropped, so only the backfill can index them. +async fn stored_history(db: &Db, world: &World, rng: &mut StdRng) { + for author in 0..world.authors.len() { + for _ in 0..rng.random_range(0..12usize) { + let message = write_message(db, world, rng, author, None).await; + world.messages.lock().expect("model").extend(message); + } + } + let snapshot = world.messages.lock().expect("model").clone(); + for (i, message) in snapshot.iter().enumerate() { + if rng.random_bool(0.2) { + let token = world.token(); + let edit = sign( + &world.authors[message.author].keys, + EDIT, + &format!("{token} edited"), + vec![ + vec!["h".into(), message.channel.to_string()], + vec!["e".into(), message.event.id.to_hex()], + ], + world.tick(), + ); + db.insert_event( + world.communities[message.community], + &edit, + Some(message.channel), + ) + .await + .expect("insert edit"); + world.messages.lock().expect("model")[i].edits.push(Edit { + event: edit, + token, + deleted: false, + }); + } else if rng.random_bool(0.1) { + delete_event( + db, + world, + message.author, + message.community, + message.channel, + &message.event, + None, + None, + ) + .await; + world.messages.lock().expect("model")[i].deleted = true; + } + } + sqlx::query("DELETE FROM search_outbox") + .execute(db.pool()) + .await + .expect("forget the history's rows"); +} + +#[derive(Debug, Clone, Copy)] +struct Plan { + workers: usize, + other_workers: usize, + batch: i64, + faults: Faults, +} + +fn plan(seed: u64, rng: &mut StdRng) -> Plan { + let workers = [1, 4, 8][(seed % 3) as usize]; + Plan { + workers, + other_workers: [1, 4, 8][rng.random_range(0..3)], + batch: rng.random_range(1..12), + faults: Faults { + throttle: rng.random_range(0..10), + item_failures: rng.random_range(0..25), + lost_response: rng.random_range(0..8), + stall: rng.random_range(0..20), + late_apply: env_or("BUZZ_TEST_CONSISTENCY_LATE_APPLY", "0") == "1", + sequence_back: env_or("BUZZ_TEST_CONSISTENCY_SEQUENCE_BACK", "0") == "1", + }, + } +} + +/// Run `indexer`'s drain, giving up after a bound so nothing hangs. +async fn bounded_drain(indexer: &Indexer) { + let _ = tokio::time::timeout(Duration::from_secs(40), indexer.drain()).await; +} + +/// Index concurrently with the writers until `done`, injecting crashes, +/// overlapping indexers, outages and, with `sequence_back`, sequence +/// rewinds. +async fn driver( + db: Db, + first: Indexer, + second: Indexer, + proxy: Arc, + done: Arc, + seed: u64, + sequence_back: bool, +) -> (usize, usize, usize, usize) { + let mut rng = StdRng::seed_from_u64(seed ^ 0xd21_7e5); + let (mut crashes, mut overlaps, mut outages, mut rewinds) = (0, 0, 0, 0); + while !done.load(Ordering::SeqCst) { + if sequence_back && rng.random_bool(0.15) { + // A failover to a replica that had not seen the last values: + // the sequence hands some of them out again. + sqlx::query( + "SELECT setval('search_index_version', \ + greatest(last_value - $1, 1)) FROM search_index_version", + ) + .bind(rng.random_range(1..=50i64)) + .execute(db.pool()) + .await + .expect("set the version sequence back"); + rewinds += 1; + } + match rng.random_range(0..100u32) { + 0..=44 => bounded_drain(&first).await, + 45..=69 => { + // Crash mid-batch: the claimed rows roll back. + let indexer = first.clone(); + let task = tokio::spawn(async move { indexer.drain().await }); + tokio::time::sleep(Duration::from_millis(rng.random_range(0..60))).await; + task.abort(); + let _ = task.await; + proxy.crash(); + crashes += 1; + } + 70..=89 => { + // A lease handover: the old holder's pass is still running + // when the new one starts. + let (a, b) = (first.clone(), second.clone()); + let backfill = second.clone(); + let _ = tokio::join!(bounded_drain(&a), bounded_drain(&b), async { + let _ = backfill.backfill().await; + }); + overlaps += 1; + } + _ => { + proxy.outage(Duration::from_millis(rng.random_range(50..600))); + outages += 1; + } + } + tokio::time::sleep(Duration::from_millis(rng.random_range(0..20))).await; + } + (crashes, overlaps, outages, rewinds) +} + +/// What one community's document should hold, read from Postgres. +#[derive(Debug, Clone, PartialEq)] +struct Expected { + kind: i64, + author: String, + channel: Option, + channel_type: Option, + author_is_agent: bool, + thread_root: Option, + mentions: Vec, + created_at: i64, + content: String, +} + +/// id, kind, pubkey, channel, created_at, channel type, agent, thread root, +/// mentions, content. +type ExpectedRow = ( + Vec, + i32, + Vec, + Option, + i64, + Option, + bool, + Option>, + Vec, + String, +); +/// id, created_at, channel, tags, content of a live edit. +type EditRow = (Vec, i64, Option, Value, String); +/// created_at, id, content of the latest live edit of a message. +type LatestEdit = (i64, Vec, String); + +async fn expected_from_postgres(db: &Db, community: CommunityId) -> BTreeMap { + let rows: Vec = sqlx::query_as( + "SELECT e.id, e.kind, e.pubkey, e.channel_id, extract(epoch FROM e.created_at)::bigint, \ + c.channel_type::text, (u.agent_owner_pubkey IS NOT NULL), t.root_event_id, \ + ARRAY(SELECT m.pubkey_hex::text FROM event_mentions m \ + WHERE m.community_id = e.community_id AND m.event_id = e.id \ + ORDER BY 1), \ + e.content \ + FROM events e \ + LEFT JOIN channels c ON c.community_id = e.community_id AND c.id = e.channel_id \ + LEFT JOIN users u ON u.community_id = e.community_id AND u.pubkey = e.pubkey \ + LEFT JOIN thread_metadata t ON t.community_id = e.community_id \ + AND t.event_created_at = e.created_at AND t.event_id = e.id \ + WHERE e.community_id = $1 AND e.deleted_at IS NULL AND e.kind = ANY($2)", + ) + .bind(community.as_uuid()) + .bind(search_outbox::SEARCHABLE_KINDS.as_slice()) + .fetch_all(db.pool()) + .await + .expect("expected documents"); + // Live edits, applied in Rust from their first `e` tag. + let edits: Vec = sqlx::query_as( + "SELECT id, extract(epoch FROM created_at)::bigint, channel_id, tags, content FROM events \ + WHERE community_id = $1 AND kind = 40003 AND deleted_at IS NULL", + ) + .bind(community.as_uuid()) + .fetch_all(db.pool()) + .await + .expect("edits"); + let mut latest: BTreeMap<(String, Option), LatestEdit> = BTreeMap::new(); + for (id, at, channel, tags, content) in edits { + let Some(target) = tags.as_array().and_then(|tags| { + tags.iter() + .find(|tag| tag[0] == "e") + .and_then(|tag| tag[1].as_str().map(str::to_lowercase)) + }) else { + continue; + }; + let entry = + latest + .entry((target, channel)) + .or_insert((i64::MIN, Vec::new(), String::new())); + if (at, &id) > (entry.0, &entry.1) { + *entry = (at, id, content); + } + } + rows.into_iter() + .map( + |( + id, + kind, + pubkey, + channel, + created_at, + channel_type, + agent, + root, + mentions, + content, + )| { + let id = hex::encode(id); + let content = latest + .get(&(id.clone(), channel)) + .map_or(content, |(_, _, content)| content.clone()); + ( + id, + Expected { + kind: kind.into(), + author: hex::encode(pubkey), + channel: channel.map(|channel| channel.to_string()), + channel_type, + author_is_agent: agent, + thread_root: root.map(hex::encode), + mentions, + created_at, + content, + }, + ) + }, + ) + .collect() +} + +async fn upstream(method: reqwest::Method, path: &str, body: Option) -> Value { + let client = reqwest::Client::new(); + let mut request = client.request(method, format!("{}/{path}", opensearch_url())); + if let Some(body) = body { + request = request.json(&body); + } + let response = request.send().await.expect("OpenSearch request"); + response.json().await.expect("OpenSearch body") +} + +/// Check the index against Postgres and the model; returns the violations. +async fn verify(db: &Db, world: &World, prefix: &str) -> Vec { + let alias = format!("{prefix}messages"); + let mut violations = Vec::new(); + let depth = search_outbox::depth(db.pool()).await.expect("depth"); + if depth != 0 { + violations.push(format!("outbox holds {depth} rows")); + } + upstream(reqwest::Method::POST, &format!("{alias}/_refresh"), None).await; + let messages = world.messages.lock().expect("model").clone(); + let mut total_expected = 0; + for (c, community) in world.communities.iter().enumerate() { + let expected = expected_from_postgres(db, *community).await; + total_expected += expected.len(); + let model: Vec<&Message> = messages.iter().filter(|m| m.community == c).collect(); + // The model and Postgres agree on what is live and its text. + for message in &model { + let id = message.event.id.to_hex(); + match (expected.get(&id), message.deleted) { + (Some(_), true) => violations.push(format!("{id}: deleted in the model, live in Postgres")), + (None, false) => violations.push(format!("{id}: live in the model, gone from Postgres; author {} {}, parent {:?}", message.author, world.authors[message.author].keys.public_key().to_hex(), message.parent.map(hex::encode))), + (Some(row), false) if !row.content.starts_with(&format!("{} ", message.current_token())) => { + violations.push(format!( + "{id}: Postgres text {:?}, model token {}", + row.content, + message.current_token() + )) + } + (Some(row), false) + if row.mentions != message.mentions + || row.thread_root != message.root.map(hex::encode) => + { + violations.push(format!( + "{id}: Postgres fields differ from the model: {row:?}, model mentions {:?} root {:?}", + message.mentions, + message.root.map(hex::encode) + )) + } + _ => {} + } + } + // Every token ever written in the community, as a named query, so + // each hit says which texts it matches. + let tokens: Vec<&str> = model.iter().flat_map(|m| m.tokens()).collect(); + let mut hits: BTreeMap)> = BTreeMap::new(); + let mut chunks: Vec<&[&str]> = tokens.chunks(500).collect(); + if chunks.is_empty() { + chunks.push(&[]); + } + for chunk in chunks { + let should: Vec = chunk + .iter() + .map(|token| json!({ "term": { "content": { "value": token, "_name": token } } })) + .collect(); + let body = upstream( + reqwest::Method::POST, + &format!("{alias}/_search"), + Some(json!({ + "size": 10000, + "query": { "bool": { + "filter": [{ "term": { "community": community.as_uuid().to_string() } }], + "should": should + }} + })), + ) + .await; + for hit in body["hits"]["hits"].as_array().expect("hits") { + let id = hit["_id"].as_str().expect("_id").to_string(); + let entry = hits + .entry(id) + .or_insert_with(|| (hit["_source"].clone(), BTreeSet::new())); + for name in hit["matched_queries"].as_array().into_iter().flatten() { + entry.1.insert(name.as_str().expect("name").to_string()); + } + } + } + let prefix = format!("{}:", community.as_uuid()); + for (doc_id, (source, matched)) in &hits { + let Some(event) = doc_id.strip_prefix(&prefix) else { + violations.push(format!("{doc_id}: document of another community")); + continue; + }; + let Some(row) = expected.get(event) else { + violations.push(format!( + "{event}: document for a message that is not live; matches {matched:?}" + )); + continue; + }; + let want_token = row + .content + .split(' ') + .next() + .unwrap_or_default() + .to_string(); + if *matched != BTreeSet::from([want_token.clone()]) { + violations.push(format!( + "{event}: text matches {matched:?}, want {want_token}" + )); + } + let fields = json!({ + "community": community.as_uuid().to_string(), + "event_id": event, + "kind": row.kind, + "author": row.author, + "channel": row.channel, + "channel_type": row.channel_type, + "author_is_agent": row.author_is_agent, + "thread_root": row.thread_root, + "mentions": row.mentions, + "created_at": row.created_at, + }); + if *source != fields { + violations.push(format!("{event}: fields {source} want {fields}")); + } + } + for event in expected.keys() { + if !hits.contains_key(&format!("{prefix}{event}")) { + violations.push(format!("{event}: live message has no document")); + } + } + } + let count = upstream(reqwest::Method::GET, &format!("{alias}/_count"), None).await; + if count["count"].as_u64() != Some(total_expected as u64) { + violations.push(format!( + "index holds {} documents, want {total_expected}", + count["count"] + )); + } + violations +} + +struct RunReport { + messages: usize, + bulks: usize, + crashes: usize, + overlaps: usize, + outages: usize, + late_applied: usize, + late_after_newer: usize, + rewinds: usize, +} + +async fn run(db: &Db, seed: u64, ops: usize) -> Result> { + reset(db).await; + let mut rng = StdRng::seed_from_u64(seed); + let plan = plan(seed, &mut rng); + let world = Arc::new(setup_world(db, &mut rng, seed).await); + stored_history(db, &world, &mut rng).await; + + let prefix = format!("cons-{}-", Uuid::new_v4().simple()); + let direct = SearchIndex::new(&OpenSearchConfig { + url: opensearch_url(), + basic_auth: None, + index_prefix: prefix.clone(), + }) + .expect("client"); + direct.ensure().await.expect("create index"); + let proxy = Arc::new(Proxy::start(seed).await); + let indexer = |workers: usize| { + Indexer::new(db.clone(), proxy.index(&prefix)) + .with_workers(workers) + .with_batch_size(plan.batch) + .with_backfill_bound(plan.batch * 2) + }; + let (first, second) = (indexer(plan.workers), indexer(plan.other_workers)); + proxy.set_faults(Some(plan.faults)); + + let done = Arc::new(AtomicBool::new(false)); + let backfill = { + let (indexer, done) = (first.clone(), done.clone()); + let mut rng = StdRng::seed_from_u64(seed ^ 0xbac_f111); + tokio::spawn(async move { + while !done.load(Ordering::SeqCst) { + let _ = tokio::time::timeout(Duration::from_secs(20), indexer.backfill()).await; + tokio::time::sleep(Duration::from_millis(rng.random_range(0..30))).await; + } + }) + }; + let driving = tokio::spawn(driver( + db.clone(), + first.clone(), + second, + proxy.clone(), + done.clone(), + seed, + plan.faults.sequence_back, + )); + let writers: Vec<_> = (0..world.authors.len()) + .map(|author| { + tokio::spawn(writer( + db.clone(), + world.clone(), + author, + seed.wrapping_mul(1000).wrapping_add(author as u64), + ops, + )) + }) + .collect(); + for writer in writers { + writer.await.expect("writer"); + } + done.store(true, Ordering::SeqCst); + backfill.await.expect("backfill task"); + let (crashes, overlaps, outages, rewinds) = driving.await.expect("driver"); + + // Let everything drain with the faults off. A pass can still fail + // while documents hold versions the sequence handed out again; their + // rows stay queued until the sequence passes them. + proxy.set_faults(None); + let mut last_error = None; + let drained = tokio::time::timeout(Duration::from_secs(120), async { + loop { + let queued = first.backfill().await.expect("final backfill"); + if let Err(error) = first.drain().await { + last_error = Some(error.to_string()); + } + let incomplete: i64 = sqlx::query_scalar( + "SELECT count(*) FROM communities c LEFT JOIN search_backfill b ON b.community_id = c.id \ + WHERE b.completed_at IS NULL", + ) + .fetch_one(db.pool()) + .await + .expect("backfill state"); + if queued == 0 + && incomplete == 0 + && search_outbox::depth(db.pool()).await.expect("depth") == 0 + && proxy.state.pending.load(Ordering::SeqCst) == 0 + { + break; + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + }) + .await; + let mut violations = Vec::new(); + if drained.is_err() { + violations.push(format!( + "the outbox did not drain within 120 s; last drain error: {last_error:?}" + )); + } + violations.extend(verify(db, &world, &prefix).await); + let report = RunReport { + messages: world.messages.lock().expect("model").len(), + bulks: proxy.state.bulks.load(Ordering::Relaxed), + crashes, + overlaps, + outages, + late_applied: proxy.state.late_applied.load(Ordering::SeqCst), + late_after_newer: proxy.state.late_after_newer.load(Ordering::SeqCst), + rewinds, + }; + if violations.is_empty() { + direct.delete().await.expect("delete index"); + Ok(report) + } else { + violations.insert( + 0, + format!( + "seed {seed}: {plan:?}, index prefix {prefix} kept, {} messages, {} bulks, {crashes} crashes, {overlaps} overlaps, {outages} outages, {} late ({} after a newer write), {rewinds} sequence rewinds", + report.messages, report.bulks, report.late_applied, report.late_after_newer + ), + ); + Err(violations) + } +} + +/// From each seed, random writes, deletions, edits, account deletions and a +/// backfill interleave with crashing, overlapping and throttled indexers; +/// afterwards the index matches Postgres exactly. +#[tokio::test(flavor = "multi_thread", worker_threads = 8)] +#[ignore = "requires Postgres and OpenSearch, and a database of its own"] +async fn the_index_converges_on_postgres_under_interleaving() { + let db = connect().await; + let ops: usize = env_or("BUZZ_TEST_CONSISTENCY_OPS", "20") + .parse() + .expect("ops"); + let mut failures = Vec::new(); + for seed in seeds() { + let started = Instant::now(); + match tokio::time::timeout(Duration::from_secs(300), run(&db, seed, ops)).await { + Ok(Ok(report)) => eprintln!( + "seed {seed}: ok in {:?}: {} messages, {} bulks, {} crashes, {} overlaps, {} outages, {} late ({} after a newer write), {} sequence rewinds", + started.elapsed(), + report.messages, + report.bulks, + report.crashes, + report.overlaps, + report.outages, + report.late_applied, + report.late_after_newer, + report.rewinds + ), + Ok(Err(violations)) => { + eprintln!("seed {seed}: FAILED\n {}", violations.join("\n ")); + failures.push(seed); + } + Err(_) => { + eprintln!("seed {seed}: FAILED: timed out after 300 s"); + failures.push(seed); + } + } + } + assert!(failures.is_empty(), "failing seeds: {failures:?}"); +} diff --git a/crates/buzz-search/tests/postgres_opensearch_search.rs b/crates/buzz-search/tests/postgres_opensearch_search.rs index 8ae2196404..3c9e97483f 100644 --- a/crates/buzz-search/tests/postgres_opensearch_search.rs +++ b/crates/buzz-search/tests/postgres_opensearch_search.rs @@ -12,8 +12,7 @@ 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); -// - deleted_events_are_excluded: deletes reach the index in issue 04. +// - prefix_*: prefix mode is reworked with prefix analysis (issue 06). search_suite_tests! { Backend::OpenSearch; #[ignore = "requires Postgres and OpenSearch"] @@ -33,16 +32,22 @@ search_suite_tests! { fn excluded_kinds_are_storage_level_unsearchable, fn author_only_kinds_are_storage_level_unsearchable, fn p_gated_persistent_kinds_have_storage_null_tsvector, + fn deleted_events_are_excluded, } use std::time::Duration; use buzz_core::CommunityId; -use buzz_db::{search_outbox, Db, DbConfig}; -use buzz_search::indexer::Indexer; +use buzz_db::channel::{ChannelType, ChannelVisibility}; +use buzz_db::event::ThreadMetadataParams; +use buzz_db::search_outbox::SearchDocument; +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::{ChannelScope, SearchMode, SearchQuery, SearchService, SearchSort}; -use nostr::{Event, EventBuilder, Keys, Kind}; +use nostr::{Event, EventBuilder, Keys, Kind, Tag, Timestamp}; use opensearch::http::transport::Transport; use opensearch::indices::{IndicesCreateParts, IndicesExistsParts}; use opensearch::{GetParts, OpenSearch}; @@ -57,8 +62,17 @@ fn opensearch_url() -> String { /// A database layer with the search outbox on, as the relay runs it when /// OpenSearch is configured. async fn sync_db() -> Db { + let db = unsynced_db().await; + search_outbox::enable(db.pool()) + .await + .expect("enable outbox"); + db +} + +/// A database layer as a relay without OpenSearch runs it: admission queues +/// nothing. +async fn unsynced_db() -> Db { let (pool, _) = search_suite::setup().await; - search_outbox::enable(&pool).await.expect("enable outbox"); pool.close().await; Db::new(&DbConfig { database_url: std::env::var("BUZZ_TEST_DATABASE_URL") @@ -82,6 +96,16 @@ async fn sync_index() -> (SearchIndex, String) { (index, prefix) } +/// A message signed `offset` seconds from now. +fn message_at(keys: &Keys, content: &str, offset: i64) -> Event { + EventBuilder::new(Kind::Custom(9), content) + .custom_created_at(Timestamp::from( + (Timestamp::now().as_secs() as i64 + offset) as u64, + )) + .sign_with_keys(keys) + .expect("sign") +} + fn message(keys: &Keys, content: &str) -> Event { EventBuilder::new(Kind::Custom(9), content) .sign_with_keys(keys) @@ -134,7 +158,11 @@ async fn admitted_messages_become_searchable() { let (index, prefix) = sync_index().await; let community = search_suite::mk_community(db.pool(), "sync.example").await; let keys = Keys::generate(); - let indexer = tokio::spawn(Indexer::new(db.clone(), index.clone()).run()); + let indexer = tokio::spawn( + Indexer::new(db.clone(), index.clone()) + .with_new_index_settle(Duration::ZERO) + .run(), + ); let kept = message(&keys, "syncword kept"); db.insert_event(community, &kept, None) @@ -194,18 +222,29 @@ async fn the_indexer_lease_hands_over() { let keys = Keys::generate(); let service = SearchService::with_opensearch(db.pool().clone(), index.clone()); - let first = tokio::spawn(Indexer::new(db.clone(), index.clone()).run()); - let before = message(&keys, "leaseword before"); + // Both are signed now, a second apart, so the newest-first order the + // assertion expects does not depend on how long the handover takes. + let before = message_at(&keys, "leaseword before", -1); + let after = message_at(&keys, "leaseword after", 0); + + let first = tokio::spawn( + Indexer::new(db.clone(), index.clone()) + .with_new_index_settle(Duration::ZERO) + .run(), + ); db.insert_event(community, &before, None) .await .expect("insert"); wait_until_indexed(&db, &index).await; // The first instance holds the lease, so the second only waits. - let second = tokio::spawn(Indexer::new(db.clone(), index.clone()).run()); + let second = tokio::spawn( + Indexer::new(db.clone(), index.clone()) + .with_new_index_settle(Duration::ZERO) + .run(), + ); first.abort(); let _ = first.await; - let after = message(&keys, "leaseword after"); db.insert_event(community, &after, None) .await .expect("insert"); @@ -257,11 +296,13 @@ fn raw_client() -> OpenSearch { OpenSearch::new(Transport::single_node(&opensearch_url()).expect("transport")) } -/// A batch the cluster rejects leaves its rows queued and its community -/// skipped, while other communities are still indexed in the same pass. +/// A bulk item the cluster rejects keeps only its own row queued: the other +/// items of the same request are indexed and their rows removed, other +/// communities are indexed in the same pass, and the pass does not fail, so +/// nothing backs off. #[tokio::test] #[ignore = "requires Postgres and OpenSearch"] -async fn a_rejected_community_does_not_hold_back_others() { +async fn a_failed_bulk_item_keeps_only_its_own_row() { let db = sync_db().await; // An index whose `content` is a keyword: a term longer than 32766 bytes // is rejected per document with HTTP 400. @@ -280,30 +321,46 @@ async fn a_rejected_community_does_not_hold_back_others() { let index = SearchIndex::new(&OpenSearchConfig { url: opensearch_url(), basic_auth: None, - index_prefix: prefix, + index_prefix: prefix.clone(), }) .expect("client"); let poisoned = search_suite::mk_community(db.pool(), "poisoned.example").await; let healthy = search_suite::mk_community(db.pool(), "healthy.example").await; let keys = Keys::generate(); - db.insert_event(poisoned, &message(&keys, &"x".repeat(40_000)), None) - .await - .expect("insert oversized term"); - db.insert_event(healthy, &message(&keys, "fine"), None) - .await - .expect("insert"); + let oversized = message(&keys, &"x".repeat(40_000)); + let neighbour = message(&keys, "fine neighbour"); + let elsewhere = message(&keys, "fine elsewhere"); + for (community, event) in [ + (poisoned, &oversized), + (poisoned, &neighbour), + (healthy, &elsewhere), + ] { + db.insert_event(community, event, None) + .await + .expect("insert"); + } - let error = Indexer::new(db.clone(), index.clone()) + let report = Indexer::new(db.clone(), index.clone()) .drain() .await - .expect_err("the pass reports the rejected batch"); - assert!(error.to_string().contains("rejected"), "{error}"); - let queued: Vec = sqlx::query_scalar("SELECT community_id FROM search_outbox") - .fetch_all(db.pool()) - .await - .expect("queued rows"); - assert_eq!(queued, vec![*poisoned.as_uuid()]); + .expect("a rejected item does not fail the pass"); + // The refused item is tried again with its community's next batch, + // which holds nothing else, so that community is skipped. + assert_eq!((report.written, report.failed), (2, 2)); + assert_eq!(queued_events(&db).await, vec![*oversized.id.as_bytes()]); + for (community, event, found) in [ + (poisoned, &oversized, false), + (poisoned, &neighbour, true), + (healthy, &elsewhere, true), + ] { + assert_eq!( + indexed(&prefix, community, event).await, + found, + "{}", + event.content + ); + } index.delete().await.expect("delete index"); } @@ -344,3 +401,1277 @@ async fn writes_never_create_an_index() { assert_eq!(find(&service, community, "orphan").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") +} + +/// A channel of `community` created by `owner`. +async fn channel(db: &Db, community: CommunityId, owner: &Keys) -> Uuid { + db.ensure_user(community, owner.public_key().as_bytes()) + .await + .expect("ensure user"); + db.create_channel( + community, + &format!("sync-{}", Uuid::new_v4().simple()), + ChannelType::Stream, + ChannelVisibility::Open, + None, + owner.public_key().as_bytes(), + None, + ) + .await + .expect("create channel") + .id +} + +/// A message in `channel`, signed `offset` seconds from now. +fn channel_message( + keys: &Keys, + channel: Uuid, + kind: u16, + content: &str, + tags: &[&[&str]], + offset: i64, +) -> Event { + let mut all = vec![Tag::parse(["h", &channel.to_string()]).expect("h tag")]; + all.extend( + tags.iter() + .map(|tag| Tag::parse(tag.iter().copied()).expect("tag")), + ); + EventBuilder::new(Kind::Custom(kind), content) + .tags(all) + .custom_created_at(Timestamp::from( + (Timestamp::now().as_secs() as i64 + offset) as u64, + )) + .sign_with_keys(keys) + .expect("sign") +} + +/// Delete `target` with a NIP-09 deletion, as the relay stores one. +async fn delete(db: &Db, community: CommunityId, keys: &Keys, channel: Uuid, target: &Event) { + let deletion = channel_message(keys, channel, 5, "", &[&["e", &target.id.to_hex()]], 2); + let (_, _, deleted, _) = db + .insert_deletion_event( + community, + &deletion, + Some(channel), + None, + &[DeletionTarget { + event_id: target.id.as_bytes(), + created_at: signed_at(target), + parent_event_id: None, + root_event_id: None, + }], + &Keys::generate(), + ) + .await + .expect("insert deletion"); + assert_eq!(deleted, vec![true]); +} + +/// A deleted message no longer matches once the indexer catches up. +#[tokio::test] +#[ignore = "requires Postgres and OpenSearch"] +async fn a_deleted_message_no_longer_matches() { + let db = sync_db().await; + let (index, _) = sync_index().await; + let community = search_suite::mk_community(db.pool(), "delete.example").await; + let keys = Keys::generate(); + let channel = channel(&db, community, &keys).await; + let service = SearchService::with_opensearch(db.pool().clone(), index.clone()); + let indexer = tokio::spawn( + Indexer::new(db.clone(), index.clone()) + .with_new_index_settle(Duration::ZERO) + .run(), + ); + + let doomed = channel_message(&keys, channel, 9, "deleteword doomed", &[], 0); + let kept = channel_message(&keys, channel, 9, "deleteword kept", &[], 0); + for event in [&doomed, &kept] { + db.insert_event(community, event, Some(channel)) + .await + .expect("insert"); + } + wait_until_indexed(&db, &index).await; + assert_eq!(find(&service, community, "deleteword").await.len(), 2); + + delete(&db, community, &keys, channel, &doomed).await; + wait_until_indexed(&db, &index).await; + assert_eq!( + find(&service, community, "deleteword").await, + vec![*kept.id.as_bytes()] + ); + + indexer.abort(); + index.delete().await.expect("delete index"); +} + +/// An edited message matches its new text and not its old text; deleting +/// the edit brings the old text back. +#[tokio::test] +#[ignore = "requires Postgres and OpenSearch"] +async fn an_edited_message_matches_its_current_text() { + let db = sync_db().await; + let (index, _) = sync_index().await; + let community = search_suite::mk_community(db.pool(), "edit.example").await; + let keys = Keys::generate(); + let channel = channel(&db, community, &keys).await; + let service = SearchService::with_opensearch(db.pool().clone(), index.clone()); + let indexer = tokio::spawn( + Indexer::new(db.clone(), index.clone()) + .with_new_index_settle(Duration::ZERO) + .run(), + ); + + let original = channel_message(&keys, channel, 9, "oldword typo", &[], 0); + db.insert_event(community, &original, Some(channel)) + .await + .expect("insert"); + wait_until_indexed(&db, &index).await; + assert_eq!( + find(&service, community, "oldword").await, + vec![*original.id.as_bytes()] + ); + + let target = original.id.to_hex(); + let first = channel_message(&keys, channel, 40003, "midword", &[&["e", &target]], 1); + let latest = channel_message( + &keys, + channel, + 40003, + "newword fixed", + &[&["e", &target]], + 2, + ); + for edit in [&latest, &first] { + db.insert_event(community, edit, Some(channel)) + .await + .expect("insert edit"); + } + wait_until_indexed(&db, &index).await; + assert!(find(&service, community, "oldword").await.is_empty()); + assert!(find(&service, community, "midword").await.is_empty()); + assert_eq!( + find(&service, community, "newword").await, + vec![*original.id.as_bytes()] + ); + + delete(&db, community, &keys, channel, &latest).await; + delete(&db, community, &keys, channel, &first).await; + wait_until_indexed(&db, &index).await; + assert!(find(&service, community, "newword").await.is_empty()); + assert_eq!( + find(&service, community, "oldword").await, + vec![*original.id.as_bytes()] + ); + + indexer.abort(); + index.delete().await.expect("delete index"); +} + +/// Account deletion scrubs a message another person replied to and erases +/// the rest; neither matches its text afterwards, and the reply still does. +/// It runs as `buzz-admin user-deletions` does, without the outbox enabled: +/// the messages reach the index through the backfill. +#[tokio::test] +#[ignore = "requires Postgres and OpenSearch"] +async fn scrubbed_and_erased_messages_no_longer_match() { + let db = unsynced_db().await; + let (index, _) = sync_index().await; + let community = search_suite::mk_community(db.pool(), "scrub.example").await; + let leaving = Keys::generate(); + let staying = Keys::generate(); + let channel = channel(&db, community, &leaving).await; + db.ensure_user(community, staying.public_key().as_bytes()) + .await + .expect("ensure user"); + let service = SearchService::with_opensearch(db.pool().clone(), index.clone()); + let indexer = Indexer::new(db.clone(), index.clone()); + + let root = channel_message(&leaving, channel, 9, "scrubword referenced", &[], -2); + let erased = channel_message(&leaving, channel, 9, "scrubword alone", &[], -1); + for event in [&root, &erased] { + db.insert_event(community, event, Some(channel)) + .await + .expect("insert"); + } + let root_hex = root.id.to_hex(); + let reply = channel_message( + &staying, + channel, + 9, + "replyword", + &[ + &["e", &root_hex, "", "root"], + &["e", &root_hex, "", "reply"], + ], + 0, + ); + db.insert_event_with_thread_metadata( + community, + &reply, + Some(channel), + Some(ThreadMetadataParams { + event_id: reply.id.as_bytes(), + event_created_at: signed_at(&reply), + channel_id: channel, + parent_event_id: Some(root.id.as_bytes()), + parent_event_created_at: Some(signed_at(&root)), + root_event_id: Some(root.id.as_bytes()), + root_event_created_at: Some(signed_at(&root)), + depth: 1, + broadcast: false, + }), + ) + .await + .expect("insert reply"); + assert_eq!(search_outbox::depth(db.pool()).await.expect("depth"), 0); + indexer.backfill().await.expect("backfill"); + drain(&indexer, &index).await; + assert_eq!(find(&service, community, "scrubword").await.len(), 2); + + let summary = db + .user_deletion_store() + .run_message_batches( + &ContentBatchOptions { + community: *community.as_uuid(), + pubkey: leaving.public_key().to_hex(), + relay_pubkey: None, + batch_size: 100, + max_items: 1000, + }, + ExecutionMode::Delete, + None, + &mut Vec::new(), + ) + .await + .expect("delete the account's messages"); + assert_eq!( + summary.scrubbed_events, 1, + "the replied-to root is scrubbed" + ); + drain(&indexer, &index).await; + assert!(find(&service, community, "scrubword").await.is_empty()); + assert_eq!( + find(&service, community, "replyword").await, + vec![*reply.id.as_bytes()] + ); + + index.delete().await.expect("delete index"); +} + +/// Keys queued in the outbox, newest event first. +async fn queued_events(db: &Db) -> Vec<[u8; 32]> { + sqlx::query_scalar::<_, Vec>( + "SELECT event_id FROM search_outbox ORDER BY event_created_at DESC, event_id DESC", + ) + .fetch_all(db.pool()) + .await + .expect("queued rows") + .into_iter() + .map(|id| id.try_into().expect("32-byte id")) + .collect() +} + +/// Index what is queued and make it visible to search. +async fn drain(indexer: &Indexer, index: &SearchIndex) { + indexer.drain().await.expect("drain"); + index.refresh().await.expect("refresh"); +} + +/// Messages stored before OpenSearch was configured are backfilled newest +/// first, one bounded batch at a time. A restart resumes below the last +/// batch instead of starting over, live messages are indexed while the +/// backfill runs, and backfilling again creates no duplicate documents. +#[tokio::test] +#[ignore = "requires Postgres and OpenSearch"] +async fn stored_messages_are_backfilled_newest_first_and_resume() { + let db = unsynced_db().await; + let (index, prefix) = sync_index().await; + let community = search_suite::mk_community(db.pool(), "backfill.example").await; + // Another community, with nothing to backfill, takes its turns too. + search_suite::mk_community(db.pool(), "bystander.example").await; + let keys = Keys::generate(); + // Oldest first: stored[4] is the newest. + let stored: Vec = (0..5) + .map(|n| message_at(&keys, &format!("oldword {n}"), n - 10)) + .collect(); + for event in &stored { + db.insert_event(community, event, None) + .await + .expect("insert"); + } + let id = |event: &Event| *event.id.as_bytes(); + assert_eq!(search_outbox::depth(db.pool()).await.expect("depth"), 0); + + search_outbox::enable(db.pool()) + .await + .expect("enable outbox"); + let service = SearchService::with_opensearch(db.pool().clone(), index.clone()); + // Two keys per batch, and no more queued than one batch at a time. + let indexer = || { + Indexer::new(db.clone(), index.clone()) + .with_batch_size(2) + .with_backfill_bound(2) + }; + + // The first batch is the two newest messages. + let first = indexer(); + assert_eq!(first.backfill().await.expect("backfill"), 2); + assert_eq!( + queued_events(&db).await, + vec![id(&stored[4]), id(&stored[3])] + ); + assert_eq!( + first.backfill().await.expect("backfill"), + 0, + "nothing more is queued while the outbox is at its bound" + ); + drain(&first, &index).await; + assert_eq!( + find(&service, community, "oldword").await, + vec![id(&stored[4]), id(&stored[3])] + ); + + // Stop here. A new indexer, as after a restart, continues below the + // first batch. + drop(first); + let restarted = indexer(); + assert_eq!(restarted.backfill().await.expect("backfill"), 2); + assert_eq!( + queued_events(&db).await, + vec![id(&stored[2]), id(&stored[1])] + ); + + // A live message admitted mid-backfill is indexed by the next drain. + let live = message(&keys, "oldword live"); + db.insert_event(community, &live, None) + .await + .expect("insert live"); + drain(&restarted, &index).await; + let completed: Option> = + sqlx::query_scalar("SELECT completed_at FROM search_backfill WHERE community_id = $1") + .bind(community.as_uuid()) + .fetch_one(db.pool()) + .await + .expect("marker"); + assert!(completed.is_none(), "the backfill is still running"); + let progress = buzz_db::search_backfill::progress(db.pool()) + .await + .expect("progress"); + assert!(progress.contains(&(community, false)), "{progress:?}"); + assert_eq!( + find(&service, community, "oldword").await, + vec![ + id(&live), + id(&stored[4]), + id(&stored[3]), + id(&stored[2]), + id(&stored[1]) + ] + ); + + // The last batch is short, which completes the community. + assert_eq!(restarted.backfill().await.expect("backfill"), 1); + drain(&restarted, &index).await; + assert_eq!(restarted.backfill().await.expect("backfill"), 0); + let progress = buzz_db::search_backfill::progress(db.pool()) + .await + .expect("progress"); + assert!(progress.contains(&(community, true)), "{progress:?}"); + let everything = vec![ + id(&live), + id(&stored[4]), + id(&stored[3]), + id(&stored[2]), + id(&stored[1]), + id(&stored[0]), + ]; + assert_eq!(find(&service, community, "oldword").await, everything); + + // Backfill everything again: the documents are rewritten, not doubled. + sqlx::query("DELETE FROM search_backfill") + .execute(db.pool()) + .await + .expect("restart backfill"); + while restarted.backfill().await.expect("backfill") > 0 { + drain(&restarted, &index).await; + } + drain(&restarted, &index).await; + assert_eq!(find(&service, community, "oldword").await, everything); + let count: serde_json::Value = raw_client() + .count(opensearch::CountParts::Index(&[&format!( + "{prefix}messages" + )])) + .send() + .await + .expect("count") + .json() + .await + .expect("count body"); + assert_eq!(count["count"], 6, "{count}"); + index.delete().await.expect("delete index"); +} + +/// Wait until `count` messages of `community` match `q`, while the index +/// may still be missing. +async fn wait_until_found( + index: &SearchIndex, + service: &SearchService, + community: CommunityId, + q: &str, + count: usize, +) { + tokio::time::timeout(Duration::from_secs(30), async { + loop { + // Fails until the indexer has created the index. + if index.refresh().await.is_ok() && find(service, community, q).await.len() == count { + break; + } + tokio::time::sleep(Duration::from_millis(100)).await; + } + }) + .await + .expect("every stored message becomes searchable"); +} + +/// The lease holder starts backfilling on its own once OpenSearch is +/// configured, and again into an index it recreates after the old one went +/// away, also when the relay stopped just before or just after creating it. +#[tokio::test] +#[ignore = "requires Postgres and OpenSearch"] +async fn the_indexer_backfills_on_its_own() { + let db = unsynced_db().await; + let (index, prefix) = sync_index().await; + let proxy = Proxy::start().await; + let community = search_suite::mk_community(db.pool(), "auto.example").await; + let keys = Keys::generate(); + for n in 0..5 { + db.insert_event( + community, + &message_at(&keys, &format!("autoword {n}"), -n), + None, + ) + .await + .expect("insert"); + } + search_outbox::enable(db.pool()) + .await + .expect("enable outbox"); + let start = || { + tokio::spawn( + Indexer::new(db.clone(), proxy.index(&prefix)) + .with_batch_size(2) + .with_backfill_bound(2) + .with_new_index_settle(Duration::ZERO) + .run(), + ) + }; + let mut indexer = start(); + let service = SearchService::with_opensearch(db.pool().clone(), index.clone()); + wait_until_found(&index, &service, community, "autoword", 5).await; + let progress = buzz_db::search_backfill::progress(db.pool()) + .await + .expect("progress"); + assert!(progress.contains(&(community, true)), "{progress:?}"); + + // The index goes away while the backfill is complete. + index.delete().await.expect("delete index"); + wait_until_found(&index, &service, community, "autoword", 5).await; + + // The relay stops once before its create reaches the cluster, and once + // right after the cluster created the index. Each time the restarted + // relay backfills every message into the new index. + for create in [Create::Refuse, Create::Lose] { + let (done, stopped) = tokio::sync::oneshot::channel(); + proxy.set_create(create(done)).await; + index.delete().await.expect("delete index"); + tokio::time::timeout(Duration::from_secs(30), stopped) + .await + .expect("the indexer creates the index") + .expect("create signal"); + indexer.abort(); + let _ = indexer.await; + indexer = start(); + wait_until_found(&index, &service, community, "autoword", 5).await; + } + indexer.abort(); + index.delete().await.expect("delete index"); +} + +/// While a new index is backfilled, no community reports a complete +/// backfill, including one whose progress was already cleared, as by an +/// operator's `DELETE FROM search_backfill` before deleting the index. +#[tokio::test] +#[ignore = "requires Postgres and OpenSearch"] +async fn no_community_reports_a_complete_backfill_while_it_runs_again() { + let recorder = metrics_exporter_prometheus::PrometheusBuilder::new().build_recorder(); + let scrape = recorder.handle(); + // The test runtime has one thread, so the spawned indexer records here. + let _recorder = metrics::set_default_local_recorder(&recorder); + // What a scrape reports for the community, if anything. + let complete = |community: CommunityId| { + let series = format!("buzz_search_backfill_complete{{community=\"{community}\"}} "); + scrape + .render() + .lines() + .find_map(|line| line.strip_prefix(series.as_str()).map(str::to_owned)) + }; + + let db = unsynced_db().await; + let (index, prefix) = sync_index().await; + let proxy = Proxy::start().await; + let keys = Keys::generate(); + let mut communities = Vec::new(); + for host in ["first.example", "second.example"] { + let community = search_suite::mk_community(db.pool(), host).await; + for n in 0..3 { + db.insert_event( + community, + &message_at(&keys, &format!("gaugeword {n}"), -n), + None, + ) + .await + .expect("insert"); + } + communities.push(community); + } + search_outbox::enable(db.pool()) + .await + .expect("enable outbox"); + let indexer = tokio::spawn( + Indexer::new(db.clone(), proxy.index(&prefix)) + .with_batch_size(2) + .with_backfill_bound(2) + .with_new_index_settle(Duration::ZERO) + .run(), + ); + tokio::time::timeout(Duration::from_secs(30), async { + while !(communities + .iter() + .all(|community| complete(*community).as_deref() == Some("1")) + && search_outbox::depth(db.pool()).await.expect("depth") == 0) + { + tokio::time::sleep(Duration::from_millis(100)).await; + } + }) + .await + .expect("both backfills complete and are indexed"); + + // Rebuild, holding the first write into the new index: the first + // community's first batch is queued, the second's not yet. The hold + // starts with the create, so a pass before the index delete passes. + let (arrived, held) = tokio::sync::oneshot::channel(); + let (release, released) = tokio::sync::oneshot::channel(); + proxy + .set_create(Create::Then(Bulk::Hold { + arrived, + release: released, + })) + .await; + sqlx::query("DELETE FROM search_backfill") + .execute(db.pool()) + .await + .expect("clear backfill progress"); + index.delete().await.expect("delete index"); + tokio::time::timeout(Duration::from_secs(30), held) + .await + .expect("the indexer writes into the new index") + .expect("hold signal"); + for community in &communities { + assert_eq!(complete(*community).as_deref(), Some("0"), "{community}"); + } + let _ = release.send(()); + indexer.abort(); + index.delete().await.expect("delete index"); +} + +/// Whether the index holds `event`'s document. +async fn indexed(prefix: &str, community: CommunityId, event: &Event) -> bool { + let response = raw_client() + .get(GetParts::IndexId( + &format!("{prefix}messages"), + &format!("{}:{}", community.as_uuid(), event.id.to_hex()), + )) + .send() + .await + .expect("get document"); + let document: serde_json::Value = response.json().await.expect("document body"); + document["found"] == true +} + +/// What the proxy does with the next bulk request. +enum Bulk { + /// Forward it. + Pass, + /// Answer HTTP 429, as Serverless does while it scales. + Throttle, + /// Signal `arrived`, wait for `release`, then forward it. + Hold { + arrived: tokio::sync::oneshot::Sender<()>, + release: tokio::sync::oneshot::Receiver<()>, + }, +} + +/// What the proxy does with the next index creation, signalling the +/// sender once it is done. +enum Create { + /// Answer HTTP 503 without creating the index, as when the relay stops + /// before its create reaches the cluster. + Refuse(tokio::sync::oneshot::Sender<()>), + /// Create the index, then answer HTTP 503, as when the relay stops + /// right after the cluster created it. + Lose(tokio::sync::oneshot::Sender<()>), + /// Create the index, and apply this to the bulk requests that follow. + Then(Bulk), +} + +/// An HTTP proxy in front of the test cluster that can throttle or hold +/// bulk requests, and refuse or lose an index creation. +struct Proxy { + url: String, + bulk: std::sync::Arc>, + create: std::sync::Arc>>, + server: tokio::task::JoinHandle<()>, +} + +impl Proxy { + async fn start() -> Self { + let bulk = std::sync::Arc::new(tokio::sync::Mutex::new(Bulk::Pass)); + let create = std::sync::Arc::new(tokio::sync::Mutex::new(None)); + let state = ( + bulk.clone(), + create.clone(), + reqwest::Client::new(), + opensearch_url(), + ); + let app = axum::Router::new() + .fallback(proxy_request) + .with_state(state); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("bind proxy"); + let url = format!("http://{}", listener.local_addr().expect("proxy address")); + let server = tokio::spawn(async move { + axum::serve(listener, app).await.expect("serve proxy"); + }); + Self { + url, + bulk, + create, + server, + } + } + + /// The index behind this proxy, using `prefix`. + fn index(&self, prefix: &str) -> SearchIndex { + SearchIndex::new(&OpenSearchConfig { + url: self.url.clone(), + basic_auth: None, + index_prefix: prefix.into(), + }) + .expect("proxied client") + } + + async fn set(&self, bulk: Bulk) { + *self.bulk.lock().await = bulk; + } + + async fn set_create(&self, create: Create) { + *self.create.lock().await = Some(create); + } +} + +impl Drop for Proxy { + fn drop(&mut self) { + self.server.abort(); + } +} + +type ProxyState = ( + std::sync::Arc>, + std::sync::Arc>>, + reqwest::Client, + String, +); + +fn unavailable() -> axum::response::Response { + axum::response::Response::builder() + .status(503) + .body(axum::body::Body::empty()) + .expect("unavailable response") +} + +async fn proxy_request( + axum::extract::State((bulk, create, client, upstream)): axum::extract::State, + request: axum::extract::Request, +) -> axum::response::Response { + let (parts, body) = request.into_parts(); + let body = axum::body::to_bytes(body, usize::MAX) + .await + .expect("request body"); + // An index creation is a PUT of the index name alone. + let creates = + parts.method == axum::http::Method::PUT && parts.uri.path().matches('/').count() == 1; + let mut lost = None; + if creates { + match create.lock().await.take() { + None => {} + Some(Create::Refuse(done)) => { + let _ = done.send(()); + return unavailable(); + } + Some(Create::Lose(done)) => lost = Some(done), + Some(Create::Then(next)) => *bulk.lock().await = next, + } + } + if parts.uri.path().ends_with("/_bulk") { + let action = std::mem::replace(&mut *bulk.lock().await, Bulk::Pass); + match action { + Bulk::Pass => {} + Bulk::Throttle => { + *bulk.lock().await = Bulk::Throttle; + return axum::response::Response::builder() + .status(429) + .header("content-type", "application/json") + .body(axum::body::Body::from( + r#"{"error":{"type":"too_many_requests"},"status":429}"#, + )) + .expect("throttled response"); + } + Bulk::Hold { arrived, release } => { + let _ = arrived.send(()); + let _ = release.await; + } + } + } + let path = parts.uri.path_and_query().map_or("/", |path| path.as_str()); + let mut forward = client + .request(parts.method, format!("{upstream}{path}")) + .body(body); + if let Some(content_type) = parts.headers.get("content-type") { + forward = forward.header("content-type", content_type); + } + let response = forward.send().await.expect("forward to OpenSearch"); + if let Some(done) = lost { + assert!(response.status().is_success(), "the index is created"); + let _ = done.send(()); + return unavailable(); + } + let mut builder = axum::response::Response::builder().status(response.status().as_u16()); + if let Some(content_type) = response.headers().get("content-type") { + builder = builder.header("content-type", content_type); + } + builder + .body(axum::body::Body::from( + response.bytes().await.expect("OpenSearch response"), + )) + .expect("proxied response") +} + +/// Throttling ends the pass as throttled, not failed, and keeps every row +/// queued; indexing completes once the cluster accepts writes again. +#[tokio::test] +#[ignore = "requires Postgres and OpenSearch"] +async fn throttling_keeps_rows_queued() { + let db = sync_db().await; + let (index, prefix) = sync_index().await; + let proxy = Proxy::start().await; + let community = search_suite::mk_community(db.pool(), "throttle.example").await; + let keys = Keys::generate(); + let queued = [ + message(&keys, "slowword one"), + message(&keys, "slowword two"), + ]; + for event in &queued { + db.insert_event(community, event, None) + .await + .expect("insert"); + } + let indexer = Indexer::new(db.clone(), proxy.index(&prefix)).with_workers(2); + + proxy.set(Bulk::Throttle).await; + let error = indexer.drain().await.expect_err("throttled"); + assert!(matches!(error, IndexerError::Throttled), "{error}"); + assert_eq!(search_outbox::depth(db.pool()).await.expect("depth"), 2); + + proxy.set(Bulk::Pass).await; + let report = indexer.drain().await.expect("drain"); + assert_eq!(report.written, 2); + index.refresh().await.expect("refresh"); + let service = SearchService::with_opensearch(db.pool().clone(), index.clone()); + assert_eq!(find(&service, community, "slowword").await.len(), 2); + index.delete().await.expect("delete index"); +} + +/// A change committed while an earlier row for the same message is being +/// indexed keeps its own row and is indexed afterwards. The proxy holds the +/// worker's bulk request, after its re-read and before its delete. +#[tokio::test] +#[ignore = "requires Postgres and OpenSearch"] +async fn a_change_during_indexing_is_indexed_afterwards() { + let db = sync_db().await; + let (index, prefix) = sync_index().await; + let proxy = Proxy::start().await; + let community = search_suite::mk_community(db.pool(), "gate.example").await; + let keys = Keys::generate(); + let channel = channel(&db, community, &keys).await; + let original = channel_message(&keys, channel, 9, "firstword", &[], 0); + db.insert_event(community, &original, Some(channel)) + .await + .expect("insert"); + + let (arrived_tx, arrived) = tokio::sync::oneshot::channel(); + let (release, release_rx) = tokio::sync::oneshot::channel(); + proxy + .set(Bulk::Hold { + arrived: arrived_tx, + release: release_rx, + }) + .await; + let indexer = Indexer::new(db.clone(), proxy.index(&prefix)); + let drain = tokio::spawn(async move { indexer.drain().await }); + arrived.await.expect("the worker sent its batch"); + + // The worker has read "firstword" and not yet deleted its row. + let edit = channel_message( + &keys, + channel, + 40003, + "secondword", + &[&["e", &original.id.to_hex()]], + 1, + ); + db.insert_event(community, &edit, Some(channel)) + .await + .expect("insert edit"); + assert_eq!(search_outbox::depth(db.pool()).await.expect("depth"), 2); + release.send(()).expect("release the batch"); + + let report = drain.await.expect("drain task").expect("drain"); + assert_eq!(report.batches, 2, "the edit's row is its own batch"); + assert_eq!(search_outbox::depth(db.pool()).await.expect("depth"), 0); + index.refresh().await.expect("refresh"); + let service = SearchService::with_opensearch(db.pool().clone(), index.clone()); + assert!(find(&service, community, "firstword").await.is_empty()); + assert_eq!( + find(&service, community, "secondword").await, + vec![*original.id.as_bytes()] + ); + index.delete().await.expect("delete index"); +} + +/// A stored channel message's document with `content` as its text. +fn document_of(event: &Event, channel: Uuid, content: &str) -> SearchDocument { + SearchDocument { + event_id: event.id.to_bytes(), + kind: 9, + pubkey: event.pubkey.to_bytes(), + channel_id: Some(channel), + created_at: signed_at(event), + content: content.into(), + channel_type: Some("stream".into()), + author_is_agent: false, + thread_root: None, + mentions: Vec::new(), + } +} + +/// A community of its own with one channel, and the channel owner's keys. +async fn late_community(db: &Db) -> (CommunityId, Keys, Uuid) { + let community = search_suite::mk_community( + db.pool(), + &format!("late-{}.example", Uuid::new_v4().simple()), + ) + .await; + let keys = Keys::generate(); + let channel = channel(db, community, &keys).await; + (community, keys, channel) +} + +/// The next value of the version sequence batches read. +async fn next_version(db: &Db) -> i64 { + sqlx::query_scalar("SELECT nextval('search_index_version')") + .fetch_one(db.pool()) + .await + .expect("next version") +} + +/// A database layer whose connections read `clock_timestamp()` ahead by +/// the microseconds [`set_clock_skew`] last set, through a function on +/// their own search path. Nothing else on these connections changes. +async fn skewed_clock_db() -> Db { + let url = std::env::var("BUZZ_TEST_DATABASE_URL") + .unwrap_or_else(|_| search_suite::TEST_DB_URL.into()); + let setup = Db::new(&DbConfig { + database_url: url.clone(), + ..DbConfig::default() + }) + .await + .expect("connect database layer"); + for statement in [ + "CREATE SCHEMA IF NOT EXISTS buzz_test_clock", + "CREATE TABLE IF NOT EXISTS buzz_test_clock.skew (micros BIGINT NOT NULL)", + "CREATE OR REPLACE FUNCTION buzz_test_clock.clock_timestamp() RETURNS timestamptz \ + LANGUAGE sql AS $$ SELECT pg_catalog.clock_timestamp() + make_interval(secs => \ + (SELECT coalesce(max(micros), 0) FROM buzz_test_clock.skew) / 1000000.0) $$", + ] { + sqlx::query(statement) + .execute(setup.pool()) + .await + .expect("install the skewed clock"); + } + let separator = if url.contains('?') { '&' } else { '?' }; + Db::new(&DbConfig { + database_url: format!( + "{url}{separator}options=-c%20search_path%3Dbuzz_test_clock%2Cpg_catalog%2Cpublic" + ), + ..DbConfig::default() + }) + .await + .expect("connect skewed database layer") +} + +/// Run every `clock_timestamp()` of a [`skewed_clock_db`] `micros` ahead. +async fn set_clock_skew(db: &Db, micros: i64) { + sqlx::query( + "WITH cleared AS (DELETE FROM buzz_test_clock.skew) \ + INSERT INTO buzz_test_clock.skew (micros) VALUES ($1)", + ) + .bind(micros) + .execute(db.pool()) + .await + .expect("set the clock skew"); +} + +/// The index keeps each document's newest version: a bulk request the +/// cluster applies after a later one, as when its indexer timed out or +/// crashed with the request in flight, changes nothing. Its items come back +/// as conflicts, which nobody reads: its batch has ended. +/// Mutation: write without the external version → RED. +#[tokio::test] +#[ignore = "requires Postgres and OpenSearch"] +async fn a_late_write_cannot_undo_a_newer_one() { + let db = sync_db().await; + let (index, prefix) = sync_index().await; + let (community, keys, channel) = late_community(&db).await; + let event = channel_message(&keys, channel, 9, "firstword", &[], 0); + db.insert_event(community, &event, Some(channel)) + .await + .expect("insert"); + let document = |content: &str| document_of(&event, channel, content); + let write = |documents: Vec, removed: Vec<[u8; 32]>, version: i64| { + let index = index.clone(); + async move { + index + .write(community, &documents, &removed, version) + .await + .expect("write") + .conflicts + } + }; + let service = SearchService::with_opensearch(db.pool().clone(), index.clone()); + + // The edit's write lands first, then the original's late one. + assert_eq!(write(vec![document("secondword")], vec![], 2).await, 0); + assert_eq!(write(vec![document("firstword")], vec![], 1).await, 1); + index.refresh().await.expect("refresh"); + assert!(find(&service, community, "firstword").await.is_empty()); + assert_eq!( + find(&service, community, "secondword").await, + vec![event.id.to_bytes()] + ); + + // The removal lands first, then the edit's late write. + assert_eq!(write(vec![], vec![event.id.to_bytes()], 3).await, 0); + assert_eq!(write(vec![document("secondword")], vec![], 2).await, 1); + index.refresh().await.expect("refresh"); + assert!(!indexed(&prefix, community, &event).await); + index.delete().await.expect("delete index"); +} + +/// A live batch is its events' newest writer, so a conflict it meets means +/// the version sequence handed out a value again, as after a Postgres crash +/// or promoting an asynchronous replica: here the document was +/// written at a version the sequence has not reached. The newer state stays +/// queued and the pass fails, and once the sequence passes the version the +/// index holds, it is written. +/// Mutation: count a version conflict as written → RED. +#[tokio::test] +#[ignore = "requires Postgres and OpenSearch"] +async fn a_newer_state_below_the_held_version_stays_queued() { + let db = sync_db().await; + let (index, _prefix) = sync_index().await; + let (community, keys, channel) = late_community(&db).await; + let original = channel_message(&keys, channel, 9, "firstword", &[], 0); + db.insert_event(community, &original, Some(channel)) + .await + .expect("insert"); + let ahead = next_version(&db).await + 1_000; + let outcome = index + .write( + community, + &[document_of(&original, channel, "firstword")], + &[], + ahead, + ) + .await + .expect("write ahead"); + assert!(outcome.failed.is_empty(), "{outcome:?}"); + let edit = channel_message( + &keys, + channel, + 40003, + "secondword", + &[&["e", &original.id.to_hex()]], + 1, + ); + db.insert_event(community, &edit, Some(channel)) + .await + .expect("insert edit"); + let service = SearchService::with_opensearch(db.pool().clone(), index.clone()); + let indexer = Indexer::new(db.clone(), index.clone()); + + assert!(indexer.drain().await.is_err(), "a conflict fails the pass"); + assert!(search_outbox::depth(db.pool()).await.expect("depth") > 0); + index.refresh().await.expect("refresh"); + assert!(find(&service, community, "secondword").await.is_empty()); + + sqlx::query("SELECT setval('search_index_version', $1)") + .bind(ahead) + .execute(db.pool()) + .await + .expect("move the sequence to the held version"); + drain(&indexer, &index).await; + assert_eq!(search_outbox::depth(db.pool()).await.expect("depth"), 0); + assert!(find(&service, community, "firstword").await.is_empty()); + assert_eq!( + find(&service, community, "secondword").await, + vec![original.id.to_bytes()] + ); + index.delete().await.expect("delete index"); +} + +/// A batch's request can land after the batch has ended and a later batch +/// has written a newer state, as when its indexer timed out with the +/// request in flight. The later batch's version must be the larger one even +/// when the database clock stepped back in between; otherwise the late +/// request wins, the index keeps the older text, and no live batch ever +/// meets a conflict. Here the clock runs 10 s ahead for the first batch and +/// is put back before the second. +/// Mutation: read the version from `clock_timestamp()` → RED. +#[tokio::test] +#[ignore = "requires Postgres and OpenSearch"] +async fn a_late_request_from_before_a_clock_step_changes_nothing() { + let db = sync_db().await; + let (index, _prefix) = sync_index().await; + let skewed = skewed_clock_db().await; + let (community, keys, channel) = late_community(&db).await; + let original = channel_message(&keys, channel, 9, "firstword", &[], 0); + db.insert_event(community, &original, Some(channel)) + .await + .expect("insert"); + + // The first batch reads the original while the clock runs ahead; it + // sends its request and ends without completing, so the request is in + // flight and the row stays queued. + set_clock_skew(&db, 10_000_000).await; + let mut skip = Vec::new(); + let (documents, removed, version) = loop { + let batch = search_outbox::claim_batch(skewed.pool(), 100, &skip) + .await + .expect("claim") + .expect("a batch of the community"); + if batch.community() == community { + break ( + batch.documents.clone(), + batch.removed.clone(), + batch.version, + ); + } + skip.push(batch.community()); + }; + assert_eq!( + documents, + vec![document_of(&original, channel, "firstword")] + ); + + // The clock steps back, the message is edited, and the next batch + // writes the edit. + set_clock_skew(&db, 0).await; + let edit = channel_message( + &keys, + channel, + 40003, + "secondword", + &[&["e", &original.id.to_hex()]], + 1, + ); + db.insert_event(community, &edit, Some(channel)) + .await + .expect("insert edit"); + let indexer = Indexer::new(skewed.clone(), index.clone()); + drain(&indexer, &index).await; + assert_eq!(search_outbox::depth(db.pool()).await.expect("depth"), 0); + + // The first batch's request lands now. + let outcome = index + .write(community, &documents, &removed, version) + .await + .expect("late write"); + index.refresh().await.expect("refresh"); + let service = SearchService::with_opensearch(db.pool().clone(), index.clone()); + assert!( + find(&service, community, "firstword").await.is_empty(), + "the late request put the original text back: {outcome:?}" + ); + assert_eq!( + find(&service, community, "secondword").await, + vec![original.id.to_bytes()] + ); + assert_eq!(outcome.conflicts, 1, "{outcome:?}"); + index.delete().await.expect("delete index"); +} + +/// Two workers drain the outbox together without losing a row or indexing +/// one twice, and afterwards the index holds exactly what Postgres does. +#[tokio::test] +#[ignore = "requires Postgres and OpenSearch"] +async fn two_workers_drain_without_loss() { + let db = sync_db().await; + let (index, prefix) = sync_index().await; + let keys = Keys::generate(); + let mut stored = Vec::new(); + for n in 0..3 { + let community = search_suite::mk_community(db.pool(), &format!("workers{n}.example")).await; + let channel = channel(&db, community, &keys).await; + for m in 0..30 { + let event = channel_message(&keys, channel, 9, &format!("workword {n} {m}"), &[], -m); + db.insert_event(community, &event, Some(channel)) + .await + .expect("insert"); + stored.push((community, channel, event)); + } + } + let indexer = Indexer::new(db.clone(), index.clone()) + .with_batch_size(7) + .with_workers(2); + let report = indexer.drain().await.expect("drain"); + assert_eq!( + (report.written, report.removed, report.failed), + (90, 0, 0), + "every row indexed exactly once" + ); + assert_eq!(search_outbox::depth(db.pool()).await.expect("depth"), 0); + + // Delete every third message and edit every fifth live one. + let mut deleted = Vec::new(); + for (i, (community, channel, event)) in stored.iter().enumerate() { + if i % 3 == 0 { + delete(&db, *community, &keys, *channel, event).await; + deleted.push(event.id); + } else if i % 5 == 0 { + let edit = channel_message( + &keys, + *channel, + 40003, + "rewritten", + &[&["e", &event.id.to_hex()]], + 1, + ); + db.insert_event(*community, &edit, Some(*channel)) + .await + .expect("insert edit"); + } + } + indexer.drain().await.expect("drain"); + assert_eq!(search_outbox::depth(db.pool()).await.expect("depth"), 0); + index.refresh().await.expect("refresh"); + for (community, _, event) in &stored { + assert_eq!( + indexed(&prefix, *community, event).await, + !deleted.contains(&event.id), + "{}", + event.content + ); + } + let service = SearchService::with_opensearch(db.pool().clone(), index.clone()); + let mut rewritten = 0; + for community in stored + .iter() + .map(|(community, _, _)| *community) + .collect::>() + { + rewritten += find(&service, community, "rewritten").await.len(); + } + let expected = (0..stored.len()) + .filter(|i| i % 3 != 0 && i % 5 == 0) + .count(); + assert_eq!(rewritten, expected); + let count: serde_json::Value = raw_client() + .count(opensearch::CountParts::Index(&[&format!( + "{prefix}messages" + )])) + .send() + .await + .expect("count") + .json() + .await + .expect("count body"); + assert_eq!(count["count"], 60, "{count}"); + index.delete().await.expect("delete index"); +} + +/// Several instances started at once end with exactly one lease holder, which +/// indexes what is queued. +#[tokio::test] +#[ignore = "requires Postgres and OpenSearch"] +async fn instances_started_together_elect_one_leader() { + let db = sync_db().await; + let (index, _) = sync_index().await; + let community = search_suite::mk_community(db.pool(), "fleet.example").await; + let event = message(&Keys::generate(), "fleetword"); + db.insert_event(community, &event, None) + .await + .expect("insert"); + let instances: Vec<_> = (0..4) + .map(|_| { + tokio::spawn( + Indexer::new(db.clone(), index.clone()) + .with_new_index_settle(Duration::ZERO) + .run(), + ) + }) + .collect(); + let service = SearchService::with_opensearch(db.pool().clone(), index.clone()); + tokio::time::timeout(Duration::from_secs(30), async { + loop { + index.refresh().await.expect("refresh"); + if !find(&service, community, "fleetword").await.is_empty() { + break; + } + tokio::time::sleep(Duration::from_millis(100)).await; + } + }) + .await + .expect("the leader indexes the queued message"); + // The indexer lease: a session advisory lock on one bigint key, which + // pg_locks shows as its high and low halves. + let holders: i64 = sqlx::query_scalar( + "SELECT count(*) FROM pg_locks \ + WHERE locktype = 'advisory' AND granted AND objsubid = 1 \ + AND database = (SELECT oid FROM pg_database WHERE datname = current_database()) \ + AND classid = $1::bigint::oid AND objid = $2::bigint::oid", + ) + .bind(0x4255_5A5A_i64) + .bind(0x5345_4152_i64) + .fetch_one(db.pool()) + .await + .expect("lease holders"); + assert_eq!(holders, 1); + for instance in instances { + instance.abort(); + } + index.delete().await.expect("delete index"); +} diff --git a/docs/database.md b/docs/database.md index 2f9a51ea27..cf0e56e0ad 100644 --- a/docs/database.md +++ b/docs/database.md @@ -290,7 +290,7 @@ apply: | `migrations/NNNN_.sql` | The forward migration for existing databases. Use the next free number; rebase and renumber on a collision. Never edit a merged migration: its checksum changes, and relays that run the migrator fail with sqlx `VersionMismatch`. Fix forward in a new migration. | | `schema/tables/public/.sql` | The table's final `CREATE TABLE` and its `CREATE INDEX` statements, one table per file. This is the declarative schema source. | | `schema/schema.sql` | An `\i` line for each new file, after the tables it depends on. | -| `schema/types/`, `schema/partitions/`, `schema/seeds/` | The matching non-table objects. The layout test permits nothing else here. `schema/` has no `functions/` or `triggers/` directory, and Rule 1 forbids adding one. | +| `schema/types/`, `schema/sequences/`, `schema/partitions/`, `schema/seeds/` | The matching non-table objects. The layout test permits nothing else here. `schema/` has no `functions/` or `triggers/` directory, and Rule 1 forbids adding one. | | `scripts/reconcile-schema-after-pgschema.sql` | Idempotent convergence, plus a live assertion, for anything `pgschema` does not preserve: seed rows, some storage parameters, partition attachment, and the shapes listed in AGENTS.md *Common Gotchas* #7. | | `crates/buzz-push-gateway/migrations/`, `crates/buzz-push-gateway/schema/`, **and** the relay copies | The six `push_gateway_*` tables have two homes. The gateway applies its own migration history to its own database, through a pre-install/pre-upgrade Helm Job ([push-gateway-deployment.md](push-gateway-deployment.md)). `crates/buzz-push-gateway/schema/tables/public/` holds the gateway's declarative end state, one table per file; its parity test fails when it drifts from the gateway migrations. The relay schema also defines them: `migrations/` (`0015`, `0043`, `0045`, `0060`), `schema/tables/public/push_gateway_*.sql`, and `schema/seeds/push_gateway_*.sql`. Until the duplication is removed, a gateway schema change goes in both, as relay `0060` mirrors gateway `0006`. Every rule here applies to both. The target is for the gateway to own its tables alone, in its own migrations and declarative schema; do not add new gateway tables to the relay schema. | diff --git a/docs/opensearch-search-deployment.md b/docs/opensearch-search-deployment.md index 187df2dee4..dfc0450e07 100644 --- a/docs/opensearch-search-deployment.md +++ b/docs/opensearch-search-deployment.md @@ -1,31 +1,40 @@ # OpenSearch message index deployment With `BUZZ_OPENSEARCH_URL` set, the relay keeps an OpenSearch index of -messages up to date through the `search_outbox` table. Searches still run on -Postgres. +messages up to date through the `search_outbox` table, and backfills the +messages stored before it was set. Searches still run on Postgres. | Variable | Meaning | | --- | --- | | `BUZZ_OPENSEARCH_URL` | HTTP(S) cluster URL without credentials, query or fragment. Unset turns indexing off. | | `BUZZ_OPENSEARCH_USERNAME`, `BUZZ_OPENSEARCH_PASSWORD` | Optional basic auth. Set both or neither. | -| `BUZZ_OPENSEARCH_PREVIEW` | Required with the URL until [block/buzz#9862](https://github.com/block/buzz/pull/9862), because deleted messages stay in the index. Use it only on relays without real data. | +| `BUZZ_SEARCH_INDEXER_WORKERS` | Indexer workers on the relay that holds the lease: 1 to 32, default 1. Each holds one connection from `BUZZ_DB_POOL_SIZE` for the length of a bulk request, so leave the pool room for them. | +| `BUZZ_OPENSEARCH_PREVIEW` | Required with the URL for now, because deleting a community leaves its messages in the index. Use it only on relays without real data. | ## Rollout order -1. Deploy a release that lists `search_outbox` as a pending deletion-scoped - table ([block/buzz#9871](https://github.com/block/buzz/pull/9871)). - Deletion code that predates it rejects the catalog once migration `0106` - runs, which stops community deletion. -2. Deploy the release with migration `0106`. Nothing is queued until the - setting is on. +1. Deploy a release that lists `search_outbox` and `search_backfill` as + pending deletion-scoped tables + ([block/buzz#9871](https://github.com/block/buzz/pull/9871)). Deletion + code that predates it rejects the catalog once migration `0106` runs, + which stops community deletion. +2. Deploy the release with migrations `0106` to `0108`. Nothing is queued + until the setting is on. 3. Set `BUZZ_OPENSEARCH_URL` and `BUZZ_OPENSEARCH_PREVIEW=true` on every - relay. Each relay queues only the messages it stores, so one without the - settings leaves gaps. A relay with them refuses to start before `0106` has - run. Until [block/buzz#9862](https://github.com/block/buzz/pull/9862) - caps bulk requests, a cluster with a 10 MiB request limit can reject a - full batch. + relay in one deploy. A relay queues only its own writes, so one without + the settings leaves the index without the messages it stores and with the + ones it deletes. A relay with them refuses to start before the migrations + have run. The backfill starts with the first relay to hold the lease. -Messages stored before step 3 are not indexed; there is no backfill yet. +If a relay without the settings ran after the backfill started, wait until +every relay has them, then delete the index while searches run on +Postgres. The relay clears the backfill progress, creates the index again, +waits 30 seconds before its first write, and backfills every community. It +does the same whenever the index goes missing. Running +`DELETE FROM search_backfill` without deleting the index is +not enough: the backfill reads only live messages, so it would leave the +documents of messages deleted in the meantime. Deleting one community's row +backfills that community again. To turn indexing off, unset the URL and restart the relays. Queued rows stay until it is back on. @@ -42,8 +51,56 @@ The index holds the words of every indexed message, DMs included, so anyone who can query the cluster can search them. Limit cluster access to the relays. If you stream Postgres changes through logical replication, leave -`search_outbox` out of the publication. Its rows are short-lived queue -entries. +`search_outbox` and `search_backfill` out of the publication. Their rows are +short-lived queue entries and progress markers. + +After a point-in-time restore, or a cut-over to a cluster built by logical +replication (which copies no sequence values), the version sequence can be +far below the versions the index holds. The index then refuses changes to the +messages it holds: `buzz_search_index_version_conflicts_total` rises and their +rows stay in `search_outbox`. Rebuild the index (above), or move the sequence +past any version handed out before. The indexer takes far fewer than a +million values a second, so a value tied to the clock works after every +restore or cut-over: + +```sh +psql -c "SELECT setval('search_index_version', GREATEST((SELECT last_value FROM search_index_version) + 1000000000000, 10000000000000000 + (EXTRACT(EPOCH FROM now())::bigint * 1000000)))" +``` + +## What to watch + +| Metric | Act when | +| --- | --- | +| `buzz_search_index_rejected_total` | It rises steadily: the cluster refuses those documents for good, and their rows stay queued. | +| `buzz_search_index_version_conflicts_total` | It is not zero: the version sequence handed out values again (below). | +| `buzz_search_backfill_complete` | `1` means every stored message of the community is queued, not yet indexed. Move searches to OpenSearch once it is `1` for every community and `search_outbox` has emptied. | + +If `buzz_search_index_rejected_total` rises, investigate the rejection and +fix the cause. The relay retries rejected rows automatically. A sustained +spike can block newer messages in the affected community and pause backfill +across communities. After the fix, verify that the queue drains. + +## Known gaps + +- **Deleted communities.** Deleting a community does not remove its + documents from the index. No search can return them, but their words stay + in the index. +- **Postgres crash or failover.** The version sequence can hand out values + again after a Postgres crash or the promotion of an asynchronous replica. + Rows then stay queued until the sequence passes the versions the index + holds. If a bulk request sent before the crash also lands after a newer + write of the same message, the index keeps that message's older text + until it changes again. +- **Writes applied late.** OpenSearch forgets a delete's version after 60 + seconds (`gc_deletes`), so an older write that lands later, such as a + previous lease holder's bulk request, brings the deleted document back. +- **Removed text on disk.** A removed document can no longer be found, but + its text stays in the index's files until OpenSearch merges them. The + relay does not force that merge. + +In the two cases before this one, a search can match text a message no longer has. Every +hit is re-read from Postgres before it is returned, so that text is never +shown. ## Local run diff --git a/migrations/0107_search_backfill.sql b/migrations/0107_search_backfill.sql new file mode 100644 index 0000000000..8c78df4f19 --- /dev/null +++ b/migrations/0107_search_backfill.sql @@ -0,0 +1,13 @@ +-- Per-community search backfill progress; see +-- schema/tables/public/search_backfill.sql. Its writers use community +-- admission (docs/database.md). A new, empty table. +SET LOCAL lock_timeout = '5s'; +CREATE TABLE search_backfill ( + community_id UUID NOT NULL, + cursor_created_at TIMESTAMPTZ, + cursor_event_id BYTEA CHECK (length(cursor_event_id) = 32), + enqueued BIGINT NOT NULL DEFAULT 0, + completed_at TIMESTAMPTZ, + updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), + PRIMARY KEY (community_id) +); diff --git a/migrations/0108_search_index_version.sql b/migrations/0108_search_index_version.sql new file mode 100644 index 0000000000..0e54165499 --- /dev/null +++ b/migrations/0108_search_index_version.sql @@ -0,0 +1,5 @@ +-- The search indexer's external version; see +-- schema/sequences/search_index_version.sql. A new sequence: it locks no +-- existing object. +SET LOCAL lock_timeout = '5s'; +CREATE SEQUENCE search_index_version AS BIGINT START WITH 10000000000000000; diff --git a/schema/schema.sql b/schema/schema.sql index f7800133a9..f8f6f6998a 100644 --- a/schema/schema.sql +++ b/schema/schema.sql @@ -6,9 +6,10 @@ -- namespace, so nothing else may live under it. -- -- Everything SchemaBot cannot apply lives in this directory's other --- subdirectories: `types/`, `partitions/`, and `seeds/`. This file composes --- them into one fresh database, in load order: types → tables → partitions → --- seeds. docs/database.md forbids triggers, functions, and foreign keys. +-- subdirectories: `types/`, `sequences/`, `partitions/`, and `seeds/`. This +-- file composes them into one fresh database, in load order: types → +-- sequences → tables → partitions → seeds. docs/database.md forbids +-- triggers, functions, and foreign keys. -- -- `./bin/pgschema apply --file schema/schema.sql` resolves the `\i` includes -- relative to this file (it refuses `..`). `pgschema` skips INSERTs and some @@ -60,6 +61,7 @@ CREATE EXTENSION IF NOT EXISTS pgcrypto; \i types/subscription_status.sql \i types/pause_reason.sql \i types/channel_add_policy.sql +\i sequences/search_index_version.sql -- tables \i tables/public/communities.sql @@ -97,6 +99,7 @@ CREATE EXTENSION IF NOT EXISTS pgcrypto; \i tables/public/push_leases.sql \i tables/public/push_wake_outbox.sql \i tables/public/push_match_queue.sql +\i tables/public/search_backfill.sql \i tables/public/search_outbox.sql \i tables/public/push_gateway_challenges.sql \i tables/public/push_gateway_installations.sql diff --git a/schema/sequences/search_index_version.sql b/schema/sequences/search_index_version.sql new file mode 100644 index 0000000000..c634dbca99 --- /dev/null +++ b/schema/sequences/search_index_version.sql @@ -0,0 +1,11 @@ +-- The external version the search indexer writes with each batch (see +-- crates/buzz-db/src/store/search_outbox.rs). While a primary runs, a +-- sequence never hands out a value twice, so a batch's version is larger +-- than that of every batch before it. It can repeat values after a crash, +-- since a value read by a transaction that has not committed is not yet +-- durable, and after promoting an asynchronous replica; see +-- docs/opensearch-search-deployment.md for what that does to the index. +-- OpenSearch accepts an external version only above the one a document +-- holds, and documents written without one hold small internal versions +-- (one per write), so the sequence starts far above them. +CREATE SEQUENCE search_index_version AS BIGINT START WITH 10000000000000000; diff --git a/schema/tables/public/search_backfill.sql b/schema/tables/public/search_backfill.sql new file mode 100644 index 0000000000..c11d9479d7 --- /dev/null +++ b/schema/tables/public/search_backfill.sql @@ -0,0 +1,17 @@ +-- ── Search backfill ─────────────────────────────────────────────────────────── +-- How far the search indexer has walked each community's searchable events, +-- newest first, queuing their keys in `search_outbox`. The cursor is the +-- (created_at, id) key of the oldest event queued so far; NULL before the +-- first batch. `completed_at` is set once no older event is left. Deleting a +-- community's row backfills it again from its newest event. Keep this table +-- out of logical-replication publications, like `search_outbox`. + +CREATE TABLE search_backfill ( + community_id UUID NOT NULL, + cursor_created_at TIMESTAMPTZ, + cursor_event_id BYTEA CHECK (length(cursor_event_id) = 32), + enqueued BIGINT NOT NULL DEFAULT 0, + completed_at TIMESTAMPTZ, + updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), + PRIMARY KEY (community_id) +);