: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
fix(cdp): replace evalsha with hget for read-only HogWatcher state checks (#57512)
Meikel Ratzdb26000ac895
diff --git a/nodejs/src/cdp/services/monitoring/hog-watcher.service.test.ts b/nodejs/src/cdp/services/monitoring/hog-watcher.service.test.tsindex 1650d29cbfdd..9fddf1bf87d6 100644--- a/nodejs/src/cdp/services/monitoring/hog-watcher.service.test.ts+++ b/nodejs/src/cdp/services/monitoring/hog-watcher.service.test.ts@@ -393,6 +393,76 @@ describe('HogWatcher', () => {})})+ describe('getPersistedStates', () => {+ it('should return healthy with full bucket for unknown function', async () => {+ const state = await watcher.getPersistedState('totally-unknown-function-id')+ expect(state).toEqual({+ state: HogWatcherState.healthy,+ tokens: 10000,+ })+ })++ it('should not create Redis keys on read-only access', async () => {+ const unknownId = 'never-executed-function'+ await watcher.getPersistedState(unknownId)+ await watcher.getPersistedState(unknownId)++ // Verify no key was created — reads should be side-effect-free+ const exists = await redis.useClient({ name: 'test-check' }, async (client) => {+ return await client.exists(`${BASE_REDIS_KEY}/tokens/${unknownId}`)+ })+ expect(exists).toEqual(0)+ })++ it('should cap refill at bucketSize after large time gap', async () => {+ await watcher.observeResults([createResult({ duration: 10000, kind: 'async_function' })])+ expect((await watcher.getPersistedState(hogFunctionId)).tokens).toBeLessThan(10000)++ // Advance time by a very large amount — tokens should cap at bucketSize, not overflow+ advanceTime(1_000_000_000)+ const state = await watcher.getPersistedState(hogFunctionId)+ expect(state.tokens).toEqual(watcherConfig.bucketSize)+ })++ it('should handle pool existing without ts in Redis', async () => {+ // Write pool directly without ts to simulate corrupted state+ await redis.useClient({ name: 'test-setup' }, async (client) => {+ await client.hset(`${BASE_REDIS_KEY}/tokens/${hogFunctionId}`, 'pool', '5000')+ })++ const state = await watcher.getPersistedState(hogFunctionId)+ // With no ts, timeDiff is 0, so no refill — tokens should be the raw pool value+ expect(state.tokens).toEqual(5000)+ })++ it('should handle ts existing without pool in Redis', async () => {+ // Write ts directly without pool to simulate corrupted state+ await redis.useClient({ name: 'test-setup' }, async (client) => {+ await client.hset(`${BASE_REDIS_KEY}/tokens/${hogFunctionId}`, 'ts', Math.round(now / 1000))+ })++ const state = await watcher.getPersistedState(hogFunctionId)+ // With no pool, should return bucketSize (healthy default)+ expect(state.tokens).toEqual(watcherConfig.bucketSize)+ })++ it('should return consistent results between write and read paths', async () => {+ // Write costs via observeResults (uses evalsha Lua script)+ await watcher.observeResults([+ createResult({ duration: 5000, kind: 'async_function' }),+ createResult({ duration: 5000, kind: 'async_function' }),+ ])++ // Read immediately via getPersistedState (uses hget)+ const state = await watcher.getPersistedState(hogFunctionId)++ // Tokens should be reduced but function still healthy+ expect(state.tokens).toBeLessThan(watcherConfig.bucketSize)+ expect(state.tokens).toBeGreaterThan(0)+ expect(state.state).toEqual(HogWatcherState.healthy)+ })+ })+describe('doStateChanges - with resetPool', () => {const expectMockCaptureTeamEvent = (state: string, previousState: string) => {expect(mockCaptureTeamEvent).toHaveBeenCalledWith(team, 'hog_function_state_change', {diff --git a/nodejs/src/cdp/services/monitoring/hog-watcher.service.ts b/nodejs/src/cdp/services/monitoring/hog-watcher.service.tsindex 4f570520839f..6c5a8583a4b0 100644--- a/nodejs/src/cdp/services/monitoring/hog-watcher.service.ts+++ b/nodejs/src/cdp/services/monitoring/hog-watcher.service.ts@@ -186,16 +186,24 @@ export class HogWatcherService {}/**- * Get the persisted states of a list of hog functions+ * Get the persisted states of a list of hog functions.+ *+ * Uses plain hget calls instead of the evalsha Lua script.+ * The Lua script with cost=0 was doing 2 hget + 2 hset + 1 expire+ * per call — all writes unnecessary for a read-only check.+ * Replacing with 2 hget calls eliminates ~60% of internal Redis+ * operations per read and makes this method safe to route to+ * read replicas in the future.*/public async getPersistedStates(ids: HogFunctionType['id'][]): Promise<Record<HogFunctionType['id'], HogWatcherFunctionState>> {const idsSet = new Set(ids)+ const nowSeconds = Math.round(Date.now() / 1000)const res = await this.redis.usePipeline({ name: 'getStates' }, (pipeline) => {for (const id of idsSet) {- pipeline.checkRateLimitV2(...this.rateLimitArgs(id, 0))+ pipeline.hmget(`${REDIS_KEY_TOKENS}/${id}`, 'pool', 'ts')pipeline.get(`${REDIS_KEY_STATE}/${id}`)}})@@ -203,14 +211,22 @@ export class HogWatcherService {return Array.from(idsSet).reduce((acc, id, index) => {const resIndex = index * 2- // V2 returns [tokensBefore, tokensAfter], we use tokensAfter- const tokenResult = res ? res[resIndex][1] : undefined- const tokens = tokenResult?.[1] ?? this.config.bucketSize- const state = res ? res[resIndex + 1][1] : undefined+ const [pool, ts] = res?.[resIndex]?.[1] ?? [null, null]+ const stateVal = res?.[resIndex + 1]?.[1]++ // Same refill calculation as the Lua token bucket script+ let tokens: number+ if (pool === null || pool === undefined) {+ tokens = this.config.bucketSize+ } else {+ const timeDiff = ts ? Math.max(nowSeconds - Number(ts), 0) : 0+ const owedTokens = timeDiff * this.config.refillRate+ tokens = Math.min(Number(pool) + owedTokens, this.config.bucketSize)+ }acc[id] = {- state: state ? Number(state) : HogWatcherState.healthy,- tokens: tokens,+ state: stateVal ? Number(stateVal) : HogWatcherState.healthy,+ tokens,}return acc