: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(workflows): sweep conversion watchers in the janitor and raise the default window (#92980)
Daniel Marchuk0c3cd049c27b
diff --git a/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.test.ts b/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.test.tsindex 54186b36ba6a..68626f4a6b68 100644--- a/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.test.ts+++ b/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.test.ts@@ -220,7 +220,6 @@ class MatcherUnderTest extends CdpHogflowSubscriptionMatcherConsumer {// they call have been reset.public clearWatcherTimers(): void {clearInterval((this as any).watcherTeamsRefreshTimer)- clearInterval((this as any).watcherSweepTimer)}}diff --git a/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts b/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.tsindex bbf229f9066d..1d1966a4325b 100644--- a/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts@@ -47,10 +47,6 @@ import { counterParseError } from './metrics'// the first bootstrap and offset-loss edge cases (covered by the deferred lag alerting follow-up).const startAtLatest = START_AT_LATEST-// Expired watchers are not urgent — they have already stopped matching via the expires_at predicate,-// so this only reclaims space.-const WATCHER_SWEEP_INTERVAL_MS = 60_000-// How stale the has-live-watchers gate may be. A team that just enrolled its first run while its only// goal flow was already paused waits at most this long to be admitted.const WATCHER_TEAMS_REFRESH_INTERVAL_MS = 30_000@@ -203,7 +199,6 @@ export class CdpHogflowSubscriptionMatcherConsumer<// the survivor's id so the survivor's person/event updates can wake them.private personDistinctIdKafkaConsumer: KafkaConsumerInterfaceprivate cyclotronPool: Pool- private watcherSweepTimer: NodeJS.Timeout | null = nullprivate watcherTeamsRefreshTimer: NodeJS.Timeout | null = null// Teams with at least one unexpired watcher. Empty until the first refresh, which start() awaits// before consuming, so the gate is never consulted against an unpopulated set.@@ -1092,8 +1087,6 @@ export class CdpHogflowSubscriptionMatcherConsumer<public override async start(): Promise<void> {await super.start()- // Watchers that convert are deleted by the claim; ones that never convert are only removed- // here, so without this the table grows for the lifetime of the deployment.// Awaited so the first batches are gated against a populated set rather than an empty one,// which would drop messages for teams whose only goal flow is paused. A failure here must not// stop the matcher starting: an empty set degrades the gate to its previous flow-only@@ -1108,17 +1101,10 @@ export class CdpHogflowSubscriptionMatcherConsumer<captureException(err)})}, WATCHER_TEAMS_REFRESH_INTERVAL_MS)- this.watcherSweepTimer = setInterval(() => {- void this.invocationResultsService.conversionWatchersService.sweepExpired().catch((err) => {- logger.error('⚠️', 'Conversion watcher sweep failed', { err })- captureException(err)- })- }, WATCHER_SWEEP_INTERVAL_MS)- // Neither timer is work the process should stay alive for: both are periodic maintenance that- // the next start picks up. Unref'd, a consumer that was started but never stopped cannot hold- // the event loop open — which is what a leaked one does to a long single-process test run.+ // Not work the process should stay alive for: periodic maintenance that the next start picks+ // up. Unref'd, a consumer that was started but never stopped cannot hold the event loop open —+ // which is what a leaked one does to a long single-process test run.this.watcherTeamsRefreshTimer.unref()- this.watcherSweepTimer.unref()// Surface failures to each kafka consumer so the offset doesn't advance past a batch we// couldn't match. The pod will crash and replay; the SELECT is read-only and the UPDATE// (with `status = 'available'` guards) is idempotent, so replay is safe. All three streams@@ -1158,9 +1144,6 @@ export class CdpHogflowSubscriptionMatcherConsumer<public override async stop(): Promise<void> {logger.info('💤', `Stopping ${this.name}...`)- if (this.watcherSweepTimer) {- clearInterval(this.watcherSweepTimer)- }if (this.watcherTeamsRefreshTimer) {clearInterval(this.watcherTeamsRefreshTimer)}diff --git a/nodejs/src/cdp/services/conversion-watchers/conversion-watchers.service.ts b/nodejs/src/cdp/services/conversion-watchers/conversion-watchers.service.tsindex 04a6b9cb1c82..4c3aa8dd3bca 100644--- a/nodejs/src/cdp/services/conversion-watchers/conversion-watchers.service.ts+++ b/nodejs/src/cdp/services/conversion-watchers/conversion-watchers.service.ts@@ -16,11 +16,6 @@ const counterConversionWatchersFailed = new Counter({help: 'Watcher rows dropped because the insert failed. Each one is a run whose conversion can never be counted, so the conversion rate under-reports by exactly this much.',})-const counterConversionWatchersSwept = new Counter({- name: 'cdp_conversion_watchers_swept',- help: 'Expired watcher rows deleted. These are runs that reached the end of their attribution window without converting.',-})-const gaugeConversionWatchersPending = new Gauge({name: 'cdp_conversion_watchers_pending_rows',help: 'Watcher rows queued in memory waiting for the next flush. Resets to 0 after each flush.',@@ -30,15 +25,12 @@ const gaugeConversionWatchersPending = new Gauge({// binds 10.const INSERT_CHUNK_SIZE = 1000-// Bounds one sweep so a long-neglected table can't lock a huge delete; the interval simply runs again.-const SWEEP_LIMIT = 10000-/**- * Owns the `conversion_watchers` table: writes a watcher when a run enrolls, and deletes expired ones.+ * Writes a watcher row when a run enrolls.** Reading and claiming watchers belongs to the subscription matcher, which is where the event stream- * is. This service is the write side, wired into `InvocationResultsService` alongside the other- * result-borne row sinks.+ * is, and deleting expired ones belongs to the cyclotron janitor. This service is the write side,+ * wired into `InvocationResultsService` alongside the other result-borne row sinks.*/export class ConversionWatchersService {private queuedRows: ConversionWatcherRow[] = []@@ -78,9 +70,9 @@ export class ConversionWatchersService {// Set first so a flush that has not started yet gets no pool and drops its rows through the// failure counter, rather than opening a connection this method is about to close.this.stopped = true- // A flush or a sweep that is already running holds a pool reference and awaits a query. Ending- // the pool under it would fail the work it has not finished, so wait for every one of them.- // Each operation reports its own failure, and shutdown must not re-raise that.+ // A flush that is already running holds a pool reference and awaits a query. Ending the pool+ // under it would fail the work it has not finished, so wait for every one of them. Each+ // operation reports its own failure, and shutdown must not re-raise that.await Promise.all([...this.inFlight].map((operation) => operation.catch(() => {})))const pool = this.poolthis.pool = null@@ -170,29 +162,4 @@ export class ConversionWatchersService {values)}-- /**- * Deletes watchers whose attribution window has closed. Nothing else removes them: a watcher that- * converts is deleted by the claim, and one that never converts would otherwise live forever.- */- public async sweepExpired(): Promise<number> {- return this.track(this.deleteExpiredRows())- }-- private async deleteExpiredRows(): Promise<number> {- const pool = this.getPool()- if (!pool) {- return 0- }- const result = await pool.query(- `DELETE FROM conversion_watchers- WHERE id IN (- SELECT id FROM conversion_watchers WHERE expires_at <= NOW() LIMIT $1- )`,- [SWEEP_LIMIT]- )- const deleted = result.rowCount ?? 0- counterConversionWatchersSwept.inc(deleted)- return deleted- }}diff --git a/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts b/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.tsindex f3f3601c48d1..e8cefbfdecdb 100644--- a/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts+++ b/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts@@ -2535,5 +2535,33 @@ describe('Cyclotron V2', () => {expect(result.depths.get('queue-a')).toBe(2)expect(result.depths.get('queue-b')).toBe(1)})++ it('sweeps expired conversion watchers and keeps live ones', async () => {+ // The sweep is the only thing that removes a watcher that never converts. If a refactor+ // drops it from runOnce the table grows without bound and nothing else fails, so assert+ // the delete happens on a real row.+ const insertWatcher = async (id: string, expiresAt: Date): Promise<void> => {+ await assertPool.query(+ `INSERT INTO conversion_watchers+ (id, team_id, function_id, run_id, distinct_id, goal, expires_at)+ VALUES ($1, 1, $2, $1, $3, $4, $5)`,+ [id, uuidv7(), `sweep-${id}`, JSON.stringify({ events: [] }), expiresAt]+ )+ }+ const expired = uuidv7()+ const live = uuidv7()+ await insertWatcher(expired, new Date(Date.now() - 60_000))+ await insertWatcher(live, new Date(Date.now() + 3_600_000))++ const janitor = createJanitor()+ await janitor.runOnce()++ const remaining = await assertPool.query(`SELECT id FROM conversion_watchers WHERE id = ANY($1::uuid[])`, [+ [expired, live],+ ])+ expect(remaining.rows.map((r) => r.id)).toEqual([live])++ await janitor.stop()+ })})})diff --git a/nodejs/src/cdp/services/cyclotron-v2/janitor.ts b/nodejs/src/cdp/services/cyclotron-v2/janitor.tsindex 685ec53deffc..4944e2916a3d 100644--- a/nodejs/src/cdp/services/cyclotron-v2/janitor.ts+++ b/nodejs/src/cdp/services/cyclotron-v2/janitor.ts@@ -3,6 +3,7 @@ import { Pool } from 'pg'import { Counter, Gauge } from 'prom-client'import { logger } from '~/common/utils/logger'+import { captureException } from '~/common/utils/posthog'import { CYCLOTRON_INVOCATION_JOB_QUEUES, CyclotronJobInvocationHogFlow } from '../../types'import { v2JobToInvocation } from '../job-queue/job-queue-postgres-v2'@@ -63,6 +64,12 @@ const janitorRunCounter = new Counter({help: 'Number of janitor cleanup runs completed',})+// The name is load-bearing: dashboards and alerts query it, so it must not follow the code around.+const conversionWatchersSweptCounter = new Counter({+ name: 'cdp_conversion_watchers_swept',+ help: 'Expired conversion watcher rows deleted. These are runs that reached the end of their attribution window without converting.',+})+const queueDepthGauge = new Gauge({name: 'cdp_cyclotron_v2_queue_depth',help: 'Number of available jobs per queue',@@ -152,6 +159,13 @@ export class CyclotronV2Janitor {}async runOnce(): Promise<CyclotronV2CleanupResult> {+ // Sweep first, before the cyclotron-cleanup stages below. Each of those issues an unguarded+ // pool.query, so a failure specific to cyclotron_jobs (a statement timeout or lock pressure on+ // that hot table) rejects out of runOnce and would skip the sweep for as long as it lasts. The+ // sweep touches a different table and swallows its own errors, so running it up front keeps+ // expired watchers draining even while cyclotron cleanup is failing.+ await this.sweepExpiredConversionWatchers()+const deletedCounts = await this.cleanupTerminalJobs()const deleted = Object.values(deletedCounts).reduce((a, b) => a + b, 0)@@ -471,6 +485,40 @@ export class CyclotronV2Janitor {return count}+ /**+ * Deletes conversion watchers whose attribution window has closed.+ *+ * Nothing else removes them: a watcher that converts is deleted by the matcher's claim, and one+ * that never converts would otherwise live forever. This runs here rather than in the matcher+ * because every matcher pod would run its own copy, all deleting from the same table.+ *+ * A failure is reported to error tracking and swallowed: an expired watcher has already stopped+ * matching via the `expires_at` predicate, so a missed sweep costs space and never a conversion,+ * and it must not stop the janitor finishing its cyclotron work. The report matters because the+ * catch hides the failure from the run otherwise — a persistent one grows the table unbounded.+ */+ async sweepExpiredConversionWatchers(): Promise<number> {+ try {+ const result = await this.pool.query(+ `DELETE FROM conversion_watchers+ WHERE id IN (+ SELECT id FROM conversion_watchers WHERE expires_at <= NOW() LIMIT $1+ )`,+ [this.cleanupBatchSize]+ )+ const deleted = result.rowCount ?? 0+ if (deleted > 0) {+ conversionWatchersSweptCounter.inc(deleted)+ logger.info('CyclotronV2Janitor swept expired conversion watchers', { count: deleted })+ }+ return deleted+ } catch (err) {+ logger.error('CyclotronV2Janitor conversion watcher sweep failed', { error: String(err) })+ captureException(err)+ return 0+ }+ }+async measureQueueDepths(): Promise<Map<string, number>> {const result = await this.pool.query<{ queue_name: string; count: string }>(`SELECT queue_name, COUNT(*) as countdiff --git a/nodejs/src/cdp/services/hogflows/conversion-watcher.ts b/nodejs/src/cdp/services/hogflows/conversion-watcher.tsindex 9a2cfda744fb..33d10dce8cf6 100644--- a/nodejs/src/cdp/services/hogflows/conversion-watcher.ts+++ b/nodejs/src/cdp/services/hogflows/conversion-watcher.ts@@ -62,10 +62,16 @@ export function buildConversionWatcher(invocation: CyclotronJobInvocationHogFlow}}-// A null window means "no explicit window", which cannot mean "forever": the row would never be-// swept and the table would grow without bound. The cap is also what keeps the watcher population-// proportional to recent traffic rather than to all traffic ever.-export const MAX_CONVERSION_WINDOW_MINUTES = 30 * 24 * 60+// What a workflow measures when it sets no explicit window. This answers "how long after entering the+// workflow does a conversion still count", so it is a product choice rather than a storage one. A+// workflow whose own steps run past this can never measure the back half of its own runs.+export const DEFAULT_CONVERSION_WINDOW_MINUTES = 90 * 24 * 60++// The ceiling on an explicitly configured window. It exists only to bound the table: a row that never+// expires is a row the sweep can never reclaim. It cannot sit below the default, or a workflow could+// ask for less than it gets by asking for nothing. Raising it further waits on an unambiguous way to+// express the window, since today's out-of-range values are minutes fields holding second counts.+export const MAX_CONVERSION_WINDOW_MINUTES = 90 * 24 * 60// Substituting our window for the configured one changes what the workflow's conversion rate measures,// so it must not be silent: a clamped run reports over the cap, not over the window it asked for.@@ -77,7 +83,7 @@ const counterConversionWindowClamped = new Counter({function conversionWindowMinutes(hogFlow: HogFlow): number {const configured = hogFlow.conversion?.window_minutesif (!configured || configured <= 0) {- return MAX_CONVERSION_WINDOW_MINUTES+ return DEFAULT_CONVERSION_WINDOW_MINUTES}if (configured > MAX_CONVERSION_WINDOW_MINUTES) {counterConversionWindowClamped.inc()diff --git a/nodejs/src/cdp/services/hogflows/hogflow-conversion-watcher.test.ts b/nodejs/src/cdp/services/hogflows/hogflow-conversion-watcher.test.tsindex 647f1b381d5c..09aa53f7cd83 100644--- a/nodejs/src/cdp/services/hogflows/hogflow-conversion-watcher.test.ts+++ b/nodejs/src/cdp/services/hogflows/hogflow-conversion-watcher.test.ts@@ -4,7 +4,11 @@ import { HogFlow } from '~/cdp/schema/hogflow'import { createExampleHogFlowInvocation } from '../../_tests/fixtures-hogflows'import { CyclotronJobInvocationHogFlow } from '../../types'-import { MAX_CONVERSION_WINDOW_MINUTES, buildConversionWatcher } from './conversion-watcher'+import {+ DEFAULT_CONVERSION_WINDOW_MINUTES,+ MAX_CONVERSION_WINDOW_MINUTES,+ buildConversionWatcher,+} from './conversion-watcher'describe('buildConversionWatcher', () => {const propertyBytecode = ['_H', 1, 32, 'Chrome', 32, '$browser', 32, 'properties', 32, 'person', 1, 3, 11]@@ -72,8 +76,8 @@ describe('buildConversionWatcher', () => {})it.each([- ['an unbounded window', null, MAX_CONVERSION_WINDOW_MINUTES],- ['a window longer than the cap', 60 * 24 * 90, MAX_CONVERSION_WINDOW_MINUTES],+ ['no configured window', null, DEFAULT_CONVERSION_WINDOW_MINUTES],+ ['a window longer than the cap', 60 * 24 * 400, MAX_CONVERSION_WINDOW_MINUTES],['a window inside the cap', 60, 60],])('expires after %s', (_name, windowMinutes, expectedMinutes) => {// Treating null as "forever" would leave rows the expiry sweep can never reach.