: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): compare redis and valkey mirror results (#76562)
Ben White9c0aff86ecb8
diff --git a/nodejs/src/cdp/cdp-api.ts b/nodejs/src/cdp/cdp-api.tsindex b1dc6ad4ea38..a166c817a044 100644--- a/nodejs/src/cdp/cdp-api.ts+++ b/nodejs/src/cdp/cdp-api.ts@@ -64,6 +64,7 @@ import {} from './utils'import { convertToHogFunctionFilterGlobal } from './utils/hog-function-filtering'import { JWT, PosthogJwtAudience } from './utils/jwt-utils'+import { mirrorCall, mirrorCompare } from './utils/mirror-call'// Allowlist of safe content types for webhook responses to prevent XSSconst SAFE_CONTENT_TYPES = new Set([@@ -121,6 +122,7 @@ export class CdpApi {private hogFlowExecutor: HogFlowExecutorServiceprivate hogWatcher: HogWatcherService+ private hogWatcherMirror: HogWatcherService | nullprivate hogTransformer: HogTransformerServiceprivate invocationResultsService: InvocationResultsServiceprivate rerunJobManager: RerunJobManager | null = null@@ -153,6 +155,7 @@ export class CdpApi {this.nativeDestinationExecutorService = services.nativeDestinationExecutorServicethis.segmentDestinationExecutorService = services.segmentDestinationExecutorServicethis.hogWatcher = services.hogWatcher+ this.hogWatcherMirror = services.hogWatcherMirrorthis.invocationResultsService = services.invocationResultsService// API-only services. The hog-transformer's monitoring service reuses the same@@ -181,7 +184,8 @@ export class CdpApi {this.hogFunctionManager,this.hogExecutor,this.hogWatcher,- this.invocationResultsService+ this.invocationResultsService,+ this.hogWatcherMirror)this.batchResolverProducer = batchResolverProducerthis.rescheduleJwt = config.WORKFLOWS_RESCHEDULE_JWT_SECRET@@ -300,7 +304,11 @@ export class CdpApi {() =>async (req: ModifiedRequest, res: express.Response): Promise<void> => {const { id } = req.params- const summary = await this.hogWatcher.getPersistedState(id)+ const summary = await mirrorCompare(+ 'hog-watcher.getPersistedState',+ () => this.hogWatcher.getPersistedState(id),+ () => this.hogWatcherMirror?.getPersistedState(id)+ )res.json(summary)}@@ -317,7 +325,11 @@ export class CdpApi {return}- const summary = await this.hogWatcher.getPersistedState(id)+ const summary = await mirrorCompare(+ 'hog-watcher.getPersistedState',+ () => this.hogWatcher.getPersistedState(id),+ () => this.hogWatcherMirror?.getPersistedState(id)+ )const hogFunction = await this.hogFunctionManager.fetchHogFunction(id)if (!hogFunction) {@@ -328,20 +340,35 @@ export class CdpApi {// Only allow patching the status if it is different from the current statusif (summary.state !== state) {- await this.hogWatcher.forceStateChange(hogFunction, state)+ await Promise.all([+ this.hogWatcher.forceStateChange(hogFunction, state),+ mirrorCall('hog-watcher.forceStateChange', () =>+ this.hogWatcherMirror?.forceStateChange(hogFunction, state)+ ),+ ])}// Hacky - wait for a little to give a chance for the state to changeawait delay(100)- res.json(await this.hogWatcher.getPersistedState(id))+ res.json(+ await mirrorCompare(+ 'hog-watcher.getPersistedState',+ () => this.hogWatcher.getPersistedState(id),+ () => this.hogWatcherMirror?.getPersistedState(id)+ )+ )}private getFunctionStates =() =>async (req: ModifiedRequest, res: express.Response): Promise<void> => {try {- const allStates = await this.hogWatcher.getAllFunctionStates()+ const allStates = await mirrorCompare(+ 'hog-watcher.getAllFunctionStates',+ () => this.hogWatcher.getAllFunctionStates(),+ () => this.hogWatcherMirror?.getAllFunctionStates()+ )// Transform the data for better consumption by Grafana and sort by tokens ascendingconst statesArray = Object.entries(allStates)diff --git a/nodejs/src/cdp/cdp-services.ts b/nodejs/src/cdp/cdp-services.tsindex 2ad29f518a65..290fe8c68866 100644--- a/nodejs/src/cdp/cdp-services.ts+++ b/nodejs/src/cdp/cdp-services.ts@@ -437,7 +437,8 @@ export function createCdpCoreServices(backoffMaxMs: config.CDP_FETCH_BACKOFF_MAX_MS,},redis,- messageAssetsService+ messageAssetsService,+ valkeyShadow?.writer ?? null)const hogExecutor = new HogExecutorService(diff --git a/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.ts b/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.tsindex 20e42ab92dff..e8398309d724 100644--- a/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.ts@@ -23,6 +23,7 @@ import {} from '../types'import { logEntry } from '../utils'import { createInvocation, createInvocationResult } from '../utils/invocation-utils'+import { mirrorCall, mirrorCompare } from '../utils/mirror-call'import { CdpConsumerBase, CdpConsumerBaseDeps } from './cdp-base.consumer'const DISALLOWED_HEADERS = [@@ -432,7 +433,11 @@ export class CdpSourceWebhooksConsumer extends CdpConsumerBase<PluginsServerConfconst [webhook, hogFunctionState] = await Promise.all([this.getWebhook(webhookId),- this.hogWatcher.getCachedEffectiveState(webhookId),+ mirrorCompare(+ 'hog-watcher.getCachedEffectiveState',+ () => this.hogWatcher.getCachedEffectiveState(webhookId),+ () => this.hogWatcherMirror?.getCachedEffectiveState(webhookId)+ ),])if (!webhook) {@@ -461,7 +466,10 @@ export class CdpSourceWebhooksConsumer extends CdpConsumerBase<PluginsServerConfvoid this.promiseScheduler.schedule(this.invocationResultsService.flush(),- this.hogWatcher.observeResultsBuffered(result)+ this.hogWatcher.observeResultsBuffered(result),+ mirrorCall('hog-watcher.observeResultsBuffered', () =>+ this.hogWatcherMirror?.observeResultsBuffered(result)+ ))return resultdiff --git a/nodejs/src/cdp/services/batch-export-hog-function.service.ts b/nodejs/src/cdp/services/batch-export-hog-function.service.tsindex ad30a29ccbb7..e9e466544097 100644--- a/nodejs/src/cdp/services/batch-export-hog-function.service.ts+++ b/nodejs/src/cdp/services/batch-export-hog-function.service.ts@@ -13,6 +13,7 @@ import {} from '../types'import { convertToHogFunctionInvocationGlobals } from '../utils'import { createInvocation } from '../utils/invocation-utils'+import { mirrorCall } from '../utils/mirror-call'import { HogExecutorService } from './hog-executor.service'import { InvocationResultsService } from './invocation-results.service'import { GroupsManagerService } from './managers/groups-manager.service'@@ -46,7 +47,8 @@ export class BatchExportHogFunctionService {private hogFunctionManager: HogFunctionManagerService,private hogExecutor: HogExecutorService,private hogWatcher: HogWatcherService,- private invocationResultsService: InvocationResultsService+ private invocationResultsService: InvocationResultsService,+ private hogWatcherMirror: HogWatcherService | null = null) {this.promiseScheduler = new PromiseScheduler()}@@ -98,6 +100,9 @@ export class BatchExportHogFunctionService {Promise.all([this.invocationResultsService.queueInvocationResultsAndFlush([result]),this.hogWatcher.observeResultsBuffered(result),+ mirrorCall('hog-watcher.observeResultsBuffered', () =>+ this.hogWatcherMirror?.observeResultsBuffered(result)+ ),]))diff --git a/nodejs/src/cdp/services/hog-flow-invocation-pipeline.service.ts b/nodejs/src/cdp/services/hog-flow-invocation-pipeline.service.tsindex 662e8b9e1707..58dbb1ca97da 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 { mirrorCallWithPrimary } from '../utils/mirror-call'+import { mirrorCompare } 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,7 +101,7 @@ export class HogFlowInvocationPipeline {).flat()const hogFlowIds = possibleInvocations.map((x) => x.hogFlow.id)- const states = await mirrorCallWithPrimary(+ const states = await mirrorCompare('hog-watcher.getEffectiveStates',() =>instrumentFn('cdpConsumer.handleEachBatch.hogWatcher.getEffectiveStates', async () => {@@ -114,13 +114,15 @@ export class HogFlowInvocationPipeline {id: x.hogFlow.id,cost: 1,}))- const rateLimits = await mirrorCallWithPrimary(+ const rateLimits = await mirrorCompare('hog-rate-limiter.rateLimitGrouped',() =>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))const validInvocations: CyclotronJobInvocation[] = []diff --git a/nodejs/src/cdp/services/hog-function-invocation-pipeline.service.ts b/nodejs/src/cdp/services/hog-function-invocation-pipeline.service.tsindex 34a02c838650..32b284d444b9 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 { mirrorCallWithPrimary } from '../utils/mirror-call'+import { mirrorCompare } 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,7 +103,7 @@ export class HogFunctionInvocationPipeline {).flat()const hogFunctionIds = possibleInvocations.map((x) => x.hogFunction.id)- const states = await mirrorCallWithPrimary(+ const states = await mirrorCompare('hog-watcher.getEffectiveStates',() =>instrumentFn('cdpConsumer.handleEachBatch.hogWatcher.getEffectiveStates', async () => {@@ -116,13 +116,15 @@ export class HogFunctionInvocationPipeline {id: x.hogFunction.id,cost: 1,}))- const rateLimits = await mirrorCallWithPrimary(+ const rateLimits = await mirrorCompare('hog-rate-limiter.rateLimitGrouped',() =>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))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 82b9f1a8bcc7..74f43fa71d74 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 { mirrorCallWithPrimary } from '../../utils/mirror-call'+import { mirrorCompare } from '../../utils/mirror-call'const DUPLICATE_OBSERVATION_TTL_SECONDS = 15 * 60@@ -47,10 +47,11 @@ export class HogFlowDuplicateObserverService {let duplicate = falsetry {- const existingId = await mirrorCallWithPrimary(+ 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) {duplicate = truediff --git a/nodejs/src/cdp/services/messaging/push-notification.service.test.ts b/nodejs/src/cdp/services/messaging/push-notification.service.test.tsindex 059b65c85325..d397188251d6 100644--- a/nodejs/src/cdp/services/messaging/push-notification.service.test.ts+++ b/nodejs/src/cdp/services/messaging/push-notification.service.test.ts@@ -636,6 +636,52 @@ describe('PushNotificationService', () => {expect(mockRedisSet).toHaveBeenCalledTimes(1)})+ it('mirrors APNS provider token reads and writes to Valkey', async () => {+ const mirrorStore = new Map<string, string>()+ const mirrorSet = jest.fn((key: string, value: string) => {+ mirrorStore.set(key, value)+ return 'OK'+ })+ const mirrorRedis = {+ useClient: jest.fn((_opts: any, fn: any) =>+ fn({+ get: (key: string) => mirrorStore.get(key) ?? null,+ set: mirrorSet,+ })+ ),+ } as any+ const mirroredService = new PushNotificationService(+ integrationManager,+ encryptedFields,+ fetchUtils,+ mockRedis,+ undefined,+ mirrorRedis+ )+ mockTrackedFetch.mockResolvedValue({+ fetchError: null,+ fetchResponse: { status: 200, text: () => Promise.resolve(''), dump: () => Promise.resolve() },+ fetchDuration: 15,+ })+ const invocation = createSendPushNotificationInvocation({+ '$device_push_subscription_com.example.app': encryptedFields.encrypt('apns-device-token'),+ })++ await mirroredService.executeSendPushNotification(invocation)++ expect(mirrorRedis.useClient).toHaveBeenCalledWith(+ expect.objectContaining({ name: 'apns-jwt-read' }),+ expect.any(Function)+ )+ expect(mirrorSet).toHaveBeenCalledWith(+ expect.stringContaining('@posthog/apns-provider-jwt/'),+ expect.any(String),+ 'EX',+ 2700+ )+ expect([...mirrorStore.values()]).toEqual([...redisStore.values()])+ })+it('sets apns-priority to 5 for passive interruption level', async () => {const invocation = createSendPushNotificationInvocation({'$device_push_subscription_com.example.app': encryptedFields.encrypt('apns-device-token'),diff --git a/nodejs/src/cdp/services/messaging/push-notification.service.ts b/nodejs/src/cdp/services/messaging/push-notification.service.tsindex 7adc0ac58c7b..9fd3f50e16a7 100644--- a/nodejs/src/cdp/services/messaging/push-notification.service.ts+++ b/nodejs/src/cdp/services/messaging/push-notification.service.ts@@ -6,6 +6,7 @@ import {CyclotronInvocationQueueParametersSendPushNotificationType,PushNotificationPayloadType,} from '~/cdp/schema/cyclotron'+import { mirrorCall, mirrorCompare } from '~/cdp/utils/mirror-call'import { RedisV2 } from '~/common/redis/redis-v2'import { instrumented } from '~/common/tracing/tracing-utils'import { parseJSON } from '~/common/utils/json-parse'@@ -163,7 +164,8 @@ export class PushNotificationService {private encryptedFields: EncryptedFields,private fetchUtils: PushNotificationFetchUtils,private redis: RedisV2 | null,- private messageAssetsService?: MessageAssetsService+ private messageAssetsService?: MessageAssetsService,+ private redisMirror: RedisV2 | null = null) {}@instrumented('push-notification.executeSendPushNotification')@@ -556,9 +558,15 @@ export class PushNotificationService {const keyFingerprint = createHash('sha256').update(`${teamId}:${keyId}:${signingKey}`).digest('hex')const cacheKey = `${APNS_JWT_CACHE_PREFIX}${keyFingerprint}`- const cached = await this.redis?.useClient({ name: 'apns-jwt-read', failOpen: true }, (client) =>- client.get(cacheKey)- )+ const read = (pool: RedisV2) =>+ pool.useClient({ name: 'apns-jwt-read', failOpen: true }, (client) => client.get(cacheKey))+ const cached = this.redis+ ? await mirrorCompare(+ 'push-notification.apns-jwt-read',+ () => read(this.redis!),+ () => (this.redisMirror ? read(this.redisMirror) : undefined)+ )+ : nullif (cached) {return cached}@@ -572,9 +580,16 @@ export class PushNotificationService {const signature = sign.sign({ key: signingKey, dsaEncoding: 'ieee-p1363' }, 'base64url')const jwt = `${signingInput}.${signature}`- await this.redis?.useClient({ name: 'apns-jwt-write', failOpen: true }, (client) =>- client.set(cacheKey, jwt, 'EX', APNS_JWT_TTL_SECONDS)- )+ const write = (pool: RedisV2) =>+ pool.useClient({ name: 'apns-jwt-write', failOpen: true }, (client) =>+ client.set(cacheKey, jwt, 'EX', APNS_JWT_TTL_SECONDS)+ )+ await Promise.all([+ this.redis ? write(this.redis) : undefined,+ mirrorCall('push-notification.apns-jwt-write', () =>+ this.redisMirror ? write(this.redisMirror) : undefined+ ),+ ])return jwt}diff --git a/nodejs/src/cdp/services/monitoring/hog-masker.service.ts b/nodejs/src/cdp/services/monitoring/hog-masker.service.tsindex aa0cfda948c8..7e193a9a1d87 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 { mirrorCallWithPrimary } from '../../utils/mirror-call'+import { mirrorCompare } 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`@@ -32,6 +32,21 @@ type GenericHogInvocationWithMasker = CyclotronJobInvocation & {masker?: MaskContext}+type MaskPipelineResult = Awaited<ReturnType<RedisV2['usePipeline']>>++function allowedExecutionsForResult(result: MaskPipelineResult, index: number, masker: MaskContext): number | null {+ const newValue: number | null = result ? result[index * 2][1] : null+ if (newValue === null) {+ return null+ }++ const oldValue = newValue - masker.increment+ if (masker.threshold) {+ return Math.floor((newValue - 1) / masker.threshold) - Math.floor((oldValue - 1) / masker.threshold)+ }+ return oldValue === 0 ? 1 : 0+}+function isHogFunctionInvocation(invocation: CyclotronJobInvocation): invocation is CyclotronJobInvocationHogFunction {return (invocation as CyclotronJobInvocationHogFunction).hogFunction !== undefined}@@ -154,33 +169,26 @@ export class HogMaskerService {})}- const result = await mirrorCallWithPrimary(+ const maskContexts = Object.values(masks)+ 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) =>+ allowedExecutionsForResult(primary, index, masker) ===+ allowedExecutionsForResult(mirror, index, masker)+ ))- Object.values(masks).forEach((masker, index) => {- const newValue: number | null = result ? result[index * 2][1] : null- if (newValue === null) {+ maskContexts.forEach((masker, index) => {+ const allowedExecutions = allowedExecutionsForResult(result, index, masker)+ if (allowedExecutions === null) {// We fail closed here as with a masking config the typical case will be not to sendreturn}-- const oldValue = newValue - masker.increment-- // Simplest case - the previous value was 0- masker.allowedExecutions = oldValue === 0 ? 1 : 0-- if (masker.threshold) {- // TRICKY: We minus 1 to account for the "first" execution- const thresholdsPasses =- Math.floor((newValue - 1) / masker.threshold) - Math.floor((oldValue - 1) / masker.threshold)-- if (thresholdsPasses) {- masker.allowedExecutions = thresholdsPasses- }- }+ masker.allowedExecutions = allowedExecutions})return invocationsWithMasker.reduce(diff --git a/nodejs/src/cdp/utils/mirror-call.test.ts b/nodejs/src/cdp/utils/mirror-call.test.tsindex 53170064b8da..75fea7adf320 100644--- a/nodejs/src/cdp/utils/mirror-call.test.ts+++ b/nodejs/src/cdp/utils/mirror-call.test.ts@@ -1,4 +1,8 @@-import { mirrorCall, mirrorCallWithPrimary } from './mirror-call'+import { logger } from '~/common/utils/logger'++import { mirrorCall, mirrorCompare } from './mirror-call'++jest.mock('~/common/utils/logger', () => ({ logger: { warn: jest.fn() } }))describe('mirrorCall', () => {it('resolves when the call resolves in time', async () => {@@ -27,18 +31,32 @@ describe('mirrorCall', () => {expect(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 mirror results match', async () => {+ await expect(+ mirrorCompare(+ 'test.compare',+ () => Promise.resolve({ state: 'healthy' }),+ () => Promise.resolve({ state: 'healthy' })+ )+ ).resolves.toEqual({ state: 'healthy' })+ expect(logger.warn).not.toHaveBeenCalledWith('🪞', '[mirror:test.compare] result mismatch')+ })++ it('reports a mismatch without changing the primary result', async () => {+ await expect(+ mirrorCompare(+ 'test.compare',+ () => Promise.resolve({ state: 'healthy' }),+ () => Promise.resolve({ state: 'degraded' })+ )+ ).resolves.toEqual({ state: 'healthy' })+ expect(logger.warn).toHaveBeenCalledWith('🪞', '[mirror:test.compare] result mismatch')})it('returns the primary result when the mirror fails', async () => {await expect(- mirrorCallWithPrimary(- 'test.pair',+ mirrorCompare(+ 'test.compare',() => Promise.resolve('primary'),() => Promise.reject(new Error('boom')))diff --git a/nodejs/src/cdp/utils/mirror-call.ts b/nodejs/src/cdp/utils/mirror-call.tsindex e212d0881a28..cbb04cc7ab34 100644--- a/nodejs/src/cdp/utils/mirror-call.ts+++ b/nodejs/src/cdp/utils/mirror-call.ts@@ -1,8 +1,50 @@+import { isDeepStrictEqual } from 'node:util'+import { Counter } from 'prom-client'+import { logger } from '~/common/utils/logger'import { instrumentFn } from '../../common/tracing/tracing-utils'const DEFAULT_TIMEOUT_MS = 2000+const mismatchWarningLogged = new Set<string>()++const mirrorOperationsTotal = new Counter({+ name: 'cdp_valkey_mirror_operations_total',+ help: 'CDP Redis-to-Valkey mirror operations by operation and outcome.',+ labelNames: ['operation', 'outcome'],+})++type MirrorOutcome<T> = { status: 'completed'; value: T } | { status: 'skipped' } | { status: 'failed' }++async function runMirrorCall<T>(+ label: string,+ call: () => Promise<T> | undefined,+ 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,+ new Promise<never>((_, reject) => {+ timeoutId = setTimeout(() => reject(new Error(`mirror call timed out after ${timeoutMs}ms`)), timeoutMs)+ }),+ ])+ return { status: 'completed', value }+ } catch (err) {+ mirrorOperationsTotal.labels({ operation: label, outcome: 'failed' }).inc()+ logger.warn('🪞', `[mirror:${label}] failed`, { err: String(err) })+ return { status: 'failed' }+ } finally {+ if (timeoutId) {+ clearTimeout(timeoutId)+ }+ }+}/*** Wraps a Valkey mirror call so it can never affect the primary code path.@@ -28,38 +70,38 @@ export async function mirrorCall(timeoutMs: number = DEFAULT_TIMEOUT_MS): Promise<void> {return instrumentFn({ key: `cdp.mirror.${label}`, sendException: false }, async () => {- let timeoutId: NodeJS.Timeout | undefined- try {- const promise = call()- if (!promise) {- return- }- await Promise.race([- promise,- new Promise<never>((_, reject) => {- timeoutId = setTimeout(- () => reject(new Error(`mirror call timed out after ${timeoutMs}ms`)),- timeoutMs- )- }),- ])- } catch (err) {- logger.warn('🪞', `[mirror:${label}] failed`, { err: String(err) })- } finally {- if (timeoutId) {- clearTimeout(timeoutId)- }+ const outcome = await runMirrorCall(label, call, timeoutMs)+ if (outcome.status === 'completed') {+ mirrorOperationsTotal.labels({ operation: label, outcome: 'completed' }).inc()}})}-/** Runs Redis and its Valkey shadow in parallel while keeping Redis authoritative. */-export async function mirrorCallWithPrimary<T>(+/**+ * Runs an authoritative Redis read and its Valkey mirror in parallel, returning+ * the Redis result while recording whether Valkey returned equivalent data.+ */+export async function mirrorCompare<T>(label: string,primaryCall: () => Promise<T>,- mirrorCallFactory: () => Promise<unknown> | undefined,- timeoutMs?: number+ mirrorCallFactory: () => Promise<T> | undefined,+ isEquivalent: (primary: T, mirror: T) => boolean = isDeepStrictEqual,+ timeoutMs: number = DEFAULT_TIMEOUT_MS): Promise<T> {- const [primary] = await Promise.all([primaryCall(), mirrorCall(label, mirrorCallFactory, timeoutMs)])+ const primaryPromise = primaryCall()+ const mirrorPromise = instrumentFn({ key: `cdp.mirror.${label}`, sendException: false }, () =>+ runMirrorCall(label, mirrorCallFactory, timeoutMs)+ )+ const [primary, mirror] = await Promise.all([primaryPromise, mirrorPromise])++ if (mirror.status === 'completed') {+ const outcome = isEquivalent(primary, mirror.value) ? 'matched' : 'mismatched'+ mirrorOperationsTotal.labels({ operation: label, outcome }).inc()+ if (outcome === 'mismatched' && !mismatchWarningLogged.has(label)) {+ mismatchWarningLogged.add(label)+ logger.warn('🪞', `[mirror:${label}] result mismatch`)+ }+ }+return primary}