Skip to content

perf(db): split the time-crossings enqueue and enrichment reaper into short statements - #5042

Open
strelov1 wants to merge 1 commit into
mainfrom
perf/outbox-crossings-batches
Open

strelov1 wants to merge 1 commit into
mainfrom
perf/outbox-crossings-batches

Conversation

@strelov1

@strelov1 strelov1 commented Nov 23, 2026 •

Copy link
Copy Markdown
Owner

Why

Two housekeeping statements ran for tens of minutes on prod and held one snapshot the whole time, which stops autovacuum and makes CONCURRENTLY operations wait:

statement calls mean max
EnqueueSearchTimeCrossings (reindex marker-only, 3×/day) 27 1171 s 5141 s
DeleteIneligibleEnrichmentOutbox (start of each hourly enrich run) 141 376 s 6129 s

(pg_stat_statements on core since 2026-11-04.)

What

  • Age crossings → EnqueueSearchAgeCrossings: one UNION of range scans, created_at on jobs_open_created_idx, posted_at on jobs_open_enrich_freshness_idx (written as posted_at IS NOT NULL + COALESCE range, which is exact; a bare posted_at range made the planner skip-scan jobs_company_slug_idx for 185 s).
  • Unseen-window crossings → EnqueueSearchUnseenCrossings: walks job_activity in 1M-row primary-key chunks (last_seen_at stays unindexed on purpose). Each chunk is first cut to the bands of the distinct windows (4 of them, not one per source), so only the rows that may cross reach the jobs lookup. cmd/reindex loops the chunks and moves its cursor only after all of them succeed, as before.
  • Enrichment reaper: one call reads 100k queue entries in job_id order (index-only on the (job_id, target_version) key) and anti-joins jobs_sitemap_idx, the open-and-canonical partial index, which is the claim's own filter. Every live entry of a doomed job is deleted, including a version past the chunk edge. cmd/enrich loops until it has deleted 20k (same bound as before) or reached the end.

All three keep ON CONFLICT DO NOTHING / id order and the dead-letter exemption.

Measurements (prod replica on operator, which other jobs were loading)

before after
time-crossings select, 10 h window 659 s, seq scan of jobs (5.2M blocks) age part 4–70 s (warm/cold) + unseen 7–9 s per 1M-row chunk
reaper select 1089 s for one capped call (594k jobs_pkey probes) 21–35 s per 100k-entry chunk

Equivalence on real data: for the same (since, until], the old query and the two new ones selected the same 37,958 jobs (0 only-old, 0 only-new). Core EXPLAIN (no ANALYZE) shows the same index plans, including the reaper's generic plan.

Tests

  • search_time_reach_integration_test: walks job_activity one row per chunk; adds a job with no job_activity row, a closed crossing and a repost crossing.
  • enrichment_reaper_integration_test: chunk size 1 with a job whose two versions straddle a chunk edge; the bound test goes through the loop.
  • cmd/reindex unit tests: cursor passing between chunks, and a failed chunk keeps the pass cursor.

Note

Medium Risk
Touches scheduled reindex and hourly enrich housekeeping SQL with cursor semantics; equivalence was validated on prod replica but incorrect chunking could miss queues or over-delete in edge cases.

Overview
Replaces two long-running DB housekeeping statements with chunked, cursor-driven passes so each statement finishes in seconds instead of holding a snapshot for tens of minutes (blocking autovacuum and concurrent index work).

Time-crossings enqueue (cmd/reindex): EnqueueSearchTimeCrossings splits into EnqueueSearchAgeCrossings (index-backed UNION of created_at / posted_at age bands) and EnqueueSearchUnseenCrossings (1M-row walks over job_activity with after_id cursors). The reindex worker loops unseen chunks before advancing the pass cursor; failures still block cursor movement.

Enrichment reaper (cmd/enrich): DeleteIneligibleEnrichmentOutbox now takes after_job_id / chunk_size / max_rows, scans the queue in 100k job_id chunks via the outbox index, and returns last_job_id + deleted. Reap loops until the same 20k bound or end of queue.

Tests cover chunk boundaries (multi-version doomed jobs, unseen cursor walks, failed chunks), integration paths mirror production loops, and worker docs reference the new query names.

Reviewed by Cursor Bugbot for commit bc0e49a. Bugbot is set up for automated code reviews on this repo. Configure here.

Summary by CodeRabbit

  • Bug Fixes
    • Large enrichment cleanup runs now process records in bounded batches, helping cleanup continue reliably when queues contain many entries.
    • Time-based search updates now process records in chunks, reducing the chance that eligible listings are missed during reindexing.
    • Closed, duplicate, private, and otherwise ineligible listings are excluded from time-based search updates.
    • Failed batch processing no longer advances the saved progress cursor, allowing the work to be retried.

