: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
refactor(cdp): centralize valkey shadow calls (#76560)
Ben Whited083b5e99b88
diff --git a/nodejs/src/cdp/services/hog-flow-invocation-pipeline.service.ts b/nodejs/src/cdp/services/hog-flow-invocation-pipeline.service.tsindex 285e7bdda552..662e8b9e1707 100644--- a/nodejs/src/cdp/services/hog-flow-invocation-pipeline.service.ts+++ b/nodejs/src/cdp/services/hog-flow-invocation-pipeline.service.ts@@ -11,7 +11,7 @@ import { QuotaLimiting } from '../../common/services/quota-limiting.service'import { CdpValkeyShadowPools } from '../cdp-services'import { counterRateLimited } from '../consumers/metrics'import { CyclotronJobInvocation, HogFunctionInvocationGlobals, LogEntry, MinimalAppMetric } from '../types'-import { mirrorCall } from '../utils/mirror-call'+import { mirrorCallWithPrimary } from '../utils/mirror-call'import { HogFlowExecutorService } from './hogflows/hogflow-executor.service'import { HogFlowManagerService } from './hogflows/hogflow-manager.service'import { shouldBlockHogFlowDueToQuota } from './hogflows/hogflow-quota-limiting'@@ -101,27 +101,27 @@ export class HogFlowInvocationPipeline {).flat()const hogFlowIds = possibleInvocations.map((x) => x.hogFlow.id)- const [states] = await Promise.all([- instrumentFn('cdpConsumer.handleEachBatch.hogWatcher.getEffectiveStates', async () => {- return await this.deps.hogWatcher.getEffectiveStates(hogFlowIds)- }),- mirrorCall('hog-watcher.getEffectiveStates', () =>- this.deps.hogWatcherMirror?.getEffectiveStates(hogFlowIds)- ),- ])+ const states = await mirrorCallWithPrimary(+ 'hog-watcher.getEffectiveStates',+ () =>+ instrumentFn('cdpConsumer.handleEachBatch.hogWatcher.getEffectiveStates', async () => {+ return await this.deps.hogWatcher.getEffectiveStates(hogFlowIds)+ }),+ () => this.deps.hogWatcherMirror?.getEffectiveStates(hogFlowIds)+ )const rateLimitInputs: KeyedRateLimitRequest[] = possibleInvocations.map((x) => ({id: x.hogFlow.id,cost: 1,}))- const [rateLimits] = await Promise.all([- instrumentFn('cdpConsumer.handleEachBatch.hogRateLimiter.rateLimitGrouped', async () => {- return await this.hogRateLimiter.rateLimitGrouped(rateLimitInputs)- }),- mirrorCall('hog-rate-limiter.rateLimitGrouped', () =>- this.hogRateLimiterMirror?.rateLimitGrouped(rateLimitInputs)- ),- ])+ const rateLimits = await mirrorCallWithPrimary(+ 'hog-rate-limiter.rateLimitGrouped',+ () =>+ instrumentFn('cdpConsumer.handleEachBatch.hogRateLimiter.rateLimitGrouped', async () => {+ return await this.hogRateLimiter.rateLimitGrouped(rateLimitInputs)+ }),+ () => this.hogRateLimiterMirror?.rateLimitGrouped(rateLimitInputs)+ )const validInvocations: CyclotronJobInvocation[] = []await Promise.all(diff --git a/nodejs/src/cdp/services/hog-function-invocation-pipeline.service.ts b/nodejs/src/cdp/services/hog-function-invocation-pipeline.service.tsindex 6991ba264cc6..34a02c838650 100644--- a/nodejs/src/cdp/services/hog-function-invocation-pipeline.service.ts+++ b/nodejs/src/cdp/services/hog-function-invocation-pipeline.service.ts@@ -15,7 +15,7 @@ import {HogFunctionTypeType,MinimalAppMetric,} from '../types'-import { mirrorCall } from '../utils/mirror-call'+import { mirrorCallWithPrimary } from '../utils/mirror-call'import { HogExecutorService } from './hog-executor.service'import { HogFunctionManagerService } from './managers/hog-function-manager.service'import { HogFunctionMonitoringService } from './monitoring/hog-function-monitoring.service'@@ -103,27 +103,27 @@ export class HogFunctionInvocationPipeline {).flat()const hogFunctionIds = possibleInvocations.map((x) => x.hogFunction.id)- const [states] = await Promise.all([- instrumentFn('cdpConsumer.handleEachBatch.hogWatcher.getEffectiveStates', async () => {- return await this.deps.hogWatcher.getEffectiveStates(hogFunctionIds)- }),- mirrorCall('hog-watcher.getEffectiveStates', () =>- this.deps.hogWatcherMirror?.getEffectiveStates(hogFunctionIds)- ),- ])+ const states = await mirrorCallWithPrimary(+ 'hog-watcher.getEffectiveStates',+ () =>+ instrumentFn('cdpConsumer.handleEachBatch.hogWatcher.getEffectiveStates', async () => {+ return await this.deps.hogWatcher.getEffectiveStates(hogFunctionIds)+ }),+ () => this.deps.hogWatcherMirror?.getEffectiveStates(hogFunctionIds)+ )const rateLimitInputs: KeyedRateLimitRequest[] = possibleInvocations.map((x) => ({id: x.hogFunction.id,cost: 1,}))- const [rateLimits] = await Promise.all([- instrumentFn('cdpConsumer.handleEachBatch.hogRateLimiter.rateLimitGrouped', async () => {- return await this.hogRateLimiter.rateLimitGrouped(rateLimitInputs)- }),- mirrorCall('hog-rate-limiter.rateLimitGrouped', () =>- this.hogRateLimiterMirror?.rateLimitGrouped(rateLimitInputs)- ),- ])+ const rateLimits = await mirrorCallWithPrimary(+ 'hog-rate-limiter.rateLimitGrouped',+ () =>+ instrumentFn('cdpConsumer.handleEachBatch.hogRateLimiter.rateLimitGrouped', async () => {+ return await this.hogRateLimiter.rateLimitGrouped(rateLimitInputs)+ }),+ () => this.hogRateLimiterMirror?.rateLimitGrouped(rateLimitInputs)+ )const validInvocations: CyclotronJobInvocationHogFunction[] = []diff --git a/nodejs/src/cdp/services/hogflows/hogflow-duplicate-observer.service.ts b/nodejs/src/cdp/services/hogflows/hogflow-duplicate-observer.service.tsindex 6fd6e307870d..82b9f1a8bcc7 100644--- a/nodejs/src/cdp/services/hogflows/hogflow-duplicate-observer.service.ts+++ b/nodejs/src/cdp/services/hogflows/hogflow-duplicate-observer.service.ts@@ -5,7 +5,7 @@ import { RedisClient, RedisV2 } from '~/common/redis/redis-v2'import { logger } from '~/common/utils/logger'import { CyclotronJobInvocationHogFlow } from '../../types'-import { mirrorCall } from '../../utils/mirror-call'+import { mirrorCallWithPrimary } from '../../utils/mirror-call'const DUPLICATE_OBSERVATION_TTL_SECONDS = 15 * 60@@ -47,12 +47,11 @@ export class HogFlowDuplicateObserverService {let duplicate = falsetry {- const [existingId] = await Promise.all([- this.redis.useClient({ name: 'hogflow-observe', failOpen: true }, setNxGet),- mirrorCall('hog-flow-duplicate-observer.observe', () =>- this.redisMirror?.useClient({ name: 'hogflow-observe-mirror', failOpen: true }, setNxGet)- ),- ])+ const existingId = await mirrorCallWithPrimary(+ 'hog-flow-duplicate-observer.observe',+ () => this.redis!.useClient({ name: 'hogflow-observe', failOpen: true }, setNxGet),+ () => this.redisMirror?.useClient({ name: 'hogflow-observe-mirror', failOpen: true }, setNxGet)+ )if (existingId && existingId !== invocation.id) {duplicate = truehogflowDuplicateInvocationDetectedTotal.inc({ workflow_id: invocation.functionId })diff --git a/nodejs/src/cdp/services/monitoring/hog-masker.service.ts b/nodejs/src/cdp/services/monitoring/hog-masker.service.tsindex b1a0f44bc24b..aa0cfda948c8 100644--- a/nodejs/src/cdp/services/monitoring/hog-masker.service.ts+++ b/nodejs/src/cdp/services/monitoring/hog-masker.service.ts@@ -9,7 +9,7 @@ import {HogFunctionMasking,} from '../../types'import { execHog } from '../../utils/hog-exec'-import { mirrorCall } from '../../utils/mirror-call'+import { mirrorCallWithPrimary } from '../../utils/mirror-call'export const BASE_REDIS_KEY = process.env.NODE_ENV == 'test' ? '@posthog-test/hog-masker' : '@posthog/hog-masker'const REDIS_KEY_TOKENS = `${BASE_REDIS_KEY}/mask`@@ -154,12 +154,11 @@ export class HogMaskerService {})}- const [result] = await Promise.all([- this.redis.usePipeline({ name: 'masker', failOpen: true }, buildPipeline),- mirrorCall('hog-masker.filterByMasking', () =>- this.redisMirror?.usePipeline({ name: 'masker-mirror', failOpen: true }, buildPipeline)- ),- ])+ const result = await mirrorCallWithPrimary(+ 'hog-masker.filterByMasking',+ () => this.redis.usePipeline({ name: 'masker', failOpen: true }, buildPipeline),+ () => this.redisMirror?.usePipeline({ name: 'masker-mirror', failOpen: true }, buildPipeline)+ )Object.values(masks).forEach((masker, index) => {const newValue: number | null = result ? result[index * 2][1] : nulldiff --git a/nodejs/src/cdp/utils/mirror-call.test.ts b/nodejs/src/cdp/utils/mirror-call.test.tsindex faac190a3814..53170064b8da 100644--- a/nodejs/src/cdp/utils/mirror-call.test.ts+++ b/nodejs/src/cdp/utils/mirror-call.test.ts@@ -1,4 +1,4 @@-import { mirrorCall } from './mirror-call'+import { mirrorCall, mirrorCallWithPrimary } from './mirror-call'describe('mirrorCall', () => {it('resolves when the call resolves in time', async () => {@@ -26,4 +26,22 @@ describe('mirrorCall', () => {const elapsed = Date.now() - startexpect(elapsed).toBeLessThan(200)})++ it('returns the primary result after running the mirror', async () => {+ const mirror = jest.fn().mockResolvedValue('shadow')+ await expect(mirrorCallWithPrimary('test.pair', () => Promise.resolve('primary'), mirror)).resolves.toBe(+ 'primary'+ )+ expect(mirror).toHaveBeenCalledTimes(1)+ })++ it('returns the primary result when the mirror fails', async () => {+ await expect(+ mirrorCallWithPrimary(+ 'test.pair',+ () => Promise.resolve('primary'),+ () => Promise.reject(new Error('boom'))+ )+ ).resolves.toBe('primary')+ })})diff --git a/nodejs/src/cdp/utils/mirror-call.ts b/nodejs/src/cdp/utils/mirror-call.tsindex ef98d47ef791..e212d0881a28 100644--- a/nodejs/src/cdp/utils/mirror-call.ts+++ b/nodejs/src/cdp/utils/mirror-call.ts@@ -52,3 +52,14 @@ export async function mirrorCall(}})}++/** Runs Redis and its Valkey shadow in parallel while keeping Redis authoritative. */+export async function mirrorCallWithPrimary<T>(+ label: string,+ primaryCall: () => Promise<T>,+ mirrorCallFactory: () => Promise<unknown> | undefined,+ timeoutMs?: number+): Promise<T> {+ const [primary] = await Promise.all([primaryCall(), mirrorCall(label, mirrorCallFactory, timeoutMs)])+ return primary+}