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.

refactor(cdp): make the valkey shadow pool a required dependency (#78250)

Ben White9877f847c839
diff --git a/.github/workflows/ci-nodejs.yml b/.github/workflows/ci-nodejs.yml
index 359fbf2fbba4..a620ee6c57af 100644
--- a/.github/workflows/ci-nodejs.yml
+++ b/.github/workflows/ci-nodejs.yml
@@ -386,7 +386,7 @@ jobs:
# seaweedfs backs the blob-store integration tests; the profile-scoped
# stack launch above never starts it (it sits in the replay/agents
# profiles), so start it explicitly here — no profiles overlay in play.
- run: docker compose -f docker-compose.dev.yml up kafka redis7 clickhouse maildev localstack seaweedfs -d --wait
+ run: docker compose -f docker-compose.dev.yml up kafka redis7 valkey-cluster clickhouse maildev localstack seaweedfs -d --wait
- name: Create Kafka topics
run: docker compose -f docker-compose.dev.yml up kafka-init
diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml
index f5875d17408b..f8943e1fbd68 100644
--- a/docker-compose.dev.yml
+++ b/docker-compose.dev.yml
@@ -169,7 +169,6 @@ services:
CDP_REDIS_HOST: redis7
CDP_VALKEY_HOST: valkey-cluster
CDP_VALKEY_PORT: 6379
- CDP_VALKEY_DUAL_ENABLED: 'true'
# Encryption keys default is only set when NODE_ENV=dev, but the image uses production
ENCRYPTION_SALT_KEYS: '00beef0000beef0000beef0000beef00'
# PersonHog is required for CDP — point at the local gRPC router
diff --git a/nodejs/src/cdp/cdp-api.ts b/nodejs/src/cdp/cdp-api.ts
index 0aaf463cca63..b16fce0c17d4 100644
--- a/nodejs/src/cdp/cdp-api.ts
+++ b/nodejs/src/cdp/cdp-api.ts
@@ -126,7 +126,7 @@ export class CdpApi {
private hogFlowExecutor: HogFlowExecutorService
private hogWatcher: HogWatcherService
- private hogWatcherMirror: HogWatcherService | null
+ private hogWatcherMirror: HogWatcherService
private hogTransformer: HogTransformerService
private invocationResultsService: InvocationResultsService
private rerunJobManager: RerunJobManager | null = null
@@ -312,7 +312,7 @@ export class CdpApi {
const summary = await mirrorCompare(
'hog-watcher.getPersistedState',
() => this.hogWatcher.getPersistedState(id),
- () => this.hogWatcherMirror?.getPersistedState(id)
+ () => this.hogWatcherMirror.getPersistedState(id)
)
res.json(summary)
@@ -333,7 +333,7 @@ export class CdpApi {
const summary = await mirrorCompare(
'hog-watcher.getPersistedState',
() => this.hogWatcher.getPersistedState(id),
- () => this.hogWatcherMirror?.getPersistedState(id)
+ () => this.hogWatcherMirror.getPersistedState(id)
)
const hogFunction = await this.hogFunctionManager.fetchHogFunction(id)
@@ -348,7 +348,7 @@ export class CdpApi {
await Promise.all([
this.hogWatcher.forceStateChange(hogFunction, state),
mirrorCall('hog-watcher.forceStateChange', () =>
- this.hogWatcherMirror?.forceStateChange(hogFunction, state)
+ this.hogWatcherMirror.forceStateChange(hogFunction, state)
),
])
}
@@ -360,7 +360,7 @@ export class CdpApi {
await mirrorCompare(
'hog-watcher.getPersistedState',
() => this.hogWatcher.getPersistedState(id),
- () => this.hogWatcherMirror?.getPersistedState(id)
+ () => this.hogWatcherMirror.getPersistedState(id)
)
)
}
@@ -372,7 +372,7 @@ export class CdpApi {
const allStates = await mirrorCompare(
'hog-watcher.getAllFunctionStates',
() => this.hogWatcher.getAllFunctionStates(),
- () => this.hogWatcherMirror?.getAllFunctionStates()
+ () => this.hogWatcherMirror.getAllFunctionStates()
)
// Transform the data for better consumption by Grafana and sort by tokens ascending
diff --git a/nodejs/src/cdp/cdp-services.test.ts b/nodejs/src/cdp/cdp-services.test.ts
index 4f453d305cc0..f72163eb2bf6 100644
--- a/nodejs/src/cdp/cdp-services.test.ts
+++ b/nodejs/src/cdp/cdp-services.test.ts
@@ -1,6 +1,6 @@
import { RedisV2 } from '~/common/redis/redis-v2'
-import { createCdpReaderRedisPool } from './cdp-services'
+import { createCdpReaderRedisPool, createCdpValkeyShadowPools } from './cdp-services'
const mockReaderPool: RedisV2 = {
useClient: jest.fn((_opts, cb) => cb({ ping: () => Promise.resolve('PONG') } as any)),
@@ -107,3 +107,27 @@ describe('createCdpReaderRedisPool', () => {
expect(logMessage).toContain('prod-redis.internal')
})
})
+
+describe('createCdpValkeyShadowPools', () => {
+ const valkeyConfig = {
+ CDP_VALKEY_HOST: 'cdp-valkey.internal',
+ CDP_VALKEY_PORT: 6379,
+ CDP_VALKEY_PASSWORD: 'secret',
+ CDP_VALKEY_READER_HOST: '',
+ CDP_VALKEY_READER_PORT: 6379,
+ CDP_VALKEY_TLS: false,
+ REDIS_POOL_MIN_SIZE: 1,
+ REDIS_POOL_MAX_SIZE: 4,
+ }
+
+ beforeEach(() => {
+ jest.clearAllMocks()
+ })
+
+ it('throws when CDP_VALKEY_HOST is unset', () => {
+ expect(() => createCdpValkeyShadowPools({ ...valkeyConfig, CDP_VALKEY_HOST: '' }, 'test-valkey')).toThrow(
+ 'CDP_VALKEY_HOST is required'
+ )
+ expect(createRedisV2PoolFromConfig).not.toHaveBeenCalled()
+ })
+})
diff --git a/nodejs/src/cdp/cdp-services.ts b/nodejs/src/cdp/cdp-services.ts
index 5de5a3aad7c0..9d6e31cdd9e0 100644
--- a/nodejs/src/cdp/cdp-services.ts
+++ b/nodejs/src/cdp/cdp-services.ts
@@ -68,23 +68,20 @@ export interface CdpValkeyShadowPools {
export interface CdpCoreServices {
redis: RedisV2
/**
- * Shadow Valkey pools used for dual-write/read load testing. Null when
- * CDP_VALKEY_DUAL_ENABLED is false or CDP_VALKEY_HOST is unset. Consumers
- * that build their own redis-backed services (e.g. CdpEventsConsumer's
- * HogRateLimiterService) read this to construct mirror instances bound
- * to the shadow Valkey.
+ * Shadow Valkey pools used for dual-write/read. Consumers that build their own
+ * redis-backed services (e.g. CdpEventsConsumer's HogRateLimiterService) read this
+ * to construct mirror instances bound to the shadow Valkey.
*/
- valkeyShadow: CdpValkeyShadowPools | null
+ valkeyShadow: CdpValkeyShadowPools
hogFunctionManager: HogFunctionManagerService
hogFlowManager: HogFlowManagerService
hogWatcher: HogWatcherService
/**
- * Mirror HogWatcherService bound to the shadow Valkey pool. Null when
- * shadow mode is disabled. Use at call sites alongside `hogWatcher` (via
- * `mirrorCall`) to load-test the new infrastructure. Constructed with
- * `sendEvents: false` so it never emits duplicate billable team events.
+ * Mirror HogWatcherService bound to the shadow Valkey pool. Use at call sites
+ * alongside `hogWatcher` (via `mirrorCall`) to load-test the new infrastructure.
+ * Constructed with `sendEvents: false` so it never emits duplicate billable team events.
*/
- hogWatcherMirror: HogWatcherService | null
+ hogWatcherMirror: HogWatcherService
/** Hog execution with async functions (fetch, email, push). Its `hogExecutor` is the synchronous core. */
hogExecutorAsync: HogExecutorAsyncService
/** Rebuilds the templated/resolved input bundle for a hog function — used by the rerun path to re-derive `inputs` after they're stripped from the persisted payload. */
@@ -128,7 +125,6 @@ export type CdpCoreServicesConfig = Pick<
| 'CDP_VALKEY_PASSWORD'
| 'CDP_VALKEY_READER_HOST'
| 'CDP_VALKEY_READER_PORT'
- | 'CDP_VALKEY_DUAL_ENABLED'
| 'CDP_VALKEY_TLS'
| 'CDP_WATCHER_HOG_COST_TIMING_LOWER_MS'
| 'CDP_WATCHER_HOG_COST_TIMING_UPPER_MS'
@@ -248,8 +244,9 @@ export function createCdpReaderRedisPool(
/**
* Creates writer + reader pools for the shadow Valkey instance used in dual-write/read mode.
- * Returns null when CDP_VALKEY_DUAL_ENABLED is false or CDP_VALKEY_HOST is unset, in which
- * case the shadow path is disabled and behavior is identical to today.
+ * Throws when CDP_VALKEY_HOST is unset: a CDP process that cannot reach Valkey is
+ * misconfigured, and failing at startup surfaces that here rather than as mirror warn logs
+ * from every consumer.
*
* The reader falls back to the writer pool when CDP_VALKEY_READER_HOST is unset.
*/
@@ -261,15 +258,16 @@ export function createCdpValkeyShadowPools(
| 'CDP_VALKEY_PASSWORD'
| 'CDP_VALKEY_READER_HOST'
| 'CDP_VALKEY_READER_PORT'
- | 'CDP_VALKEY_DUAL_ENABLED'
| 'CDP_VALKEY_TLS'
| 'REDIS_POOL_MIN_SIZE'
| 'REDIS_POOL_MAX_SIZE'
>,
name: string
-): CdpValkeyShadowPools | null {
- if (!config.CDP_VALKEY_DUAL_ENABLED || !config.CDP_VALKEY_HOST) {
- return null
+): CdpValkeyShadowPools {
+ if (!config.CDP_VALKEY_HOST) {
+ throw new Error(
+ `[${name}] CDP_VALKEY_HOST is required but unset. Every CDP process dual-writes to Valkey; set CDP_VALKEY_HOST (and CDP_VALKEY_PORT, CDP_VALKEY_TLS as needed) for this deployment.`
+ )
}
logger.info(
@@ -299,7 +297,9 @@ export function createCdpValkeyShadowPools(
poolMaxSize: config.REDIS_POOL_MAX_SIZE,
})
- // Non-blocking startup health check — shadow misconfig must not block startup.
+ // The config is required, but reachability is not fatal: reads still come from the
+ // primary Redis, so an unreachable Valkey must not take CDP down. It stays a
+ // non-blocking check until reads move over.
void writer
.useClient({ name: 'startup-ping', timeout: 5000 }, (client) => client.ping())
.catch((err) => {
@@ -388,14 +388,12 @@ export function createCdpCoreServices(
// so it never emits duplicate billable team events on state transitions; the
// Prom counter `cdp_hog_function_state_change` may double-emit when both pools
// detect the same transition — rare, accepted during dual-write mode.
- const hogWatcherMirror: HogWatcherService | null = valkeyShadow
- ? new HogWatcherService(
- deps.teamManager,
- { ...hogWatcherConfig, sendEvents: false },
- valkeyShadow.writer,
- valkeyShadow.reader
- )
- : null
+ const hogWatcherMirror = new HogWatcherService(
+ deps.teamManager,
+ { ...hogWatcherConfig, sendEvents: false },
+ valkeyShadow.writer,
+ valkeyShadow.reader
+ )
const trackingCodeSigner = new EmailTrackingCodeSigner(config.ENCRYPTION_SALT_KEYS, config.CDP_EMAIL_TRACKING_URL)
const teamWorkflowsConfigService = new TeamWorkflowsConfigService(deps.postgres)
@@ -440,8 +438,8 @@ export function createCdpCoreServices(
backoffMaxMs: config.CDP_FETCH_BACKOFF_MAX_MS,
},
redis,
- messageAssetsService,
- valkeyShadow?.writer ?? null
+ valkeyShadow.writer,
+ messageAssetsService
)
const hogExecutorAsync = new HogExecutorAsyncService(
@@ -476,7 +474,7 @@ export function createCdpCoreServices(
// and EmailValidationService degrades to the local cache + DNS.
const emailValidationService = new EmailValidationService(deps.emailValidationValkey)
// Observer mirrors writes to Valkey (load-only); only the primary path drives metrics.
- const hogFlowDuplicateObserver = new HogFlowDuplicateObserverService(redis, valkeyShadow?.writer ?? null)
+ const hogFlowDuplicateObserver = new HogFlowDuplicateObserverService(redis, valkeyShadow.writer)
const hogFlowExecutor = new HogFlowExecutorService(
hogFlowFunctionsService,
recipientPreferencesService,
diff --git a/nodejs/src/cdp/config.ts b/nodejs/src/cdp/config.ts
index 5f5cdd523105..a0a1a659d1d0 100644
--- a/nodejs/src/cdp/config.ts
+++ b/nodejs/src/cdp/config.ts
@@ -69,16 +69,15 @@ export type CdpConfig = ClickhouseConfig & {
CDP_REDIS_READER_HOST: string
CDP_REDIS_READER_PORT: number
- // Shadow Valkey pool for dual-write/read load testing. When CDP_VALKEY_DUAL_ENABLED
- // is true and CDP_VALKEY_HOST is set, every Redis call also runs against this pool;
- // shadow results are discarded, errors/timeouts logged + counted but never affect
- // the primary code path.
+ // Shadow Valkey pool for dual-write/read. CDP_VALKEY_HOST is required: every CDP
+ // Redis call also runs against this pool, and a process without it is misconfigured
+ // rather than degraded. Shadow results are discarded, and errors/timeouts are logged
+ // and counted but never affect the primary code path.
CDP_VALKEY_HOST: string
CDP_VALKEY_PORT: number
CDP_VALKEY_PASSWORD: string
CDP_VALKEY_READER_HOST: string
CDP_VALKEY_READER_PORT: number
- CDP_VALKEY_DUAL_ENABLED: boolean
// AWS ElastiCache Valkey Serverless requires TLS; toggle off only for local non-TLS test setups.
CDP_VALKEY_TLS: boolean
@@ -237,12 +236,13 @@ export function getDefaultCdpConfig(): CdpConfig {
CDP_REDIS_READER_HOST: '',
CDP_REDIS_READER_PORT: 6379,
- CDP_VALKEY_HOST: '',
- CDP_VALKEY_PORT: 6379,
+ // Points at the `valkey-cluster` compose service, which publishes on 6390 to stay
+ // clear of the 6379 the primary CDP Redis already uses.
+ CDP_VALKEY_HOST: isTestEnv() || isDevEnv() ? '127.0.0.1' : '',
+ CDP_VALKEY_PORT: isTestEnv() || isDevEnv() ? 6390 : 6379,
CDP_VALKEY_PASSWORD: '',
CDP_VALKEY_READER_HOST: '',
CDP_VALKEY_READER_PORT: 6379,
- CDP_VALKEY_DUAL_ENABLED: false,
CDP_VALKEY_TLS: false,
SES_RATE_LIMITER_VALKEY_HOST: '',
diff --git a/nodejs/src/cdp/consumers/cdp-base.consumer.ts b/nodejs/src/cdp/consumers/cdp-base.consumer.ts
index f498382308f6..10531dadc1ac 100644
--- a/nodejs/src/cdp/consumers/cdp-base.consumer.ts
+++ b/nodejs/src/cdp/consumers/cdp-base.consumer.ts
@@ -53,7 +53,7 @@ export interface TeamIDWithConfig {
export abstract class CdpConsumerBase<TConfig extends CdpConsumerBaseConfig = CdpConsumerBaseConfig> {
redis: RedisV2
- valkeyShadow: CdpValkeyShadowPools | null
+ valkeyShadow: CdpValkeyShadowPools
isStopping = false
hogExecutorAsync: HogExecutorAsyncService
@@ -61,7 +61,7 @@ export abstract class CdpConsumerBase<TConfig extends CdpConsumerBaseConfig = Cd
hogFlowExecutor: HogFlowExecutorService
hogMasker: HogMaskerService
hogWatcher: HogWatcherService
- hogWatcherMirror: HogWatcherService | null
+ hogWatcherMirror: HogWatcherService
groupsManager: GroupsManagerService
hogFlowManager: HogFlowManagerService
@@ -109,7 +109,7 @@ export abstract class CdpConsumerBase<TConfig extends CdpConsumerBaseConfig = Cd
this.outputs = services.outputs
// Base-only services
- this.hogMasker = new HogMaskerService(services.redis, services.valkeyShadow?.writer ?? null)
+ this.hogMasker = new HogMaskerService(services.redis, services.valkeyShadow.writer)
this.personsManager = new PersonsManagerService(deps.teamManager, deps.personRepository, config.SITE_URL)
this.groupsManager = new GroupsManagerService(deps.teamManager, deps.groupRepository)
this.pluginDestinationExecutorService = new LegacyPluginExecutorService(deps.postgres, deps.geoipService)
diff --git a/nodejs/src/cdp/consumers/cdp-cyclotron-worker.consumer.ts b/nodejs/src/cdp/consumers/cdp-cyclotron-worker.consumer.ts
index 9d5b818c76da..66b555ea7a2f 100644
--- a/nodejs/src/cdp/consumers/cdp-cyclotron-worker.consumer.ts
+++ b/nodejs/src/cdp/consumers/cdp-cyclotron-worker.consumer.ts
@@ -205,9 +205,7 @@ export class CdpCyclotronWorker<
try {
await Promise.all([
this.hogWatcher.observeResults(invocationResults),
- mirrorCall('hog-watcher.observeResults', () =>
- this.hogWatcherMirror?.observeResults(invocationResults)
- ),
+ mirrorCall('hog-watcher.observeResults', () => this.hogWatcherMirror.observeResults(invocationResults)),
])
} catch (err: any) {
captureException(err)
diff --git a/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.ts b/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.ts
index 347280030d17..8a50218f5cf2 100644
--- a/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.ts
+++ b/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.ts
@@ -442,7 +442,7 @@ export class CdpSourceWebhooksConsumer extends CdpConsumerBase<PluginsServerConf
mirrorCompare(
'hog-watcher.getCachedEffectiveState',
() => this.hogWatcher.getCachedEffectiveState(webhookId),
- () => this.hogWatcherMirror?.getCachedEffectiveState(webhookId)
+ () => this.hogWatcherMirror.getCachedEffectiveState(webhookId)
),
])
@@ -473,9 +473,7 @@ export class CdpSourceWebhooksConsumer extends CdpConsumerBase<PluginsServerConf
void this.promiseScheduler.schedule(
this.invocationResultsService.flush(),
this.hogWatcher.observeResultsBuffered(result),
- mirrorCall('hog-watcher.observeResultsBuffered', () =>
- this.hogWatcherMirror?.observeResultsBuffered(result)
- )
+ mirrorCall('hog-watcher.observeResultsBuffered', () => this.hogWatcherMirror.observeResultsBuffered(result))
)
return result
diff --git a/nodejs/src/cdp/services/batch-export-hog-function.service.ts b/nodejs/src/cdp/services/batch-export-hog-function.service.ts
index 942172ddff1d..2c5a6ed27d47 100644
--- a/nodejs/src/cdp/services/batch-export-hog-function.service.ts
+++ b/nodejs/src/cdp/services/batch-export-hog-function.service.ts
@@ -48,7 +48,7 @@ export class BatchExportHogFunctionService {
private hogExecutorAsync: HogExecutorAsyncService,
private hogWatcher: HogWatcherService,
private invocationResultsService: InvocationResultsService,
- private hogWatcherMirror: HogWatcherService | null = null
+ private hogWatcherMirror: HogWatcherService
) {
this.promiseScheduler = new PromiseScheduler()
}
@@ -101,7 +101,7 @@ export class BatchExportHogFunctionService {
this.invocationResultsService.queueInvocationResultsAndFlush([result]),
this.hogWatcher.observeResultsBuffered(result),
mirrorCall('hog-watcher.observeResultsBuffered', () =>
- this.hogWatcherMirror?.observeResultsBuffered(result)
+ this.hogWatcherMirror.observeResultsBuffered(result)
),
])
)
diff --git a/nodejs/src/cdp/services/hog-flow-invocation-pipeline.service.test.ts b/nodejs/src/cdp/services/hog-flow-invocation-pipeline.service.test.ts
index bb12b16ac5e1..847b81b33a61 100644
--- a/nodejs/src/cdp/services/hog-flow-invocation-pipeline.service.test.ts
+++ b/nodejs/src/cdp/services/hog-flow-invocation-pipeline.service.test.ts
@@ -82,16 +82,19 @@ describe('HogFlowInvocationPipeline', () => {
hogFlowManager,
hogFlowExecutor,
hogWatcher,
- hogWatcherMirror: null,
+ hogWatcherMirror: hogWatcher,
hogMasker,
hogFunctionMonitoringService,
quotaLimiting,
redis: {} as any,
- valkeyShadow: null,
+ valkeyShadow: { writer: {} as any, reader: {} as any },
})
rateLimitGroupedMock = (pipeline as any).hogRateLimiter.rateLimitGrouped as jest.Mock
rateLimitGroupedMock.mockResolvedValue([])
+ // Both pools return the same result while reads still come from the primary, so the
+ // mirror shares the primary's mock rather than drifting to a stale default.
+ ;(pipeline as any).hogRateLimiterMirror.rateLimitGrouped = rateLimitGroupedMock
})
it('returns empty when no hogflows match', async () => {
diff --git a/nodejs/src/cdp/services/hog-flow-invocation-pipeline.service.ts b/nodejs/src/cdp/services/hog-flow-invocation-pipeline.service.ts
index 0fb8cf95f888..95e7c186d125 100644
--- a/nodejs/src/cdp/services/hog-flow-invocation-pipeline.service.ts
+++ b/nodejs/src/cdp/services/hog-flow-invocation-pipeline.service.ts
@@ -35,12 +35,12 @@ export interface HogFlowInvocationPipelineDeps {
hogFlowManager: HogFlowManagerService
hogFlowExecutor: HogFlowExecutorService
hogWatcher: HogWatcherService
- hogWatcherMirror: HogWatcherService | null
+ hogWatcherMirror: HogWatcherService
hogMasker: HogMaskerService
hogFunctionMonitoringService: HogFunctionMonitoringService
quotaLimiting: QuotaLimiting
redis: RedisV2
- valkeyShadow: CdpValkeyShadowPools | null
+ valkeyShadow: CdpValkeyShadowPools
}
/**
@@ -51,7 +51,7 @@ export interface HogFlowInvocationPipelineDeps {
*/
export class HogFlowInvocationPipeline {
private hogRateLimiter: KeyedRateLimiterService
- private hogRateLimiterMirror: KeyedRateLimiterService | null
+ private hogRateLimiterMirror: KeyedRateLimiterService
constructor(
private config: HogFlowInvocationPipelineConfig,
@@ -64,9 +64,7 @@ export class HogFlowInvocationPipeline {
ttlSeconds: config.CDP_RATE_LIMITER_TTL,
}
this.hogRateLimiter = new KeyedRateLimiterService(rateLimiterConfig, deps.redis)
- this.hogRateLimiterMirror = deps.valkeyShadow
- ? new KeyedRateLimiterService(rateLimiterConfig, deps.valkeyShadow.writer)
- : null
+ this.hogRateLimiterMirror = new KeyedRateLimiterService(rateLimiterConfig, deps.valkeyShadow.writer)
}
@instrumented('cdpConsumer.handleEachBatch.queueMatchingFlows')
@@ -113,7 +111,7 @@ export class HogFlowInvocationPipeline {
instrumentFn('cdpConsumer.handleEachBatch.hogWatcher.getEffectiveStates', async () => {
return await this.deps.hogWatcher.getEffectiveStates(hogFlowIds)
}),
- () => this.deps.hogWatcherMirror?.getEffectiveStates(hogFlowIds)
+ () => this.deps.hogWatcherMirror.getEffectiveStates(hogFlowIds)
)
const rateLimitInputs: KeyedRateLimitRequest[] = possibleInvocations.map((x) => ({
@@ -126,7 +124,7 @@ export class HogFlowInvocationPipeline {
instrumentFn('cdpConsumer.handleEachBatch.hogRateLimiter.rateLimitGrouped', async () => {
return await this.hogRateLimiter.rateLimitGrouped(rateLimitInputs)
}),
- () => this.hogRateLimiterMirror?.rateLimitGrouped(rateLimitInputs),
+ () => this.hogRateLimiterMirror.rateLimitGrouped(rateLimitInputs),
(primary, mirror) =>
primary.every(([, result], index) => result.isRateLimited === mirror[index]?.[1].isRateLimited)
)
diff --git a/nodejs/src/cdp/services/hog-function-invocation-pipeline.service.test.ts b/nodejs/src/cdp/services/hog-function-invocation-pipeline.service.test.ts
index 093d223326d2..26f79c584c39 100644
--- a/nodejs/src/cdp/services/hog-function-invocation-pipeline.service.test.ts
+++ b/nodejs/src/cdp/services/hog-function-invocation-pipeline.service.test.ts
@@ -93,16 +93,19 @@ describe('HogFunctionInvocationPipeline', () => {
hogFunctionManager,
hogInputsService: {} as any,
hogWatcher,
- hogWatcherMirror: null,
+ hogWatcherMirror: hogWatcher,
hogMasker,
hogFunctionMonitoringService,
quotaLimiting,
redis: {} as any,
- valkeyShadow: null,
+ valkeyShadow: { writer: {} as any, reader: {} as any },
})
rateLimitGroupedMock = (pipeline as any).hogRateLimiter.rateLimitGrouped as jest.Mock
rateLimitGroupedMock.mockResolvedValue([])
+ // Both pools return the same result while reads still come from the primary, so the
+ // mirror shares the primary's mock rather than drifting to a stale default.
+ ;(pipeline as any).hogRateLimiterMirror.rateLimitGrouped = rateLimitGroupedMock
})
it('returns empty when no hog functions match', async () => {
diff --git a/nodejs/src/cdp/services/hog-function-invocation-pipeline.service.ts b/nodejs/src/cdp/services/hog-function-invocation-pipeline.service.ts
index 108c2b73ac51..848263d9ab81 100644
--- a/nodejs/src/cdp/services/hog-function-invocation-pipeline.service.ts
+++ b/nodejs/src/cdp/services/hog-function-invocation-pipeline.service.ts
@@ -34,12 +34,12 @@ export interface HogFunctionInvocationPipelineDeps {
hogFunctionManager: HogFunctionManagerService
hogInputsService: HogInputsService
hogWatcher: HogWatcherService
- hogWatcherMirror: HogWatcherService | null
+ hogWatcherMirror: HogWatcherService
hogMasker: HogMaskerService
hogFunctionMonitoringService: HogFunctionMonitoringService
quotaLimiting: QuotaLimiting
redis: RedisV2
- valkeyShadow: CdpValkeyShadowPools | null
+ valkeyShadow: CdpValkeyShadowPools
}
export interface BuildHogFunctionInvocationsOptions {
@@ -55,7 +55,7 @@ export interface BuildHogFunctionInvocationsOptions {
*/
export class HogFunctionInvocationPipeline {
private hogRateLimiter: KeyedRateLimiterService
- private hogRateLimiterMirror: KeyedRateLimiterService | null
+ private hogRateLimiterMirror: KeyedRateLimiterService
constructor(
private config: HogFunctionInvocationPipelineConfig,
@@ -68,9 +68,7 @@ export class HogFunctionInvocationPipeline {
ttlSeconds: config.CDP_RATE_LIMITER_TTL,
}
this.hogRateLimiter = new KeyedRateLimiterService(rateLimiterConfig, deps.redis)
- this.hogRateLimiterMirror = deps.valkeyShadow
- ? new KeyedRateLimiterService(rateLimiterConfig, deps.valkeyShadow.writer)
- : null
+ this.hogRateLimiterMirror = new KeyedRateLimiterService(rateLimiterConfig, deps.valkeyShadow.writer)
}
@instrumented('cdpConsumer.handleEachBatch.queueMatchingFunctions')
@@ -111,7 +109,7 @@ export class HogFunctionInvocationPipeline {
instrumentFn('cdpConsumer.handleEachBatch.hogWatcher.getEffectiveStates', async () => {
return await this.deps.hogWatcher.getEffectiveStates(hogFunctionIds)
}),
- () => this.deps.hogWatcherMirror?.getEffectiveStates(hogFunctionIds)
+ () => this.deps.hogWatcherMirror.getEffectiveStates(hogFunctionIds)
)
const rateLimitInputs: KeyedRateLimitRequest[] = possibleInvocations.map((x) => ({
@@ -124,7 +122,7 @@ export class HogFunctionInvocationPipeline {
instrumentFn('cdpConsumer.handleEachBatch.hogRateLimiter.rateLimitGrouped', async () => {
return await this.hogRateLimiter.rateLimitGrouped(rateLimitInputs)
}),
- () => this.hogRateLimiterMirror?.rateLimitGrouped(rateLimitInputs),
+ () => this.hogRateLimiterMirror.rateLimitGrouped(rateLimitInputs),
(primary, mirror) =>
primary.every(([, result], index) => result.isRateLimited === mirror[index]?.[1].isRateLimited)
)
diff --git a/nodejs/src/cdp/services/hogflows/hogflow-duplicate-observer.service.test.ts b/nodejs/src/cdp/services/hogflows/hogflow-duplicate-observer.service.test.ts
index 3e48f17923e3..74f9d570ba3f 100644
--- a/nodejs/src/cdp/services/hogflows/hogflow-duplicate-observer.service.test.ts
+++ b/nodejs/src/cdp/services/hogflows/hogflow-duplicate-observer.service.test.ts
@@ -5,6 +5,7 @@ import { RedisV2, createRedisV2PoolFromConfig } from '~/common/redis/redis-v2'
import { closeHub, createHub } from '~/common/utils/db/hub'
import { Hub } from '~/types'
+import { createCdpValkeyShadowPools } from '../../cdp-services'
import { CyclotronJobInvocationHogFlow } from '../../types'
import { HogFlowDuplicateObserverService } from './hogflow-duplicate-observer.service'
@@ -31,6 +32,7 @@ describe('HogFlowDuplicateObserverService', () => {
let hub: Hub
let redis: RedisV2
+ let valkey: RedisV2
beforeAll(async () => {
hub = await createHub()
@@ -44,6 +46,7 @@ describe('HogFlowDuplicateObserverService', () => {
poolMinSize: hub.REDIS_POOL_MIN_SIZE,
poolMaxSize: hub.REDIS_POOL_MAX_SIZE,
})
+ valkey = createCdpValkeyShadowPools(hub, 'hogflow-duplicate-observer-test').writer
})
afterAll(async () => {
@@ -52,6 +55,7 @@ describe('HogFlowDuplicateObserverService', () => {
beforeEach(async () => {
await deleteKeysWithPrefix(redis, KEY_PREFIX)
+ await deleteKeysWithPrefix(valkey, KEY_PREFIX)
register.resetMetrics()
})
@@ -59,20 +63,20 @@ describe('HogFlowDuplicateObserverService', () => {
(await redis.useClient({ name: 'read' }, (client) => client.get(key))) ?? null
it('is a no-op when redis is null', async () => {
- const observer = new HogFlowDuplicateObserverService(null)
+ const observer = new HogFlowDuplicateObserverService(null, valkey)
await observer.observe(buildInvocation(), buildAction('action-1'))
// Nothing to assert beyond not throwing — verifies the early return.
})
it('is a no-op when invocation has no eventUuid', async () => {
- const observer = new HogFlowDuplicateObserverService(redis)
+ const observer = new HogFlowDuplicateObserverService(redis, valkey)
await observer.observe(buildInvocation({ eventUuid: null }), buildAction('action-1'))
const keys = await redis.useClient({ name: 'keys' }, (client) => client.keys(`${KEY_PREFIX}*`))
expect(keys ?? []).toHaveLength(0)
})
it('writes the key on first observation and does not flag a duplicate', async () => {
- const observer = new HogFlowDuplicateObserverService(redis)
+ const observer = new HogFlowDuplicateObserverService(redis, valkey)
await observer.observe(buildInvocation({ id: 'inv-A' }), buildAction('action-1'))
const stored = await readKey('hogflow:observe:workflow-1:event-1:action-1')
@@ -81,7 +85,7 @@ describe('HogFlowDuplicateObserverService', () => {
})
it('does not flag a duplicate when the same invocation re-observes', async () => {
- const observer = new HogFlowDuplicateObserverService(redis)
+ const observer = new HogFlowDuplicateObserverService(redis, valkey)
const inv = buildInvocation({ id: 'inv-A' })
await observer.observe(inv, buildAction('action-1'))
await observer.observe(inv, buildAction('action-1'))
@@ -90,7 +94,7 @@ describe('HogFlowDuplicateObserverService', () => {
})
it('flags a duplicate when a different invocation hits the same key', async () => {
- const observer = new HogFlowDuplicateObserverService(redis)
+ const observer = new HogFlowDuplicateObserverService(redis, valkey)
await observer.observe(buildInvocation({ id: 'inv-A' }), buildAction('action-1'))
await observer.observe(buildInvocation({ id: 'inv-B' }), buildAction('action-1'))
diff --git a/nodejs/src/cdp/services/hogflows/hogflow-duplicate-observer.service.ts b/nodejs/src/cdp/services/hogflows/hogflow-duplicate-observer.service.ts
index 74f43fa71d74..c0087cb0f28d 100644
--- a/nodejs/src/cdp/services/hogflows/hogflow-duplicate-observer.service.ts
+++ b/nodejs/src/cdp/services/hogflows/hogflow-duplicate-observer.service.ts
@@ -17,14 +17,14 @@ const hogflowDuplicateInvocationDetectedTotal = new Counter({
/**
* Detects duplicate workflow invocations via a Redis SET-NX key per
- * (workflow, event, action). When `redisMirror` is set, every observation also
- * fires against the mirror in parallel — load is realised on the mirror; only
- * the primary drives the duplicate-detected metric.
+ * (workflow, event, action). Every observation also fires against the Valkey mirror
+ * in parallel — load is realised on the mirror; only the primary drives the
+ * duplicate-detected metric.
*/
export class HogFlowDuplicateObserverService {
constructor(
private readonly redis: RedisV2 | null,
- private readonly redisMirror: RedisV2 | null = null
+ private readonly redisMirror: RedisV2
) {}
public async observe(
@@ -50,7 +50,7 @@ export class HogFlowDuplicateObserverService {
const existingId = await mirrorCompare(
'hog-flow-duplicate-observer.observe',
() => this.redis!.useClient({ name: 'hogflow-observe', failOpen: true }, setNxGet),
- () => this.redisMirror?.useClient({ name: 'hogflow-observe-mirror', failOpen: true }, setNxGet),
+ () => this.redisMirror.useClient({ name: 'hogflow-observe-mirror', failOpen: true }, setNxGet),
(primary, mirror) => Boolean(primary) === Boolean(mirror)
)
if (existingId && existingId !== invocation.id) {
diff --git a/nodejs/src/cdp/services/messaging/push-notification.service.test.ts b/nodejs/src/cdp/services/messaging/push-notification.service.test.ts
index 6e1fbc2e9f70..de62b765b0ef 100644
--- a/nodejs/src/cdp/services/messaging/push-notification.service.test.ts
+++ b/nodejs/src/cdp/services/messaging/push-notification.service.test.ts
@@ -67,6 +67,7 @@ describe('PushNotificationService', () => {
let redisStore: Map<string, string>
let mockRedisSet: jest.Mock
let mockRedis: any
+ let mockValkey: any
const mockTrackedFetch = jest.fn()
@@ -105,7 +106,21 @@ describe('PushNotificationService', () => {
),
} as any
- service = new PushNotificationService(integrationManager, encryptedFields, fetchUtils, mockRedis)
+ // Backed by its own store so mirror writes never show up in `mockRedisSet` assertions.
+ const valkeyStore = new Map<string, string>()
+ mockValkey = {
+ useClient: jest.fn((_opts: any, fn: any) =>
+ fn({
+ get: (key: string) => valkeyStore.get(key) ?? null,
+ set: (key: string, value: string) => {
+ valkeyStore.set(key, value)
+ return 'OK'
+ },
+ })
+ ),
+ } as any
+
+ service = new PushNotificationService(integrationManager, encryptedFields, fetchUtils, mockRedis, mockValkey)
})
afterEach(() => {
@@ -293,6 +308,7 @@ describe('PushNotificationService', () => {
encryptedFields,
fetchUtils,
mockRedis,
+ mockValkey,
new MessageAssetsService({ produce: jest.fn() } as any)
)
})
@@ -354,6 +370,7 @@ describe('PushNotificationService', () => {
encryptedFields,
fetchUtils,
mockRedis,
+ mockValkey,
{
buildRowForPush: () => {
throw new Error('boom')
@@ -672,7 +689,6 @@ describe('PushNotificationService', () => {
encryptedFields,
fetchUtils,
mockRedis,
- undefined,
mirrorRedis
)
mockTrackedFetch.mockResolvedValue({
diff --git a/nodejs/src/cdp/services/messaging/push-notification.service.ts b/nodejs/src/cdp/services/messaging/push-notification.service.ts
index 7bcfc1583074..5f4a7f02fc33 100644
--- a/nodejs/src/cdp/services/messaging/push-notification.service.ts
+++ b/nodejs/src/cdp/services/messaging/push-notification.service.ts
@@ -164,8 +164,8 @@ export class PushNotificationService {
private encryptedFields: EncryptedFields,
private fetchUtils: PushNotificationFetchUtils,
private redis: RedisV2 | null,
- private messageAssetsService?: MessageAssetsService,
- private redisMirror: RedisV2 | null = null
+ private redisMirror: RedisV2,
+ private messageAssetsService?: MessageAssetsService
) {}
@instrumented('push-notification.executeSendPushNotification')
@@ -569,7 +569,7 @@ export class PushNotificationService {
? await mirrorCompare(
'push-notification.apns-jwt-read',
() => read(this.redis!),
- () => (this.redisMirror ? read(this.redisMirror) : undefined)
+ () => read(this.redisMirror)
)
: null
if (cached) {
@@ -591,9 +591,7 @@ export class PushNotificationService {
)
await Promise.all([
this.redis ? write(this.redis) : undefined,
- mirrorCall('push-notification.apns-jwt-write', () =>
- this.redisMirror ? write(this.redisMirror) : undefined
- ),
+ mirrorCall('push-notification.apns-jwt-write', () => write(this.redisMirror)),
])
return jwt
}
diff --git a/nodejs/src/cdp/services/monitoring/hog-masker.service.test.ts b/nodejs/src/cdp/services/monitoring/hog-masker.service.test.ts
index b985328c602e..745948c705c0 100644
--- a/nodejs/src/cdp/services/monitoring/hog-masker.service.test.ts
+++ b/nodejs/src/cdp/services/monitoring/hog-masker.service.test.ts
@@ -8,6 +8,7 @@ import { Hub } from '~/types'
import { HOG_FLOW_MASK_EXAMPLES, HOG_MASK_EXAMPLES } from '../../_tests/examples'
import { createExampleInvocation, createHogExecutionGlobals, createHogFunction } from '../../_tests/fixtures'
import { createExampleHogFlowInvocation } from '../../_tests/fixtures-hogflows'
+import { createCdpValkeyShadowPools } from '../../cdp-services'
import { CyclotronJobInvocationHogFunction, HogFunctionType } from '../../types'
import { BASE_REDIS_KEY, HogMaskerService } from './hog-masker.service'
@@ -20,6 +21,7 @@ describe('HogMasker', () => {
let hub: Hub
let masker: HogMaskerService
let redis: RedisV2
+ let valkey: RedisV2
beforeEach(async () => {
hub = await createHub()
@@ -36,9 +38,11 @@ describe('HogMasker', () => {
poolMinSize: hub.REDIS_POOL_MIN_SIZE,
poolMaxSize: hub.REDIS_POOL_MAX_SIZE,
})
+ valkey = createCdpValkeyShadowPools(hub, 'hog-masker-test').writer
await deleteKeysWithPrefix(redis, BASE_REDIS_KEY)
+ await deleteKeysWithPrefix(valkey, BASE_REDIS_KEY)
- masker = new HogMaskerService(redis)
+ masker = new HogMaskerService(redis, valkey)
})
const advanceTime = (ms: number) => {
diff --git a/nodejs/src/cdp/services/monitoring/hog-masker.service.ts b/nodejs/src/cdp/services/monitoring/hog-masker.service.ts
index 7e193a9a1d87..be11cf12eaac 100644
--- a/nodejs/src/cdp/services/monitoring/hog-masker.service.ts
+++ b/nodejs/src/cdp/services/monitoring/hog-masker.service.ts
@@ -109,7 +109,7 @@ function getTtl(invocation: CyclotronJobInvocation, maskingConfig: HogFunctionMa
export class HogMaskerService {
constructor(
private redis: RedisV2,
- private redisMirror: RedisV2 | null = null
+ private redisMirror: RedisV2
) {}
public async filterByMasking<T extends CyclotronJobInvocation>(
@@ -173,7 +173,7 @@ export class HogMaskerService {
const result = await mirrorCompare(
'hog-masker.filterByMasking',
() => this.redis.usePipeline({ name: 'masker', failOpen: true }, buildPipeline),
- () => this.redisMirror?.usePipeline({ name: 'masker-mirror', failOpen: true }, buildPipeline),
+ () => this.redisMirror.usePipeline({ name: 'masker-mirror', failOpen: true }, buildPipeline),
(primary, mirror) =>
maskContexts.every(
(masker, index) =>
diff --git a/nodejs/src/cdp/utils/mirror-call.test.ts b/nodejs/src/cdp/utils/mirror-call.test.ts
index 75fea7adf320..8c626b95d49d 100644
--- a/nodejs/src/cdp/utils/mirror-call.test.ts
+++ b/nodejs/src/cdp/utils/mirror-call.test.ts
@@ -11,13 +11,6 @@ describe('mirrorCall', () => {
expect(call).toHaveBeenCalledTimes(1)
})
- it('short-circuits when the call factory returns undefined (mirror unconfigured)', async () => {
- const call = jest.fn().mockReturnValue(undefined)
- await mirrorCall('test.op', call, 50)
- expect(call).toHaveBeenCalledTimes(1)
- // Resolving with no work — verified by virtue of the test not hanging.
- })
-
it('catches and logs errors instead of throwing', async () => {
const call = jest.fn().mockRejectedValue(new Error('boom'))
await expect(mirrorCall('test.op', call, 50)).resolves.toBeUndefined()
@@ -53,6 +46,17 @@ describe('mirrorCall', () => {
expect(logger.warn).toHaveBeenCalledWith('🪞', '[mirror:test.compare] result mismatch')
})
+ it('returns the primary result when the comparator throws on an unexpected mirror shape', async () => {
+ await expect(
+ mirrorCompare<{ isRateLimited: boolean }[]>(
+ 'test.compare',
+ () => Promise.resolve([{ isRateLimited: false }]),
+ () => Promise.resolve(undefined as any),
+ (primary, mirror) => primary.every((entry, i) => entry.isRateLimited === mirror[i].isRateLimited)
+ )
+ ).resolves.toEqual([{ isRateLimited: false }])
+ })
+
it('returns the primary result when the mirror fails', async () => {
await expect(
mirrorCompare(
diff --git a/nodejs/src/cdp/utils/mirror-call.ts b/nodejs/src/cdp/utils/mirror-call.ts
index cbb04cc7ab34..94ac69c40400 100644
--- a/nodejs/src/cdp/utils/mirror-call.ts
+++ b/nodejs/src/cdp/utils/mirror-call.ts
@@ -14,22 +14,13 @@ const mirrorOperationsTotal = new Counter({
labelNames: ['operation', 'outcome'],
})
-type MirrorOutcome<T> = { status: 'completed'; value: T } | { status: 'skipped' } | { status: 'failed' }
+type MirrorOutcome<T> = { status: 'completed'; value: T } | { status: 'failed' }
-async function runMirrorCall<T>(
- label: string,
- call: () => Promise<T> | undefined,
- timeoutMs: number
-): Promise<MirrorOutcome<T>> {
+async function runMirrorCall<T>(label: string, call: () => Promise<T>, timeoutMs: number): Promise<MirrorOutcome<T>> {
let timeoutId: NodeJS.Timeout | undefined
try {
- const promise = call()
- if (!promise) {
- mirrorOperationsTotal.labels({ operation: label, outcome: 'skipped' }).inc()
- return { status: 'skipped' }
- }
const value = await Promise.race([
- promise,
+ call(),
new Promise<never>((_, reject) => {
timeoutId = setTimeout(() => reject(new Error(`mirror call timed out after ${timeoutMs}ms`)), timeoutMs)
}),
@@ -59,14 +50,10 @@ async function runMirrorCall<T>(
* primary call.
* - Wrapped in `instrumentFn` so latency / errors surface in tracing under
* the `cdp.mirror.<label>` key.
- *
- * The `call` arg returns `Promise<unknown> | undefined` so the common pattern
- * of `() => this.fooMirror?.bar(args)` works directly: when the mirror is null
- * the inner expression evaluates to undefined and the helper short-circuits.
*/
export async function mirrorCall(
label: string,
- call: () => Promise<unknown> | undefined,
+ call: () => Promise<unknown>,
timeoutMs: number = DEFAULT_TIMEOUT_MS
): Promise<void> {
return instrumentFn({ key: `cdp.mirror.${label}`, sendException: false }, async () => {
@@ -84,7 +71,7 @@ export async function mirrorCall(
export async function mirrorCompare<T>(
label: string,
primaryCall: () => Promise<T>,
- mirrorCallFactory: () => Promise<T> | undefined,
+ mirrorCallFactory: () => Promise<T>,
isEquivalent: (primary: T, mirror: T) => boolean = isDeepStrictEqual,
timeoutMs: number = DEFAULT_TIMEOUT_MS
): Promise<T> {
@@ -95,7 +82,16 @@ export async function mirrorCompare<T>(
const [primary, mirror] = await Promise.all([primaryPromise, mirrorPromise])
if (mirror.status === 'completed') {
- const outcome = isEquivalent(primary, mirror.value) ? 'matched' : 'mismatched'
+ // `isEquivalent` is caller-supplied and indexes into the mirror payload, so a shape
+ // the comparator does not expect throws here — outside runMirrorCall's guard. Treat
+ // that as a mismatch rather than letting it reject the primary result.
+ let outcome: 'matched' | 'mismatched'
+ try {
+ outcome = isEquivalent(primary, mirror.value) ? 'matched' : 'mismatched'
+ } catch (err) {
+ outcome = 'mismatched'
+ logger.warn('🪞', `[mirror:${label}] comparison threw`, { err: String(err) })
+ }
mirrorOperationsTotal.labels({ operation: label, outcome }).inc()
if (outcome === 'mismatched' && !mismatchWarningLogged.has(label)) {
mismatchWarningLogged.add(label)