… short statements

EnqueueSearchTimeCrossings read the whole jobs heap in one statement (41 min on
average on prod) and DeleteIneligibleEnrichmentOutbox probed jobs_pkey for every
queue row (up to 102 min), each holding its snapshot the whole time.

- Age crossings become EnqueueSearchAgeCrossings: range scans on
  jobs_open_created_idx and jobs_open_enrich_freshness_idx, one call.
- Unseen-window crossings become EnqueueSearchUnseenCrossings: job_activity
  walked in 1M-row primary-key chunks, pre-cut to the distinct window bands.
- The enrichment reaper walks the queue in 100k job_id chunks, probing
  jobs_sitemap_idx; the per-run bound of 20k deletions is unchanged.

On the prod replica the old and new enqueue select the same 37,958 jobs for
one window; each new statement runs in seconds there.
@cursor

cursor Bot commented Nov 23, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: d93f7764-4443-46e8-88d1-1b6250ce2a0f)

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-23T03:20:09.144594Z bc0e49a PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@coderabbitai

coderabbitai Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

Enrichment outbox reaping and search time-crossing enqueueing now use bounded chunks and cursors. Search age crossings and unseen-window crossings use separate queries.

Changes: Enrichment Reaping

Layer / File(s) Summary
Cursor-based outbox deletion query
internal/platform/db/queries/enrichment.sql, internal/platform/db/enrichment.sql.go
The query reads job IDs after a cursor and returns the last ID read and the deletion count. It applies separate chunk and deletion limits.
Bounded reaping loop
cmd/enrich/store.go, internal/platform/db/enrichment_reaper_integration_test.go
Reaping accumulates deletions across chunks until it reaches the row limit or receives no further job ID. Integration tests cover successive bounded calls and eligible entries.

Search Time Crossings

Layer / File(s) Summary
Separate age and unseen crossing queries
internal/platform/db/queries/search_outbox.sql, internal/platform/db/search_outbox.sql.go
Age crossings use creation and posting timestamps. Unseen crossings scan activity rows in job-ID chunks and return a cursor and enqueue count.
Crossing enqueue orchestration
cmd/reindex/time_crossings.go, cmd/reindex/time_crossings_test.go, internal/platform/db/search_time_reach_integration_test.go, docs/agents/workers/search.md, internal/search/searchdrain/AGENT-REFERENCE.md
The reindex process enqueues age crossings, then processes unseen crossings in chunks. Tests cover cursor advancement, eligibility, and errors. Documentation names the separate enqueue paths.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Refactor

Sequence Diagram(s)

sequenceDiagram
  participant Reindex as cmd/reindex
  participant Database as Search crossing queries
  participant Cursor as marker_pass_cursors
  Reindex->>Database: EnqueueSearchAgeCrossings
  Database-->>Reindex: affected-row count
  loop Until LastID is zero
    Reindex->>Database: EnqueueSearchUnseenCrossings(AfterID, ChunkSize)
    Database-->>Reindex: LastID and enqueued count
  end
  Reindex->>Cursor: Save cursor after enqueueing succeeds
Loading
Merge Risk: Minimal · up to bc0e4

This change splits two long-running database statements into shorter chunked ones so they hold snapshots for less time. Behavior is meant to be preserved, and no concrete defect was found in the cursor handling, deletion budget or checkpoint logic. Merge risk is minimal.

Pre-merge checks: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title names two real parts of the changeset: the time-crossings enqueue split (EnqueueSearchAgeCrossings and EnqueueSearchUnseenCrossings replacing EnqueueSearchTimeCrossings) and the enrichment r…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title names two real parts of the changeset: the time-crossings enqueue split (EnqueueSearchAgeCrossings and EnqueueSearchUnseenCrossings replacing EnqueueSearchTimeCrossings) and the enrichment reaper split (DeleteIneligibleEnrichmentOutbox now uses cursor-based chunks). The title reflects the stated objective of shortening statements to reduce how long each holds a database snapshot. It uses the conventional perf(db) prefix and is specific enough for a teammate scanning history. It does not name every detail, which is acceptable.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between f978904 and bc0e49a.

Files selected for processing: 11

  • cmd/enrich/store.go
  • cmd/reindex/time_crossings.go
  • cmd/reindex/time_crossings_test.go
  • docs/agents/workers/search.md
  • internal/platform/db/enrichment.sql.go
  • internal/platform/db/enrichment_reaper_integration_test.go
  • internal/platform/db/queries/enrichment.sql
  • internal/platform/db/queries/search_outbox.sql
  • internal/platform/db/search_outbox.sql.go
  • internal/platform/db/search_time_reach_integration_test.go
  • internal/search/searchdrain/AGENT-REFERENCE.md

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 1 remain after this review.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant