Skip to content

Commit 712e890

Browse files
salman1993gems
andauthored
feat(search): park outbox rows OpenSearch rejects and split HTTP 413 bulk requests (#9998)
## Why The search indexer copies messages from Postgres to OpenSearch through the `search_outbox` table (a queue of messages waiting to be indexed). When OpenSearch refuses a document for good, for example a mapping error or a document that is too large, the indexer keeps its row and resends it on every pass. That row: - sits at the head of its community's queue and delays newer messages there; - counts toward the 2,000-row outbox threshold that pauses backfill for every community; - keeps the queue from ever emptying, so operators can't tell the index has caught up. A request-level HTTP 413 (request too large) also failed the whole bulk request, instead of finding the one document that is too large. ## What - Rows that OpenSearch rejects for good are now parked: they leave the active queue and are retried on a slow, separate schedule. - A bulk request that gets HTTP 413 is split in half until the oversized document is alone; only that document is parked. - Mid-pass indexer lease checks stop a relay cleanly if its session advisory lock drops mid-pass, and non-throttled drain errors no longer starve parked-row retries. ## How - **Which failures park.** A per-item 400 or 413 parks that item's row. Per-item 409, 429, 5xx and 404 stay queued and retry as before. A whole-request 400 (the request itself is bad, not a document) leaves every row queued and skips the community for this pass; in a multi-request bulk write, a later whole-request 400 is reported in `BulkOutcome::failed` and retried. - **Schema.** Migration `0110_search_outbox_parked.sql` adds a nullable `parked_at TIMESTAMPTZ` column and three partial indexes: two for active rows (`parked_at IS NULL`) and one for parked rows. - **Reads that ignore parked rows.** Normal claims, `search_outbox::depth`, `search_backfill::outbox_below`, and `outbox_metrics::read` skip parked rows, so they never delay live writes, pause backfill, or inflate active lag/depth metrics. - **Settling a batch.** `SearchOutboxBatch::complete_with` runs inside the batch's Postgres transaction. It deletes rows that succeeded, sets `parked_at = now()` on one row per rejected event, removes stale parked rows for every event the batch settled, and refreshes `parked_at = now()` on transiently failed rows of a parked batch so a stuck parked batch rotates behind the cooldown instead of starving other communities. - **Parked retry.** After each drain (including when `drain()` returns a non-throttled error; skipped when throttled), `Indexer::retry_parked` claims parked rows older than 60 s (by the database clock), 50 at a time. It reads each message's current state again, so an edit or delete settles its parked row. Once a retry writes or removes something, later passes retry parked rows at once in 500-row batches until a retry clears nothing. - **One claim path.** Active and parked claims share `claim_batch_inner` (`ClaimMode::Active` or `ClaimMode::Parked`). Both use the same partition locks, `idle_limit` read and `write_within` time budget from #9996. - **Mid-pass lease checks.** `Indexer::run` wraps `SessionLeader` in a shared `LeaseGuard` and re-checks liveness inside `Indexer::pass` (before `search_backfill::reset()`, `index.create()`, `backfill()`, and `retry_parked_limit()`) and between batches in `drain_worker()`. On lease loss, the pass aborts cleanly without counting as a failure, clears `leading` and `published_parked`, and lets the outer loop re-elect. - **Metric.** A new `buzz_search_outbox_parked{community}` gauge reports parked rows. It drops to 0 when a community clears or when this relay loses the indexer lease. `docs/opensearch-search-deployment.md` documents it along with the index-deletion rollout guidance. ## Risk & Rollout Plan Medium. This changes the live indexer path for every community on relays with `BUZZ_OPENSEARCH_URL` set. Relays without OpenSearch only get the additive migration. A wrong classification parks good rows, but parked rows recover in 500-row batches once a retry succeeds, and the gauge makes them visible. - **Deploy order:** Run migration `0110_search_outbox_parked.sql` before starting any relay with OpenSearch enabled (otherwise `search_outbox::enable` refuses to start because `search_outbox.parked_at` is missing). - **Canary & healthy signals:** Roll out staging / a single relay first, then the remaining relays. Healthy looks like `buzz_search_outbox_depth` draining normally, `buzz_search_index_lag_seconds` staying low, and `buzz_search_outbox_parked` staying at `0` (or isolating only genuinely rejected documents without delaying active writes). - **Rollback:** Rolling back the relay binary is safe. Older relays never read `parked_at`, continue using `search_outbox_queue` / `search_outbox_community_queue`, and simply retry any parked rows as ordinary rows. ## Database checklist (`docs/database.md`) - **Phase:** expand. The column and partial indexes are additive. The two legacy full indexes (`search_outbox_queue`, `search_outbox_community_queue`) are retained in `0110` for rolling-deploy compatibility with older relays and can be dropped in a follow-up cleanup migration once all relays are upgraded. - **Triggers, functions, procedures, rules, foreign keys:** none added. `migrations_after_retirement_add_no_triggers_functions_or_foreign_keys` checks this. - **Data changes:** none in the migration. - **Schema locations:** `migrations/0110_search_outbox_parked.sql`, `schema/tables/public/search_outbox.sql`, and the migration count in `crates/buzz-db/src/runtime/migration.rs`. `admin_schema_parity_between_desired_state_and_migrations` checks column and index parity at the catalog level. - **Deployed relay compatibility:** old relays insert without `parked_at` (it stays `NULL`), never read it, and keep using `search_outbox_queue` and `search_outbox_community_queue`. A new relay with OpenSearch enabled checks for `search_outbox.parked_at` in `search_outbox::enable` and refuses to start if `0110` has not run. - **Lock and statement budgets:** `SET LOCAL lock_timeout = '5s'` and `SET LOCAL statement_timeout = '30s'`. Each index is skipped if `to_regclass` finds it and built inline otherwise. Each is then verified as valid, ready and live, with an exact `pg_get_indexdef` match. On large queues, deployments that apply migrations out of band can prebuild the three indexes with `CREATE INDEX CONCURRENTLY` before running `0110`. ## Testing - Ran locally against Postgres and OpenSearch 2.19.3 on `cb010b0c17` (and `cargo fmt --check` + `cargo check -p buzz-search` on doc-only head `a3b9e89fe0`): - `postgres_opensearch_search`: 44/44 passed (including parked rejection, 413 splitting, cluster-fix/edit/delete recovery, whole-request 400 vs oversized-only batch, parked-retry rotation on 409, and non-throttled drain failure not starving parked retries). - `cargo test -p buzz-search --lib`: 18/18 passed; `cargo test -p buzz-db --lib`: 225/225 passed; `cargo clippy -p buzz-db -p buzz-search --tests -- -D warnings`: clean. - Verified with `curl` against local OpenSearch 2.19 that a bad bulk request parameter (`_bulk?bogus_param=1`) returns a whole-request 400. That is the case that must stay queued, not park. - CI on `a3b9e89fe0`: PostgreSQL Tests (1856/1856), Rust Unit Tests, Rust Lint, Relay E2E, Desktop, and Security checks passed. ## Bigger picture This is part of the OpenSearch search rollout. After deploy, watch `buzz_search_outbox_parked`: a steady non-zero value means documents that OpenSearch keeps refusing, which usually points to a mapping or size limit to fix. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Salman Mohammed <smohammed@squareup.com> Co-authored-by: gems <fd3f5b81c5a75b0b7b88ab01493114227182cc60e16422921001d458d2a64236@buzz.block.builderlab.xyz>
1 parent 423410a commit 712e890

11 files changed

Lines changed: 1324 additions & 237 deletions

File tree

‎crates/buzz-db/src/runtime/migration.rs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1062,7 +1062,8 @@ mod postgres_tests {
10621062
let mut migrations: Vec<_> = MIGRATOR.iter().collect();
10631063
migrations.sort_by_key(|migration| migration.version);
10641064

1065-
assert_eq!(migrations.len(), 109);
1065+
assert_eq!(migrations.len(), 110);
1066+
assert_eq!(migrations[109].version, 110);
10661067
assert_eq!(migrations[108].version, 109);
10671068
assert!(strip_sql_comments(migrations[108].sql.as_str()).contains("'submitted'"));
10681069
assert_eq!(migrations[107].version, 108);

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

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -35,17 +35,18 @@ pub struct BackfillStep {
3535
pub completed: bool,
3636
}
3737

38-
/// Whether the outbox holds fewer than `bound` rows the indexer can drain.
39-
/// Rows of a community fenced for deletion are left out: claims skip them
40-
/// until the purge removes them, so counting them could hold back every
41-
/// other community's backfill for as long as the deletion takes. Reads at
42-
/// most `bound` rows, so it stays cheap however large the queue grows.
38+
/// Whether the outbox holds fewer than `bound` active (unparked) rows the
39+
/// indexer can drain. Rows of a community fenced for deletion and parked
40+
/// rows are left out: normal claims skip them, so counting them could hold
41+
/// back every other community's backfill. Reads at most `bound` rows, so it
42+
/// stays cheap however large the queue grows.
4343
pub async fn outbox_below(pool: &PgPool, bound: i64) -> Result<bool> {
4444
let depth: i64 = sqlx::query_scalar(
4545
"SELECT count(*) FROM ( \
4646
SELECT 1 FROM search_outbox o \
4747
JOIN communities c ON c.id = o.community_id \
4848
WHERE c.deletion_state = 'active' AND c.deleted_at IS NULL \
49+
AND o.parked_at IS NULL \
4950
LIMIT $1 \
5051
) AS bounded",
5152
)

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

Lines changed: 251 additions & 76 deletions
Large diffs are not rendered by default.

0 commit comments

Comments
 (0)