Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(cdp-cyclotron): add migrations for email fair-dequeue (#64284)

Meikel Ratzf0169464ff0e
diff --git a/rust/cyclotron-node-migrations/20260616000001_add_email_fair_dequeue_columns.sql b/rust/cyclotron-node-migrations/20260616000001_add_email_fair_dequeue_columns.sql
new file mode 100644
index 000000000000..1d9afe8901c8
--- /dev/null
+++ b/rust/cyclotron-node-migrations/20260616000001_add_email_fair_dequeue_columns.sql
@@ -0,0 +1,23 @@
+-- Fair dequeue for the email queue, scoped to queue_name='email'.
+--
+-- `dequeue_seq` is a precomputed sort key assigned at insert time so the
+-- email worker's dequeue ORDER BY stays cheap (no window functions, no
+-- recursive CTEs). It interleaves jobs across tenants: each tenant's first
+-- job sorts together, then each tenant's second job, etc. A new tenant's
+-- single email no longer waits behind another tenant's 2M-email campaign.
+--
+-- The column is NULL for non-email jobs — completely transparent to the
+-- hog/hogflow worker paths.
+ALTER TABLE cyclotron_jobs
+ ADD COLUMN IF NOT EXISTS dequeue_seq BIGINT;
+
+-- Per-team monotonic counter, used to compute dequeue_seq at insert time:
+-- dequeue_seq = counter × 16,777,216 + team_id
+--
+-- One row per team that has ever sent an email. BIGINT gives ~5 × 10^11
+-- jobs per team of headroom before sort_number overflow at the chosen
+-- block size (decades at any realistic email volume).
+CREATE TABLE IF NOT EXISTS cyclotron_email_team_seq (
+ team_id INT PRIMARY KEY,
+ counter BIGINT NOT NULL
+);
diff --git a/rust/cyclotron-node-migrations/20260616000002_add_email_fair_dequeue_index.sql b/rust/cyclotron-node-migrations/20260616000002_add_email_fair_dequeue_index.sql
new file mode 100644
index 000000000000..6e5eb2b4a245
--- /dev/null
+++ b/rust/cyclotron-node-migrations/20260616000002_add_email_fair_dequeue_index.sql
@@ -0,0 +1,14 @@
+-- no-transaction
+--
+-- Partial index supporting the email worker's fair dequeue ORDER BY.
+-- Tight predicate: only covers email rows that are actually dequeueable.
+-- Hog, hogflow, and any future queues never touch this index — their
+-- dequeue continues to use idx_cyclotron_jobs_dequeue as before.
+--
+-- `NULLS FIRST` matches the worker's `ORDER BY dequeue_seq ASC NULLS FIRST`
+-- in `fairDequeueJobs`. Without aligning the index sort to the query, the
+-- planner can't use the index to satisfy the ORDER BY and falls back to a
+-- full sort of the available set on every dequeue.
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_cyclotron_jobs_email_fair_dequeue
+ ON cyclotron_jobs (dequeue_seq NULLS FIRST)
+ WHERE status = 'available' AND queue_name = 'email';