: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(cdp): park cap-denied emails until the bucket's refill horizon (#97618)
Meikel Ratz346cf1030a92
diff --git a/docs/internal/workflows-email-sending-tiers.md b/docs/internal/workflows-email-sending-tiers.mdindex f82ee1090b94..6914badeaa51 100644--- a/docs/internal/workflows-email-sending-tiers.md+++ b/docs/internal/workflows-email-sending-tiers.md@@ -58,5 +58,11 @@ Decay, suspension drops, admin recomputes, and the backfill stay silent.- The batch audience cap is decided when the batch is dispatched. Adding an email step to the workflow while a batch is queued does not re-cap it; the send-time buckets still cap every email at execution. This is why enforcement requires the worker caps to be deployed (see the rollout order).- Test-panel sends bypass the team buckets on purpose, matching the per-workflow rate limit.- The buckets are token buckets: a full idle bucket plus refill allows up to roughly twice the stated cap in the very first period. The bucket TTLs exceed the refill periods so this does not recur from idling.+- A denied send parks until every short bucket has refilled enough to cover it, instead of retrying on a fixed few-minute cadence.+ The computed wait is capped at one hour and then jittered 1x to 2x, so a parked send can wait just under two hours between attempts.+ The wait reserves nothing: a competing send can take the tokens first, and the send parks again.+ Capacity that arrives early is only noticed when the send wakes.+ After a manual tier raise, a capped team's backlog can sit still for up to two hours.+ A send denied because the limiter itself failed keeps the shorter token bucket cadence, at most 5 to 10 minutes.- Gmail provides no per-message feedback loop, so complaint rates (ours and AWS's) cannot see Gmail complaints at all.- The `HOGFLOW_BATCH_TRIGGER_ELEVATED_TEAM_IDS` allowlist elevates a team to the top tier in Django only: the UI, the admin, and the batch audience cap show top-tier numbers, but the worker's send-time buckets read the stored tier. An allowlisted team below the top tier is therefore throttled at its stored tier while being told otherwise, and its shadow-mode delay counts overstate real impact. Before enforcing, pin each allowlisted team at the top tier from the Django admin and empty the allowlist, rather than plumbing the list into the worker.diff --git a/nodejs/src/cdp/services/messaging/email.service.test.ts b/nodejs/src/cdp/services/messaging/email.service.test.tsindex ddbbb30752bf..4b16a4257294 100644--- a/nodejs/src/cdp/services/messaging/email.service.test.ts+++ b/nodejs/src/cdp/services/messaging/email.service.test.ts@@ -5,6 +5,7 @@ import { MessageRejected, SendingPausedException, TooManyRequestsException } froimport { createExampleInvocation, insertIntegration } from '~/cdp/_tests/fixtures'import { CyclotronInvocationQueueParametersEmailType } from '~/cdp/schema/cyclotron'import { CyclotronJobInvocationHogFunction } from '~/cdp/types'+import { createRedisV2PoolFromConfig } from '~/common/redis/redis-v2'import { closeHub, createHub } from '~/common/utils/db/hub'import { PostgresUse } from '~/common/utils/db/postgres'import { waitForExpect } from '~/tests/helpers/expectations'@@ -470,12 +471,12 @@ describe('EmailService', () => {})describe('workflow sending rate limit', () => {- let claimUpTo: jest.Mock+ let claimOrReserve: jest.Mocklet limitedService: EmailServicelet limitedSendSpy: jest.SpyInstancebeforeEach(() => {- claimUpTo = jest.fn().mockResolvedValue(1)+ claimOrReserve = jest.fn().mockResolvedValue({ granted: 1, retryAfterMs: null, reserved: false })limitedService = new EmailService({sesAccessKeyId: hub.SES_ACCESS_KEY_ID,@@ -493,7 +494,7 @@ describe('EmailService', () => {new EmailSuppressionService(hub.postgres, emailSuppressionConfigFromEnv()),new RecipientsManagerService(hub.postgres),undefined,- { claimUpTo } as unknown as RateLimiterService+ { claimOrReserve } as unknown as RateLimiterService)limitedSendSpy = jest.spyOn(limitedService.sesV2Client!, 'send') as anylimitedSendSpy.mockResolvedValue({ MessageId: 'test-message-id' })@@ -502,11 +503,32 @@ describe('EmailService', () => {}})- it('reschedules without sending when the bucket denies a token', async () => {- claimUpTo.mockResolvedValue(0)+ it.each([+ // A reserved slot means "your turn is at this exact time". Park on it as-is:+ // wake earlier and the token is not there yet, so the send gets denied again+ // and goes to the back of the line.+ ['exactly at the reserved slot', 5000, true, 5000, 5000],+ // Sub-second slots too: flooring them to 1s would push the wake off its+ // slot and collide it with the slot behind.+ ['exactly at a sub-second reserved slot', 500, true, 500, 500],+ // Past the horizon there are no slots left and everyone gets the same "come+ // back in an hour", so those wakes get spread out (1x-2x) instead.+ [+ 'with spread when re-contending at the horizon',+ 60 * 60 * 1000,+ false,+ 60 * 60 * 1000,+ 2 * 60 * 60 * 1000,+ ],+ // No horizon at all (error-path denial) falls back to the clamped token+ // interval: 120/minute refills every 500ms, clamped to [1s, 2s] jittered.+ ['on the clamped token interval when the limiter could not reserve', null, false, 1000, 2000],+ ])('reschedules a denied send %s', async (_name, retryAfterMs, reserved, minDelayMs, maxDelayMs) => {+ claimOrReserve.mockResolvedValue({ granted: 0, retryAfterMs, reserved })const before = Date.now()const result = await limitedService.executeSendEmail(invocation)+ const after = Date.now()expect(limitedSendSpy).not.toHaveBeenCalled()expect(result.error).toBeUndefined()@@ -515,25 +537,70 @@ describe('EmailService', () => {// The reschedule must carry the email payload forward: without queueParameters the// retry has nothing to send and the throttled email is dropped rather than delayed.expect(result.invocation.queueParameters).toEqual(invocation.queueParameters)- // 120/minute refills a token every 500ms, so the clamped jittered wake lands in [1s, 2s].+ // Bracketed against both ends of the call, so the bounds hold the delay itself+ // and not the time the call took.const scheduledMs = result.invocation.queueScheduledAt!.toMillis()- expect(scheduledMs).toBeGreaterThanOrEqual(before + 1000)- expect(scheduledMs).toBeLessThan(before + 3000)+ expect(scheduledMs).toBeGreaterThanOrEqual(before + minDelayMs)+ expect(scheduledMs).toBeLessThanOrEqual(after + maxDelayMs)// No business metric on a pacing delay — the eventual send produces email_sent.expect(result.metrics ?? []).toEqual([])})+ it('parks consecutive denials on their exact reserved slots', async () => {+ // At 30/minute the limiter hands out slots 2s apart. Each send has to wake at+ // its own slot, exactly. If one wake moves even a little earlier, its token is+ // not there yet and the send goes to the back of the line.+ invocation.hogFunction.metadata = { email_sending_rate_limit: { count: 30, period: 'minute' } }+ const slotMs = 2000++ for (let i = 1; i <= 3; i++) {+ claimOrReserve.mockResolvedValue({ granted: 0, retryAfterMs: i * slotMs, reserved: true })++ const before = Date.now()+ const denied = await limitedService.executeSendEmail(invocation)+ const after = Date.now()++ expect(denied.finished).toBe(false)+ const parkedAt = denied.invocation.queueScheduledAt!.toMillis()+ expect(parkedAt).toBeGreaterThanOrEqual(before + i * slotMs)+ expect(parkedAt).toBeLessThanOrEqual(after + i * slotMs)+ }+ })++ it('scatters a backlog that overflows the reservation horizon', async () => {+ // When the backlog is deeper than one hour of refill there are no slots left:+ // every remaining send gets "come back in an hour". If they all came back at+ // the same moment they would pile up at the front of the queue again, so their+ // wakes get spread out over the hour.+ claimOrReserve.mockResolvedValue({ granted: 0, retryAfterMs: 60 * 60 * 1000, reserved: false })++ const parkedAt: number[] = []+ for (let i = 0; i < 20; i++) {+ const denied = await limitedService.executeSendEmail(invocation)+ expect(denied.finished).toBe(false)+ parkedAt.push(denied.invocation.queueScheduledAt!.toMillis())+ }++ // The wakes must cover a real part of the hour, not one narrow window:+ // 20 of them spread over an hour should easily span more than 10 minutes.+ const spreadMs = Math.max(...parkedAt) - Math.min(...parkedAt)+ expect(spreadMs).toBeGreaterThan(10 * 60 * 1000)+ })+it('claims one token scoped to the workflow and sends when granted', async () => {const result = await limitedService.executeSendEmail(invocation)- expect(claimUpTo).toHaveBeenCalledWith({- key: `@posthog/workflow-email-rate/${team.id}/function-1`,- requested: 1,- // Burst capacity is ~1s of budget (not the count), so the first period can't- // send ~2x the limit and an idle-expired bucket can't re-burst.- capacity: 2,- refillPerSecond: 2,- })+ expect(claimOrReserve).toHaveBeenCalledWith(+ {+ key: `@posthog/workflow-email-rate/${team.id}/function-1`,+ requested: 1,+ // Burst capacity is ~1s of budget (not the count), so the first period can't+ // send ~2x the limit and an idle-expired bucket can't re-burst.+ capacity: 2,+ refillPerSecond: 2,+ },+ 60 * 60 * 1000+ )expect(result.finished).toBe(true)expect(limitedSendSpy).toHaveBeenCalled()})@@ -550,21 +617,180 @@ describe('EmailService', () => {const result = await limitedService.executeSendEmail(invocation)- expect(claimUpTo).not.toHaveBeenCalled()+ expect(claimOrReserve).not.toHaveBeenCalled()expect(result.finished).toBe(true)expect(limitedSendSpy).toHaveBeenCalled()})it('skips the limit for test sends', async () => {- claimUpTo.mockResolvedValue(0)+ claimOrReserve.mockResolvedValue({ granted: 0, retryAfterMs: 5000 })const result = await limitedService.executeSendEmail(invocation, true)- expect(claimUpTo).not.toHaveBeenCalled()+ expect(claimOrReserve).not.toHaveBeenCalled()expect(result.finished).toBe(true)expect(limitedSendSpy).toHaveBeenCalled()})})++ // A workflow over its sending limit must not crowd out anyone else: every denied+ // send parks on its own future slot instead of retrying every second, and a+ // workflow without a limit keeps sending right past the parked backlog.+ describe('a denied backlog cannot crowd out other sends', () => {+ it('spreads denied sends over distinct future slots and leaves unlimited workflows untouched', async () => {+ const redis = createRedisV2PoolFromConfig({+ connection: hub.CDP_REDIS_HOST+ ? {+ url: hub.CDP_REDIS_HOST,+ options: { port: hub.CDP_REDIS_PORT, password: hub.CDP_REDIS_PASSWORD },+ }+ : { url: hub.REDIS_URL },+ poolMinSize: hub.REDIS_POOL_MIN_SIZE,+ poolMaxSize: hub.REDIS_POOL_MAX_SIZE,+ })+ const realLimitedService = new EmailService(+ {+ sesAccessKeyId: hub.SES_ACCESS_KEY_ID,+ sesSecretAccessKey: hub.SES_SECRET_ACCESS_KEY,+ sesRegion: hub.SES_REGION,+ sesEndpoint: hub.SES_ENDPOINT,+ sesTrackedConfigurationSet: hub.SES_TRACKED_CONFIGURATION_SET,+ sesUntrackedConfigurationSet: hub.SES_UNTRACKED_CONFIGURATION_SET,+ },+ hub.integrationManager,+ new TeamWorkflowsConfigService(hub.postgres, hub.pubSub),+ hub.ENCRYPTION_SALT_KEYS,+ hub.SITE_URL,+ new EmailTrackingCodeSigner(hub.ENCRYPTION_SALT_KEYS, hub.CDP_EMAIL_TRACKING_URL),+ new EmailSuppressionService(hub.postgres, emailSuppressionConfigFromEnv()),+ new RecipientsManagerService(hub.postgres),+ undefined,+ new RateLimiterService(redis, { name: 'workflow-email-backlog-test' })+ )+ const realSendSpy = jest.spyOn(realLimitedService.sesV2Client!, 'send') as any+ realSendSpy.mockResolvedValue({ MessageId: 'test-message-id' })++ // 6/minute: refill 0.1 tokens/s, burst capacity 1. Slow enough that the test's+ // own wall-clock time cannot refill a token between the denials below.+ invocation.hogFunction.metadata = { email_sending_rate_limit: { count: 6, period: 'minute' } }++ const first = await realLimitedService.executeSendEmail(invocation)+ expect(first.finished).toBe(true)++ const parkedAt: number[] = []+ for (let i = 0; i < 4; i++) {+ const denied = await realLimitedService.executeSendEmail(invocation)+ expect(denied.finished).toBe(false)+ parkedAt.push(denied.invocation.queueScheduledAt!.toMillis())+ }++ // Each denial must hold its own slot, one token interval (10s) apart. If the+ // parks all landed in the same window, the gaps between them would be near+ // zero or negative and the backlog would wake as one herd.+ for (let i = 1; i < parkedAt.length; i++) {+ const gapMs = parkedAt[i] - parkedAt[i - 1]+ expect(gapMs).toBeGreaterThan(9_000)+ expect(gapMs).toBeLessThan(11_000)+ }++ // A workflow without a limit on the same team sends immediately, regardless of+ // the backlog next to it.+ const other = createExampleInvocation({ team_id: team.id, id: 'function-b' })+ other.id = 'invocation-b'+ other.state.vmState = { stack: [] } as any+ other.queueParameters = createEmailParams({ from: { integrationId: 1 } })+ const otherResult = await realLimitedService.executeSendEmail(other)++ expect(otherResult.finished).toBe(true)+ expect(realSendSpy).toHaveBeenCalledTimes(2)+ })+ })++ describe('team sending cap (enforce mode)', () => {+ let claimAllOrNothingPair: jest.Mock+ let cappedService: EmailService+ let cappedSendSpy: jest.SpyInstance++ beforeEach(() => {+ claimAllOrNothingPair = jest.fn()+ const configService = new TeamWorkflowsConfigService(hub.postgres, hub.pubSub)+ jest.spyOn(configService, 'getEmailSendingTier').mockResolvedValue(0)+ cappedService = new EmailService(+ {+ sesAccessKeyId: hub.SES_ACCESS_KEY_ID,+ sesSecretAccessKey: hub.SES_SECRET_ACCESS_KEY,+ sesRegion: hub.SES_REGION,+ sesEndpoint: hub.SES_ENDPOINT,+ sesTrackedConfigurationSet: hub.SES_TRACKED_CONFIGURATION_SET,+ sesUntrackedConfigurationSet: hub.SES_UNTRACKED_CONFIGURATION_SET,+ teamEmailCapMode: 'enforce',+ teamEmailTierHourlyCaps: [100],+ teamEmailTierDailyCaps: [200],+ },+ hub.integrationManager,+ configService,+ hub.ENCRYPTION_SALT_KEYS,+ hub.SITE_URL,+ new EmailTrackingCodeSigner(hub.ENCRYPTION_SALT_KEYS, hub.CDP_EMAIL_TRACKING_URL),+ new EmailSuppressionService(hub.postgres, emailSuppressionConfigFromEnv()),+ new RecipientsManagerService(hub.postgres),+ undefined,+ null,+ { claimAllOrNothingPair } as unknown as RateLimiterService+ )+ cappedSendSpy = jest.spyOn(cappedService.sesV2Client!, 'send') as any+ cappedSendSpy.mockResolvedValue({ MessageId: 'test-message-id' })+ })++ afterEach(() => {+ jest.restoreAllMocks()+ })++ it.each([+ ['parks the send until the reported refill horizon', 30 * 60 * 1000, 30 * 60 * 1000],+ ['clamps the wake to one hour on a longer horizon', 24 * 60 * 60 * 1000, 60 * 60 * 1000],+ ])('%s', async (_name, retryAfterMs, clampedBaseMs) => {+ claimAllOrNothingPair.mockResolvedValue({ granted: false, deniedIndex: 1, retryAfterMs })++ const before = Date.now()+ const result = await cappedService.executeSendEmail(invocation)++ expect(cappedSendSpy).not.toHaveBeenCalled()+ expect(result.error).toBeUndefined()+ expect(result.finished).toBe(false)+ // The reschedule must carry the email payload forward, same as the workflow limit.+ expect(result.invocation.queueParameters).toEqual(invocation.queueParameters)+ const scheduledMs = result.invocation.queueScheduledAt!.toMillis()+ // Jitter is 1x-2x the clamped horizon; the slack absorbs scheduler overhead.+ expect(scheduledMs).toBeGreaterThanOrEqual(before + clampedBaseMs)+ expect(scheduledMs).toBeLessThan(before + 2 * clampedBaseMs + 5000)+ })++ it('retries on the token bucket cadence when the limiter reports no horizon', async () => {+ // A Valkey fault denies with no horizon. Parking on the daily cap's pacing+ // interval would hold the email long after the limiter recovered.+ jest.spyOn(Math, 'random').mockReturnValue(0)+ claimAllOrNothingPair.mockResolvedValue({ granted: false, deniedIndex: null, retryAfterMs: null })++ const before = Date.now()+ const result = await cappedService.executeSendEmail(invocation)++ expect(cappedSendSpy).not.toHaveBeenCalled()+ expect(result.finished).toBe(false)+ const scheduledMs = result.invocation.queueScheduledAt!.toMillis()+ expect(scheduledMs).toBeGreaterThanOrEqual(before + 5 * 60 * 1000)+ expect(scheduledMs).toBeLessThan(before + 5 * 60 * 1000 + 5000)+ })++ it('sends when the claim is granted', async () => {+ claimAllOrNothingPair.mockResolvedValue({ granted: true, deniedIndex: null, retryAfterMs: null })++ const result = await cappedService.executeSendEmail(invocation)++ expect(result.finished).toBe(true)+ expect(cappedSendSpy).toHaveBeenCalled()+ })+ })})describe('native email sending with maildev', () => {let invocation: CyclotronJobInvocationHogFunctiondiff --git a/nodejs/src/cdp/services/messaging/email.service.ts b/nodejs/src/cdp/services/messaging/email.service.tsindex 81385170da33..dd7a50fc0177 100644--- a/nodejs/src/cdp/services/messaging/email.service.ts+++ b/nodejs/src/cdp/services/messaging/email.service.ts@@ -1,7 +1,7 @@import { MessageHeader, SESv2Client, SendEmailCommand, SendEmailCommandInput } from '@aws-sdk/client-sesv2'import { DateTime } from 'luxon'import { SendMailOptions } from 'nodemailer'-import { Counter } from 'prom-client'+import { Counter, Histogram } from 'prom-client'import { CyclotronInvocationQueueParametersEmailType } from '~/cdp/schema/cyclotron'import { HogFlowEmailSendingRateLimit, HogFlowEmailSendingRateLimitSchema } from '~/cdp/schema/hogflow'@@ -110,6 +110,56 @@ function pickTokenBucketRetryDelayMs(refillPerSecond: number): number {return Math.floor(baseMs * (1 + Math.random()))}+// Bounds for the non-reserved cap retry delays (fallbacks and horizon overflow; a+// reserved slot is parked on exactly). The floor keeps second-scale refills from+// churning the queue. The ceiling bounds how stale the computed wake time can get:+// capacity can appear earlier than computed (a limit raise, or an idle bucket+// expiring back to full capacity), and a parked job only notices when it wakes.+const CAP_RETRY_MIN_MS = 1_000+const CAP_RETRY_MAX_MS = 60 * 60 * 1_000++function pickCapRetryDelayMs(retryAfterMs: number | null, refillPerSecond: number): number {+ // A denial with no horizon means the limiter itself failed, not that the cap was reached.+ // Valkey recovers in seconds, but a daily cap paces in hours, so that bucket's refill is the+ // wrong clock for this wake. Use the token-bucket cadence, which has a much shorter ceiling.+ if (retryAfterMs === null) {+ return pickTokenBucketRetryDelayMs(refillPerSecond)+ }+ // The 1x-2x jitter spreads re-claims so a parked backlog does not wake on the same instant.+ const clampedMs = Math.min(Math.max(retryAfterMs, CAP_RETRY_MIN_MS), CAP_RETRY_MAX_MS)+ return Math.floor(clampedMs * (1 + Math.random()))+}++// How far denied sends park. Everything at or below the top bucket is a real slot.+// Above the top bucket is overflow: the backlog is deeper than one hour of refill.+// A sustained rate up there means a team queues more email than its limit can send.+const emailReservedParkMs = new Histogram({+ name: 'cdp_email_reserved_park_ms',+ help: 'How far into the future a rate-limit-denied email parked, by limiter.',+ labelNames: ['limiter'],+ buckets: [1_000, 5_000, 15_000, 60_000, 300_000, 900_000, 1_800_000, 3_600_000],+})++function pickReservedRetryDelayMs(retryAfterMs: number | null, refillPerSecond: number, reserved: boolean): number {+ // No horizon means the limiter itself failed, not that the bucket was empty.+ // Wake on the short token-bucket cadence, not on a cap that paces in hours.+ if (retryAfterMs === null) {+ return pickTokenBucketRetryDelayMs(refillPerSecond)+ }+ // A reserved slot is the caller's own, exactly one token interval behind the slot+ // in front. Park on it as-is, with no floor: waking off the slot in either+ // direction means the token is not there (the bucket banks no surplus), the send+ // gets denied again, and it goes to the back of the line.+ if (reserved) {+ return retryAfterMs+ }+ const parkMs = Math.max(retryAfterMs, CAP_RETRY_MIN_MS)+ // Past the horizon nothing is reserved: every overflow caller got this same wake+ // time back. Spread them over the next horizon so they do not arrive as one herd+ // asking for tokens that will not be there.+ return Math.floor(parkMs * (1 + Math.random()))+}+const teamEmailCapDelayedTotal = new Counter({name: 'cdp_team_email_cap_delayed_total',help: 'Workflow email sends delayed by the team trust-tier sending cap (or that would have been, in shadow mode).',@@ -406,13 +456,16 @@ export class EmailService {// A near-empty bucket keeps every window at ~count and spreads sends evenly, which// is what the pacing is for.const capacity = Math.max(1, Math.ceil(refillPerSecond))- const granted = await this.workflowEmailRateLimiter.claimUpTo({- key: `@posthog/workflow-email-rate/${invocation.teamId}/${invocation.functionId}`,- requested: 1,- capacity,- refillPerSecond,- })- if (granted === 0) {+ const claim = await this.workflowEmailRateLimiter.claimOrReserve(+ {+ key: `@posthog/workflow-email-rate/${invocation.teamId}/${invocation.functionId}`,+ requested: 1,+ capacity,+ refillPerSecond,+ },+ CAP_RETRY_MAX_MS+ )+ if (claim.granted === 0) {workflowEmailRateLimitedTotal.inc()result.finished = false// Re-attach the email payload before rescheduling. createInvocationResult cleared@@ -421,7 +474,8 @@ export class EmailService {// send. Mirrors the fetch-retry (`result.invocation.queueParameters = params`) and// queue-routing paths, which re-attach the same way.result.invocation.queueParameters = params- const retryDelayMs = pickTokenBucketRetryDelayMs(refillPerSecond)+ const retryDelayMs = pickReservedRetryDelayMs(claim.retryAfterMs, refillPerSecond, claim.reserved)+ emailReservedParkMs.labels('workflow-email').observe(retryDelayMs)result.invocation.queueScheduledAt = DateTime.utc().plus({ milliseconds: retryDelayMs })addLog('info',@@ -618,7 +672,7 @@ export class EmailService {const denied = buckets[claim.deniedIndex ?? 1]teamEmailCapDelayedTotal.inc({ tier: String(tier), bucket: denied.name, mode })return {- retryDelayMs: pickTokenBucketRetryDelayMs(denied.refillPerSecond),+ retryDelayMs: pickCapRetryDelayMs(claim.retryAfterMs, denied.refillPerSecond),label: denied.label,}}diff --git a/nodejs/src/cdp/services/rate-limiter/rate-limiter.service.test.ts b/nodejs/src/cdp/services/rate-limiter/rate-limiter.service.test.tsindex 106939752259..fe8b83cceb85 100644--- a/nodejs/src/cdp/services/rate-limiter/rate-limiter.service.test.ts+++ b/nodejs/src/cdp/services/rate-limiter/rate-limiter.service.test.ts@@ -209,7 +209,7 @@ describe('RateLimiterService', () => {],30)- expect(claim).toEqual({ granted: true, deniedIndex: null })+ expect(claim).toEqual({ granted: true, deniedIndex: null, retryAfterMs: null })// Both pools were charged: the remainder is all that is left to claim.expect(await limiter.claimUpTo({ key: KEY_A, requested: 50, capacity: 50, refillPerSecond: 0 })).toBe(20)expect(await limiter.claimUpTo({ key: KEY_B, requested: 100, capacity: 100, refillPerSecond: 0 })).toBe(70)@@ -226,11 +226,39 @@ describe('RateLimiterService', () => {],30)- expect(claim).toEqual({ granted: false, deniedIndex: 1 })+ // refillPerSecond 0 means the missing tokens never accrue, so no horizon is reported.+ expect(claim).toEqual({ granted: false, deniedIndex: 1, retryAfterMs: null })expect(await limiter.claimUpTo({ key: KEY_A, requested: 50, capacity: 50, refillPerSecond: 0 })).toBe(50)expect(await limiter.claimUpTo({ key: KEY_B, requested: 10, capacity: 10, refillPerSecond: 0 })).toBe(10)})+ it('reports on denial how long until the missing tokens accrue', async () => {+ // Cold start: the denying bucket holds exactly its capacity of 10, so the request+ // for 30 is missing 20 tokens. At 2 tokens/s that is 10 seconds.+ const claim = await limiter.claimAllOrNothingPair(+ [+ { key: KEY_A, capacity: 50, refillPerSecond: 0 },+ { key: KEY_B, capacity: 10, refillPerSecond: 2 },+ ],+ 30+ )+ expect(claim).toEqual({ granted: false, deniedIndex: 1, retryAfterMs: 10_000 })+ })++ it('reports the slower bucket when both are short', async () => {+ // Both buckets are 20 tokens short of the request. The first one covers that in 10+ // seconds, the second needs 40. Reporting the first would wake the caller while the+ // second still cannot grant, costing a whole extra dequeue and reschedule.+ const claim = await limiter.claimAllOrNothingPair(+ [+ { key: KEY_A, capacity: 10, refillPerSecond: 2 },+ { key: KEY_B, capacity: 10, refillPerSecond: 0.5 },+ ],+ 30+ )+ expect(claim).toEqual({ granted: false, deniedIndex: 0, retryAfterMs: 40_000 })+ })+it('fails closed when the Lua call throws', async () => {const brokenValkey = {useClient: jest.fn().mockRejectedValue(new Error('connection lost')),@@ -244,7 +272,74 @@ describe('RateLimiterService', () => {],5)- expect(claim).toEqual({ granted: false, deniedIndex: null })+ expect(claim).toEqual({ granted: false, deniedIndex: null, retryAfterMs: null })+ })+ })++ describe('claimOrReserve', () => {+ const RESERVE_KEY = `${KEY}/reserve`+ const req = { key: RESERVE_KEY, requested: 1, capacity: 2, refillPerSecond: 2 }++ it('grants normally without reserving a slot', async () => {+ const claim = await limiter.claimOrReserve(req, 60_000)+ expect(claim).toEqual({ granted: 1, retryAfterMs: null, reserved: false })+ })++ it('hands successive denials distinct, later slots', async () => {+ // Drain the bucket so every claim below is a full denial. At 2 tokens/s each+ // reservation advances the slot cursor by 500ms, so three denied callers park+ // at three different times instead of all retrying against the next token.+ await limiter.claimUpTo({ ...req, requested: 2 })++ const first = await limiter.claimOrReserve(req, 60_000)+ const second = await limiter.claimOrReserve(req, 60_000)+ const third = await limiter.claimOrReserve(req, 60_000)++ expect(first.granted).toBe(0)+ expect(first.retryAfterMs).toBeGreaterThan(0)+ // Strictly later each time; the spacing is ~500ms minus wall-clock elapsed+ // between calls, so bound it loosely rather than exactly.+ expect(second.retryAfterMs!).toBeGreaterThan(first.retryAfterMs!)+ expect(third.retryAfterMs!).toBeGreaterThan(second.retryAfterMs!)+ expect(third.retryAfterMs!).toBeLessThanOrEqual(1_500)+ // All three got their own slot, so each can park on it exactly.+ expect([first.reserved, second.reserved, third.reserved]).toEqual([true, true, true])+ })++ it('charges the first denial only for the tokens the bucket is short of', async () => {+ // One token takes 4s to refill. Drain the bucket, wait 1s so a quarter of a+ // token is back, then get denied. The slot must only cover what is still+ // missing (~3s), not the full 4s: the quarter token is credit already earned.+ const partialReq = { key: `${RESERVE_KEY}/partial`, requested: 1, capacity: 1, refillPerSecond: 0.25 }+ await limiter.claimUpTo(partialReq)+ await new Promise((resolve) => setTimeout(resolve, 1_000))++ const denial = await limiter.claimOrReserve(partialReq, 60_000)++ expect(denial.granted).toBe(0)+ expect(denial.reserved).toBe(true)+ // A slow test runner only makes the slot shorter (more refill happened).+ // Charging the full interval would report 4s and fail this bound.+ expect(denial.retryAfterMs).toBeGreaterThan(0)+ expect(denial.retryAfterMs).toBeLessThanOrEqual(3_000)+ })++ it('stops advancing the cursor at the horizon', async () => {+ // One 1s slot fits the 1s horizon. The first denial takes it; everyone after+ // just gets "come back in 1s" with no slot, so the cursor cannot run away.+ const slowReq = { key: `${RESERVE_KEY}/capped`, requested: 1, capacity: 1, refillPerSecond: 1 }+ await limiter.claimUpTo({ ...slowReq })++ const first = await limiter.claimOrReserve(slowReq, 1_000)+ const second = await limiter.claimOrReserve(slowReq, 1_000)+ const third = await limiter.claimOrReserve(slowReq, 1_000)++ expect(first.retryAfterMs).toBeLessThanOrEqual(1_000)+ expect(second.retryAfterMs).toBe(1_000)+ expect(third.retryAfterMs).toBe(1_000)+ // Only the first got a slot. The other two share one wake time and are told so,+ // which is the caller's cue to spread its own wake.+ expect([first.reserved, second.reserved, third.reserved]).toEqual([true, false, false])})})})diff --git a/nodejs/src/cdp/services/rate-limiter/rate-limiter.service.ts b/nodejs/src/cdp/services/rate-limiter/rate-limiter.service.tsindex 272248d86ba9..b173da9fa119 100644--- a/nodejs/src/cdp/services/rate-limiter/rate-limiter.service.ts+++ b/nodejs/src/cdp/services/rate-limiter/rate-limiter.service.ts@@ -34,32 +34,44 @@ const claimLatency = new Histogram({})// Atomic "claim up to" token-bucket script.-// KEYS[1] = bucket hash key (stores `ts` and `pool`)+// KEYS[1] = bucket hash key (stores `ts`, `pool`, and the `resv` slot cursor)// ARGV[1] = requested tokens (integer)// ARGV[2] = pool capacity (max tokens the bucket can hold)// ARGV[3] = refill rate (tokens per second)// ARGV[4] = TTL seconds — bucket auto-expires when idle so cold-start// gives full capacity rather than a stale negative pool.+// ARGV[5] = reserve-on-deny horizon in ms; 0 disables reservation.//// `now` is sourced via `redis.call('TIME')` so all pods share a single// monotonic clock — NTP drift between workers can't over- or under-refill// the bucket on this code path.//-// Returns the number of tokens granted (0..requested).+// Returns {granted, retryAfterMs, reserved}.+//+// The reservation (ARGV[5] > 0), in plain terms: when the bucket says no, it also+// hands the caller a time slot, like a ticket at a counter. The bucket remembers+// the last slot it gave out (`resv`). The first denied caller waits only until the+// missing tokens have refilled. Everyone after that gets the next slot, one token+// interval later. So a denied backlog lines itself up over the future instead of+// everyone retrying at once. No slot is given out further than ARGV[5] ahead; past+// that the caller gets ARGV[5] back with reserved=0 and asks again when it wakes.+// A slot is a place in line, not a promise: the caller still claims when it wakes.const CLAIM_UP_TO_LUA = `local key = KEYS[1]local requested = tonumber(ARGV[1])local capacity = tonumber(ARGV[2])local refillPerSecond = tonumber(ARGV[3])local ttlSeconds = tonumber(ARGV[4])+local reserveOnDenyMaxMs = tonumber(ARGV[5])local time = redis.call('TIME')-- TIME returns {seconds, microseconds}; flatten to epoch ms.local now = tonumber(time[1]) * 1000 + math.floor(tonumber(time[2]) / 1000)-local existing = redis.call('hmget', key, 'ts', 'pool')+local existing = redis.call('hmget', key, 'ts', 'pool', 'resv')local rawTs = existing[1]local rawPool = existing[2]+local rawResv = existing[3]local availableif rawTs == false then@@ -92,7 +104,29 @@ local tokensAfter = available - grantedredis.call('hset', key, 'ts', now, 'pool', tokensAfter)redis.call('expire', key, ttlSeconds)-return granted+if granted > 0 or reserveOnDenyMaxMs <= 0 or refillPerSecond <= 0 then+ return {granted, 0, 0}+end++-- First in line: wait only for the tokens that are actually missing. A partly+-- refilled bucket is credit the caller already earned, and waiting a full interval+-- on top would throw that credit away (the pool caps at capacity). Behind someone:+-- take the slot after theirs, one full token interval later.+local slotAt+if rawResv ~= false and tonumber(rawResv) > now then+ slotAt = tonumber(rawResv) + (requested / refillPerSecond) * 1000+else+ local deficit = requested - available+ if deficit < 0 then+ deficit = 0+ end+ slotAt = now + (deficit / refillPerSecond) * 1000+end+if slotAt - now > reserveOnDenyMaxMs then+ return {0, reserveOnDenyMaxMs, 0}+end+redis.call('hset', key, 'resv', slotAt)+return {0, math.ceil(slotAt - now), 1}`// Atomic all-or-nothing claim across two buckets. Same refill math as CLAIM_UP_TO_LUA per bucket,@@ -104,13 +138,21 @@ return granted// ARGV[1] = requested tokens (integer)// ARGV[2..4] = capacity, refill/sec, TTL seconds for KEYS[1]// ARGV[5..7] = capacity, refill/sec, TTL seconds for KEYS[2]-// Returns {1, 0} on success, {0, i} when bucket i (1-based) is the first that cannot cover it.+// Returns {1, 0, 0} when granted. On denial: {0, i, retryAfterMs}, where i is the+// first bucket (1-based) that came up short and retryAfterMs is how long until BOTH+// buckets have their missing tokens back (the slower one decides). That is a lower+// bound, not a reservation: other callers can take those tokens first, so the wake+// still has to claim. A bucket that never refills has no horizon, and then the+// denial reports none.const CLAIM_ALL_OR_NOTHING_PAIR_LUA = `local time = redis.call('TIME')local now = tonumber(time[1]) * 1000 + math.floor(tonumber(time[2]) / 1000)local requested = tonumber(ARGV[1])local available = {}+local deniedIndex = 0+local retryAfterMs = 0+local horizonKnown = truefor i = 1, 2 dolocal capacity = tonumber(ARGV[(i - 1) * 3 + 2])local refillPerSecond = tonumber(ARGV[(i - 1) * 3 + 3])@@ -130,18 +172,35 @@ for i = 1, 2 doavail = math.min(capacity, currentTokens + (elapsedMs / 1000.0) * refillPerSecond)endif avail < requested then- return {0, i}+ if deniedIndex == 0 then+ deniedIndex = i+ end+ if refillPerSecond > 0 then+ local bucketRetryMs = math.ceil(((requested - avail) / refillPerSecond) * 1000)+ if bucketRetryMs > retryAfterMs then+ retryAfterMs = bucketRetryMs+ end+ else+ horizonKnown = false+ endendavailable[i] = availend+if deniedIndex > 0 then+ if not horizonKnown then+ return {0, deniedIndex, 0}+ end+ return {0, deniedIndex, retryAfterMs}+end+for i = 1, 2 dolocal ttlSeconds = tonumber(ARGV[(i - 1) * 3 + 4])redis.call('hset', KEYS[i], 'ts', now, 'pool', available[i] - requested)redis.call('expire', KEYS[i], ttlSeconds)end-return {1, 0}+return {1, 0, 0}`export interface RateLimiterConfig {@@ -191,6 +250,34 @@ export class RateLimiterService {* the worker's empty-batch sleep instead of crashing.*/public async claimUpTo(req: ClaimRequest): Promise<number> {+ return (await this.evalClaim(req, 0)).granted+ }++ /**+ * Like claimUpTo, but when the bucket says no, the caller also gets a time to come+ * back at. First denial: wait only for the missing tokens. Every denial after that:+ * the next slot, one token interval later. A denied backlog lines itself up over+ * the future instead of everyone retrying at once.+ *+ * Slots only go out up to `reserveOnDenyMs` ahead. Past that, `reserved` is false+ * and `retryAfterMs` is just the horizon: many callers get that same answer, so+ * each one must spread its own wake before parking on it. Only a reserved slot+ * (`reserved` true) is the caller's alone and safe to park on as-is.+ *+ * A slot is a place in line, not a promise. The wake still has to claim.+ * `retryAfterMs` is null on grants and when the limiter itself failed.+ */+ public async claimOrReserve(+ req: ClaimRequest,+ reserveOnDenyMs: number+ ): Promise<{ granted: number; retryAfterMs: number | null; reserved: boolean }> {+ return await this.evalClaim(req, reserveOnDenyMs)+ }++ private async evalClaim(+ req: ClaimRequest,+ reserveOnDenyMs: number+ ): Promise<{ granted: number; retryAfterMs: number | null; reserved: boolean }> {const endTimer = claimLatency.startTimer({ limiter: this.config.name })const ttlSeconds = req.ttlSeconds ?? 3600try {@@ -206,30 +293,35 @@ export class RateLimiterService {String(req.requested),String(req.capacity),String(req.refillPerSecond),- String(ttlSeconds)+ String(ttlSeconds),+ String(reserveOnDenyMs)))- const granted = Number(result)+ const [granted, retryAfterMs, reserved] = Array.isArray(result) ? result.map(Number) : [NaN, NaN, 0]if (!Number.isFinite(granted) || granted < 0) {logger.warn('🪙', `RateLimiterService(${this.config.name}) returned invalid grant`, {key: req.key,raw: result,})claimCounter.inc({ limiter: this.config.name, result: 'valkey_error' })- return 0+ return { granted: 0, retryAfterMs: null, reserved: false }}const outcome = granted === 0 ? 'denied' : granted < req.requested ? 'granted_partial' : 'granted_full'claimCounter.inc({ limiter: this.config.name, result: outcome })- return granted+ return {+ granted,+ retryAfterMs: Number.isFinite(retryAfterMs) && retryAfterMs > 0 ? retryAfterMs : null,+ reserved: reserved === 1,+ }} catch (err) {logger.warn('🪙', `RateLimiterService(${this.config.name}) claim threw`, {key: req.key,error: String(err),})claimCounter.inc({ limiter: this.config.name, result: 'valkey_error' })- return 0+ return { granted: 0, retryAfterMs: null, reserved: false }} finally {endTimer()}@@ -239,7 +331,13 @@ export class RateLimiterService {* Atomically claim `requested` tokens from BOTH buckets, or neither. A denial consumes* nothing, so a caller that retries a multi-token claim cannot drain the buckets while never* succeeding. Returns which bucket denied (index into `buckets`), or null when granted.- * Runtime errors deny with `deniedIndex: null` — fail-closed, like claimUpTo.+ * A denial also carries `retryAfterMs`, the time until every short bucket's refill has+ * accrued its missing tokens. Both buckets are measured, so a pair that is short on the+ * hourly and the daily bucket reports the slower one. It is a lower bound (competing callers+ * may take the tokens first), so callers use it to schedule the retry, never to skip the+ * re-claim.+ * Runtime errors deny with `deniedIndex: null` and `retryAfterMs: null` — fail-closed, like+ * claimUpTo.** On clustered Valkey the two keys must hash to the same slot (give them the same `{...}`* hash tag), because the Lua script touches both keys in one call and the cluster rejects@@ -249,7 +347,7 @@ export class RateLimiterService {public async claimAllOrNothingPair(buckets: [Omit<ClaimRequest, 'requested'>, Omit<ClaimRequest, 'requested'>],requested: number- ): Promise<{ granted: boolean; deniedIndex: 0 | 1 | null }> {+ ): Promise<{ granted: boolean; deniedIndex: 0 | 1 | null; retryAfterMs: number | null }> {const endTimer = claimLatency.startTimer({ limiter: this.config.name })try {const result = await this.valkey.useClient(@@ -270,27 +368,31 @@ export class RateLimiterService {))- const [granted, deniedBucket] = Array.isArray(result) ? result.map(Number) : [NaN, NaN]+ const [granted, deniedBucket, retryAfterMs] = Array.isArray(result) ? result.map(Number) : [NaN, NaN, NaN]if (granted !== 0 && granted !== 1) {logger.warn('🪙', `RateLimiterService(${this.config.name}) pair claim returned invalid result`, {keys: [buckets[0].key, buckets[1].key],raw: result,})claimCounter.inc({ limiter: this.config.name, result: 'valkey_error' })- return { granted: false, deniedIndex: null }+ return { granted: false, deniedIndex: null, retryAfterMs: null }}claimCounter.inc({ limiter: this.config.name, result: granted === 1 ? 'granted_full' : 'denied' })return granted === 1- ? { granted: true, deniedIndex: null }- : { granted: false, deniedIndex: deniedBucket === 2 ? 1 : 0 }+ ? { granted: true, deniedIndex: null, retryAfterMs: null }+ : {+ granted: false,+ deniedIndex: deniedBucket === 2 ? 1 : 0,+ retryAfterMs: Number.isFinite(retryAfterMs) && retryAfterMs > 0 ? retryAfterMs : null,+ }} catch (err) {logger.warn('🪙', `RateLimiterService(${this.config.name}) pair claim threw`, {keys: [buckets[0].key, buckets[1].key],error: String(err),})claimCounter.inc({ limiter: this.config.name, result: 'valkey_error' })- return { granted: false, deniedIndex: null }+ return { granted: false, deniedIndex: null, retryAfterMs: null }} finally {endTimer()}diff --git a/nodejs/src/cdp/services/rate-limiter/rate-limiter.valkey.integration.test.ts b/nodejs/src/cdp/services/rate-limiter/rate-limiter.valkey.integration.test.tsindex ffe9f225b336..b242d722ad00 100644--- a/nodejs/src/cdp/services/rate-limiter/rate-limiter.valkey.integration.test.ts+++ b/nodejs/src/cdp/services/rate-limiter/rate-limiter.valkey.integration.test.ts@@ -41,6 +41,6 @@ describe('RateLimiterService on Valkey Cluster', () => {const limiter = new RateLimiterService(valkeyPool, { name: 'team-email-cluster-test' })const claim = await limiter.claimAllOrNothingPair([buckets[0], buckets[1]], 10)- expect(claim).toEqual({ granted: true, deniedIndex: null })+ expect(claim).toEqual({ granted: true, deniedIndex: null, retryAfterMs: null })})})diff --git a/nodejs/src/cdp/workflows-e2e.serial.test.ts b/nodejs/src/cdp/workflows-e2e.serial.test.tsindex bcfe3b0987a7..57866c2ef5bc 100644--- a/nodejs/src/cdp/workflows-e2e.serial.test.ts+++ b/nodejs/src/cdp/workflows-e2e.serial.test.ts@@ -2642,6 +2642,12 @@ describe('Workflows E2E (email queue)', () => {hub = await createHub()hub.CDP_CYCLOTRON_BATCH_DELAY_MS = 50+ // Without a Valkey host the SES rate limiter pool is null and every sending+ // limit in this block is silently disabled. Point it at the local test Redis.+ hub.SES_RATE_LIMITER_VALKEY_HOST = hub.CDP_REDIS_HOST || '127.0.0.1'+ if (hub.CDP_REDIS_PORT) {+ hub.SES_RATE_LIMITER_VALKEY_PORT = hub.CDP_REDIS_PORT+ }// `.invalid` domains are NXDOMAIN, everything else resolves as deliverable.const nxdomain = () => Promise.reject(Object.assign(new Error('queryMx ENOTFOUND'), { code: 'ENOTFOUND' }))@@ -3454,6 +3460,110 @@ describe('Workflows E2E (email queue)', () => {}, 15000)})+ it("a workflow over its sending limit does not hold up another workflow's emails", async () => {+ // Two workflows on the same team and the same email queue. Workflow A has a+ // sending limit of 2 per minute and gets 8 sends queued at once, so all but the+ // first are denied. Workflow B has no limit and 3 sends. The whole pipeline is+ // real: events consumer -> hogflow worker -> email queue -> email worker ->+ // rate limiter -> reschedule. B's emails must go out while A's denied sends+ // park on their own future slots, each dequeued once, with the job row's+ // transition counter staying low.+ const buildEmailFlow = (triggerEvent: string, recipient: string): HogFlow =>+ new FixtureHogFlowBuilder()+ .withTeamId(team.id)+ .withStatus('active')+ .withExitCondition('exit_only_at_end')+ .withWorkflow({+ actions: {+ trigger: {+ type: 'trigger',+ config: { type: 'event', ...eventNameFilter(triggerEvent) },+ },+ email_1: {+ type: 'function_email',+ config: {+ template_id: 'template-workflows-e2e-email',+ inputs: {+ email: {+ value: {+ to: { email: recipient, name: 'Recipient' },+ from: { integrationId: 1, email: '[email protected]' },+ subject: `To ${recipient}`,+ text: 'Test text',+ html: '<p>Test html</p>',+ },+ },+ },+ },+ },+ exit: { type: 'exit', config: {} },+ },+ edges: [+ { from: 'trigger', to: 'email_1', type: 'continue' },+ { from: 'email_1', to: 'exit', type: 'continue' },+ ],+ })+ .build()++ const flowA = buildEmailFlow('signup_a', '[email protected]')+ const flowB = buildEmailFlow('signup_b', '[email protected]')+ await insertHogFlow(hub.postgres, flowA)+ await insertHogFlow(hub.postgres, flowB)+ // 2 per minute: one burst send, then one slot every 30s. The denied sends park+ // 30s+ out, far past this test's clock, so they stay parked.+ await hub.postgres.query(+ PostgresUse.COMMON_WRITE,+ `UPDATE posthog_hogflow SET email_sending_rate_limit = $1 WHERE id = $2`,+ [JSON.stringify({ count: 2, period: 'minute' }), flowA.id],+ 'set-email-sending-rate-limit'+ )++ const events = [+ ...Array.from({ length: 8 }, (_, i) =>+ createGlobals({ event: 'signup_a', uuid: new UUIDT().toString(), distinct_id: `person_a_${i}` } as any)+ ),+ ...Array.from({ length: 3 }, (_, i) =>+ createGlobals({ event: 'signup_b', uuid: new UUIDT().toString(), distinct_id: `person_b_${i}` } as any)+ ),+ ]+ const { backgroundTask } = await eventsConsumer.processBatch(events)+ await backgroundTask++ // B's 3 runs finish end to end, and A gets its one in-budget send out: 4 sends total.+ await waitForExpect(async () => {+ const jobs = await queryCyclotronJobs()+ const bJobs = jobs.filter((j: any) => j.function_id === flowB.id)+ expect(bJobs.length).toBe(3)+ expect(bJobs.every((j: any) => j.status === 'completed')).toBe(true)++ const sent = mockProducerObserver+ .getProducedKafkaMessagesForTopic(KAFKA_APP_METRICS_2)+ .filter((m: any) => m.value.app_source === 'hog_flow')+ .filter((m: any) => m.value.metric_name === 'email_sent')+ .reduce((sum: number, m: any) => sum + m.value.count, 0)+ expect(sent).toBe(4)+ }, 15000)++ // A's 7 denied sends are parked out of the way: still queued, each on its own+ // future slot, each dequeued exactly once on the email queue.+ const jobs = await queryCyclotronJobs()+ const parkedA = jobs.filter(+ (j: any) => j.function_id === flowA.id && j.queue_name === 'email' && j.status === 'available'+ )+ expect(parkedA.length).toBe(7)+ const slots = parkedA.map((j: any) => new Date(j.scheduled).getTime())+ expect(new Set(slots).size).toBe(7)+ for (const slot of slots) {+ expect(slot).toBeGreaterThan(Date.now() + 20_000)+ }+ // Trigger enqueue, hogflow pass (dequeue + route to email), email pass+ // (dequeue + park) is at most 4 transitions. Anything higher means a+ // denied send went around the loop again.+ for (const job of parkedA) {+ expect(job.transition_count).toBeLessThanOrEqual(4)+ }+ })+it('rate-limited variant processes emails end-to-end through the dedicated bucket', async () => {// Verifies the inject-pattern wiring: CyclotronJobQueueRateLimitedPostgresV2// gates dequeue via a Valkey bucket, then the email worker processes the