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.

fix(cdp): shrink the hog invocation results payload (#59616)

Ben Whitee7992dbef518
diff --git a/nodejs/src/cdp/consumers/cdp-rerun-worker.consumer.ts b/nodejs/src/cdp/consumers/cdp-rerun-worker.consumer.ts
index 6672255aae44..d15d122d4fcb 100644
--- a/nodejs/src/cdp/consumers/cdp-rerun-worker.consumer.ts
+++ b/nodejs/src/cdp/consumers/cdp-rerun-worker.consumer.ts
@@ -95,10 +95,6 @@ export class CdpRerunWorkerConsumer extends CdpConsumerBase<PluginsServerConfig>
this.clickhouseClient,
this.hogFunctionManager,
this.hogFlowManager,
- // Used at rerun time to rebuild `inputs` (the templated/resolved
- // input bundle including secrets) from the current hog function
- // config, since we strip `inputs` from the persisted globals.
- this.hogInputsService,
this.invocationResultsService.invocationResultsRowsService,
this.jobQueues,
this.invocationResultsService.monitoringService,
diff --git a/nodejs/src/cdp/rerun/rerun-e2e.test.ts b/nodejs/src/cdp/rerun/rerun-e2e.test.ts
index 20ed99c849fe..62ee777d250d 100644
--- a/nodejs/src/cdp/rerun/rerun-e2e.test.ts
+++ b/nodejs/src/cdp/rerun/rerun-e2e.test.ts
@@ -11,11 +11,13 @@ import { Clickhouse } from '~/tests/helpers/clickhouse'
import { waitForExpect } from '~/tests/helpers/expectations'
import { ensureKafkaTopics, resetKafka } from '~/tests/helpers/kafka'
import { getFirstTeam, resetTestDatabase } from '~/tests/helpers/sql'
+import { PostgresPersonRepository } from '~/worker/ingestion/persons/repositories/postgres-person-repository'
import { KAFKA_HOG_INVOCATION_RESULTS, KAFKA_INGESTION_WARNINGS } from '../../config/kafka-topics'
import { KafkaProducerWrapper } from '../../kafka/producer'
import { Hub, Team } from '../../types'
import { closeHub, createHub } from '../../utils/db/hub'
+import { UUIDT } from '../../utils/utils'
import { HOG_FILTERS_EXAMPLES, HOG_INPUTS_EXAMPLES } from '../_tests/examples'
import { insertHogFunction as _insertHogFunction, createHogExecutionGlobals } from '../_tests/fixtures'
import { CdpCyclotronWorker } from '../consumers/cdp-cyclotron-worker.consumer'
@@ -39,6 +41,7 @@ interface PersistedRow {
attempts: number
error_kind: string
function_kind: string
+ invocation_globals: string
}
/**
@@ -159,6 +162,22 @@ describe('CDP hog invocation rerun e2e', () => {
mockProducerObserver = new KafkaProducerObserver(kafkaProducer)
team = await getFirstTeam(hub.postgres)
+
+ // The rerun strips `person` from invocation_globals — the cyclotron
+ // worker reloads it via getCyclotronPerson(distinct_id). Seed a real
+ // person so the rerun can resolve `{person}` in the function's inputs.
+ await new PostgresPersonRepository(hub.postgres).createPerson(
+ DateTime.now(),
+ { email: '[email protected]' },
+ {},
+ {},
+ team.id,
+ null,
+ true,
+ new UUIDT().toString(),
+ { distinctId: 'distinct_id' }
+ )
+
mockProducerObserver.resetKafkaProducer()
hub.CDP_FETCH_RETRIES = 0
@@ -261,13 +280,19 @@ describe('CDP hog invocation rerun e2e', () => {
}, 30_000)
const originalRows = await clickhouse.query<PersistedRow>(
- `SELECT invocation_id, status, is_retry, attempts, error_kind, function_kind
+ `SELECT invocation_id, status, is_retry, attempts, error_kind, function_kind, invocation_globals
FROM hog_invocation_results
WHERE team_id = ${team.id} AND function_id = '${fnFetch.id}' AND status = 'succeeded'`
)
const originalInvocationId = originalRows[0].invocation_id
expect(originalRows[0].is_retry).toBe(0)
expect(originalRows[0].function_kind).toBe('hog_function')
+ // invocation_globals is stored gzip+base64'd, not raw JSON — base64
+ // never starts with `{`. The rerun below proves the round-trip: it can
+ // only rehydrate and re-run if `decodeInvocationGlobals` decompresses
+ // this value correctly.
+ expect(originalRows[0].invocation_globals.length).toBeGreaterThan(0)
+ expect(originalRows[0].invocation_globals.startsWith('{')).toBe(false)
// The prior cyclotron_jobs row is in a terminal 'completed' state by
// this point. The rerun path's `overwriteExisting: true` upsert
// (cyclotron-v2 ON CONFLICT) handles the PK collision without us
diff --git a/nodejs/src/cdp/rerun/rerun-paginator.routing.test.ts b/nodejs/src/cdp/rerun/rerun-paginator.routing.test.ts
index 1aa2cc65ba5c..825db9306b18 100644
--- a/nodejs/src/cdp/rerun/rerun-paginator.routing.test.ts
+++ b/nodejs/src/cdp/rerun/rerun-paginator.routing.test.ts
@@ -1,7 +1,6 @@
import { DateTime } from 'luxon'
import { CyclotronJobConflictError } from '../services/cyclotron-v2'
-import { HogInputsService } from '../services/hog-inputs.service'
import { HogFlowManagerService } from '../services/hogflows/hogflow-manager.service'
import { CyclotronJobQueuePostgresV2 } from '../services/job-queue/job-queue-postgres-v2'
import { JobQueue } from '../services/job-queue/job-queue.interface'
@@ -49,7 +48,6 @@ describe('RerunPaginatorService queue routing', () => {
{} as any,
{} as unknown as HogFunctionManagerService,
{} as unknown as HogFlowManagerService,
- {} as unknown as HogInputsService,
invocationResultsRowsService,
{ hog_function: hogQueue, hog_flow: hogflowQueue },
monitoringService,
diff --git a/nodejs/src/cdp/rerun/rerun-paginator.service.test.ts b/nodejs/src/cdp/rerun/rerun-paginator.service.test.ts
index 067dd4b42b69..a68e21c073a8 100644
--- a/nodejs/src/cdp/rerun/rerun-paginator.service.test.ts
+++ b/nodejs/src/cdp/rerun/rerun-paginator.service.test.ts
@@ -16,7 +16,6 @@ import { closeHub, createHub } from '../../utils/db/hub'
import { UUIDT } from '../../utils/utils'
import { insertHogFunction as _insertHogFunction, createHogExecutionGlobals } from '../_tests/fixtures'
import { createCdpOutputsRegistry } from '../outputs/registry'
-import { HogInputsService } from '../services/hog-inputs.service'
import { HogFlowManagerService } from '../services/hogflows/hogflow-manager.service'
import { CyclotronJobQueuePostgresV2 } from '../services/job-queue/job-queue-postgres-v2'
import { JobQueue } from '../services/job-queue/job-queue.interface'
@@ -60,7 +59,6 @@ describe('RerunPaginatorService integration', () => {
let paginatorMonitoringService: jest.Mocked<HogFunctionMonitoringService>
let hogFunctionManager: HogFunctionManagerService
let hogFlowManager: jest.Mocked<HogFlowManagerService>
- let hogInputsService: jest.Mocked<HogInputsService>
beforeAll(() => {
clickhouse = Clickhouse.create()
@@ -166,19 +164,13 @@ describe('RerunPaginatorService integration', () => {
hogFunctionManager = new HogFunctionManagerService(hub.postgres, hub.pubSub, hub.encryptedFields)
hogFunctionManager['onHogFunctionsReloaded'](team.id, [hogFunction.id])
- // Hog flow manager and inputs service stay mocked — this suite focuses on the
- // hog-function path and the CH query/rehydrate logic. Hog flow rehydration is
+ // Hog flow manager stays mocked — this suite focuses on the hog-function
+ // path and the CH query/rehydrate logic. Hog flow rehydration is
// exercised structurally (rest of the same code path) but not end-to-end here.
hogFlowManager = {
getHogFlow: jest.fn().mockResolvedValue(null),
} as unknown as jest.Mocked<HogFlowManagerService>
- hogInputsService = {
- buildInputsWithGlobals: jest
- .fn()
- .mockImplementation((_fn, globals) => Promise.resolve({ ...globals, inputs: { resolved: true } })),
- } as unknown as jest.Mocked<HogInputsService>
-
hogQueue = {
queueInvocations: jest.fn().mockResolvedValue(undefined),
} as unknown as jest.Mocked<JobQueue>
@@ -206,7 +198,6 @@ describe('RerunPaginatorService integration', () => {
chClient,
hogFunctionManager,
hogFlowManager,
- hogInputsService,
paginatorLifecycleService,
{ hog_function: hogQueue, hog_flow: hogflowQueue },
paginatorMonitoringService,
@@ -299,7 +290,7 @@ describe('RerunPaginatorService integration', () => {
expect(next.progress.done).toBe(true)
})
- it('rebuilds inputs via HogInputsService rather than trusting the stored payload', async () => {
+ it('re-enqueues bare globals — inputs are not stored or pre-resolved by the paginator', async () => {
await seedRows([{ invocation_id: 'inv-rebuild', status: 'failed', error: new Error('boom') }])
const state = buildState({
@@ -314,14 +305,12 @@ describe('RerunPaginatorService integration', () => {
await paginator.processPage(team.id, state, { jobId: 'test-rerun-job', createdAt: DateTime.now() })
- expect(hogInputsService.buildInputsWithGlobals).toHaveBeenCalledTimes(1)
- const [fn, persistedGlobals] = hogInputsService.buildInputsWithGlobals.mock.calls[0]
- expect(fn.id).toBe(hogFunction.id)
- // The persisted globals were stripped of `inputs` before storage.
- expect(persistedGlobals).not.toHaveProperty('inputs')
-
+ // The re-enqueued invocation carries no resolved `inputs` — the
+ // executor rebuilds them from the current hog function config at
+ // run time, so the rerun never trusts a stored snapshot.
const enqueued = hogQueue.queueInvocations.mock.calls[0][0] as CyclotronJobInvocationHogFunction[]
- expect((enqueued[0].state.globals as any).inputs).toEqual({ resolved: true })
+ expect(enqueued).toHaveLength(1)
+ expect(enqueued[0].state.globals).not.toHaveProperty('inputs')
})
})
@@ -480,7 +469,6 @@ describe('RerunPaginatorService integration', () => {
brokenChClient,
hogFunctionManager,
hogFlowManager,
- hogInputsService,
paginatorLifecycleService,
{ hog_function: hogQueue, hog_flow: hogflowQueue },
paginatorMonitoringService,
diff --git a/nodejs/src/cdp/rerun/rerun-paginator.service.ts b/nodejs/src/cdp/rerun/rerun-paginator.service.ts
index eb3e96919624..095653054509 100644
--- a/nodejs/src/cdp/rerun/rerun-paginator.service.ts
+++ b/nodejs/src/cdp/rerun/rerun-paginator.service.ts
@@ -2,23 +2,24 @@ import { ClickHouseClient } from '@clickhouse/client'
import { DateTime } from 'luxon'
import { Counter } from 'prom-client'
-import { parseJSON } from '../../utils/json-parse'
import { logger } from '../../utils/logger'
import { CyclotronJobConflictError } from '../services/cyclotron-v2'
-import { HogInputsService } from '../services/hog-inputs.service'
import { createHogFlowInvocation } from '../services/hogflows/hogflow-executor.service'
import { HogFlowManagerService } from '../services/hogflows/hogflow-manager.service'
import { CyclotronJobQueuePostgresV2 } from '../services/job-queue/job-queue-postgres-v2'
import { JobQueue } from '../services/job-queue/job-queue.interface'
import { HogFunctionManagerService } from '../services/managers/hog-function-manager.service'
import { HogFunctionMonitoringService } from '../services/monitoring/hog-function-monitoring.service'
-import { HogInvocationResultsService } from '../services/monitoring/hog-invocation-results.service'
+import {
+ HogInvocationResultsService,
+ decodeInvocationGlobals,
+} from '../services/monitoring/hog-invocation-results.service'
import {
CyclotronJobInvocation,
CyclotronJobInvocationHogFlow,
CyclotronJobInvocationHogFunction,
HogFunctionFilterGlobals,
- HogFunctionInvocationGlobals,
+ HogFunctionInvocationGlobalsWithInputs,
} from '../types'
import { convertToHogFunctionFilterGlobal } from '../utils/hog-function-filtering'
import { RERUN_PAGE_SIZE, RerunFunctionKind, RerunJobProgress, RerunJobState } from './rerun-job.types'
@@ -105,7 +106,6 @@ export class RerunPaginatorService {
private clickhouse: ClickHouseClient,
private hogFunctionManager: HogFunctionManagerService,
private hogFlowManager: HogFlowManagerService,
- private hogInputsService: HogInputsService,
private invocationResultsRowsService: HogInvocationResultsService,
// Re-enqueue targets keyed by function kind — see RerunJobQueues.
private jobQueues: RerunJobQueues,
@@ -440,39 +440,56 @@ export class RerunPaginatorService {
rows: InvocationRow[]
): Promise<{ queued: number; skipped: number; queuedInvocations: CyclotronJobInvocation[] }> {
const maxAttempts = state.request.filter.max_attempts
- const queuedInvocations: CyclotronJobInvocation[] = []
- let skipped = 0
- for (const row of rows) {
- if (maxAttempts !== undefined && row.attempts >= maxAttempts) {
- counterRerunInvocationsSkipped.labels(state.function_kind, 'over_max_attempts').inc()
- skipped++
- continue
- }
- try {
- const invocation = await this.rehydrateInvocation(teamId, state.function_kind, state.function_id, row)
- if (!invocation) {
- counterRerunInvocationsSkipped.labels(state.function_kind, 'rehydrate_failed').inc()
- skipped++
- continue
+ // Rehydrate the whole page concurrently — `addGroupsToGlobals` and the
+ // hog function manager are LazyLoader-backed and batch their DB lookups
+ // across concurrent callers, so a sequential loop would defeat that.
+ const rehydrated = await Promise.all(
+ rows.map(async (row): Promise<CyclotronJobInvocation | null> => {
+ if (maxAttempts !== undefined && row.attempts >= maxAttempts) {
+ counterRerunInvocationsSkipped.labels(state.function_kind, 'over_max_attempts').inc()
+ return null
+ }
+ try {
+ const invocation = await this.rehydrateInvocation(
+ teamId,
+ state.function_kind,
+ state.function_id,
+ row
+ )
+ if (!invocation) {
+ counterRerunInvocationsSkipped.labels(state.function_kind, 'rehydrate_failed').inc()
+ }
+ return invocation
+ } catch (e) {
+ logger.error('Rerun failed to rehydrate invocation', {
+ error: e instanceof Error ? e.message : String(e),
+ invocation_id: row.invocation_id,
+ })
+ counterRerunInvocationsSkipped.labels(state.function_kind, 'exception').inc()
+ return null
}
- // Rerun-start lifecycle row. is_retry/attempts are derived from
- // `state.rerunAttempts` (set by rehydrateInvocation above). The
- // matching terminal row is written by the worker when the
- // invocation finishes — same derivation, same is_retry=1.
- this.invocationResultsRowsService.queueLifecycleRow(invocation, 'running')
- queuedInvocations.push(invocation)
- } catch (e) {
- logger.error('Rerun failed to rehydrate invocation', {
- error: e instanceof Error ? e.message : String(e),
- invocation_id: row.invocation_id,
- })
- counterRerunInvocationsSkipped.labels(state.function_kind, 'exception').inc()
- skipped++
+ })
+ )
+
+ const queuedInvocations: CyclotronJobInvocation[] = []
+ for (const invocation of rehydrated) {
+ if (!invocation) {
+ continue
}
+ // Rerun-start lifecycle row. is_retry/attempts are derived from
+ // `state.rerunAttempts` (set by rehydrateInvocation). The matching
+ // terminal row is written by the worker when the invocation
+ // finishes — same derivation, same is_retry=1.
+ this.invocationResultsRowsService.queueLifecycleRow(invocation, 'running')
+ queuedInvocations.push(invocation)
}
- return { queued: queuedInvocations.length, skipped, queuedInvocations }
+ return {
+ queued: queuedInvocations.length,
+ skipped: rows.length - queuedInvocations.length,
+ queuedInvocations,
+ }
}
private async rehydrateInvocation(
@@ -483,7 +500,7 @@ export class RerunPaginatorService {
): Promise<CyclotronJobInvocation | null> {
let parsedGlobals: unknown
try {
- parsedGlobals = parseJSON(row.invocation_globals)
+ parsedGlobals = await decodeInvocationGlobals(row.invocation_globals)
} catch {
return null
}
@@ -493,18 +510,18 @@ export class RerunPaginatorService {
if (!hogFunction || hogFunction.team_id !== teamId) {
return null
}
- // The persisted globals have `inputs` stripped — secrets stay out
- // of ClickHouse. Re-resolve inputs here from the current hog function
- // config + integration store, which also gives the rerun run any
- // input changes the user made since the original invocation.
- const persistedGlobals = parsedGlobals as HogFunctionInvocationGlobals
- const globalsWithInputs = await this.hogInputsService.buildInputsWithGlobals(hogFunction, persistedGlobals)
+ // The persisted globals are minimal — `inputs`, `groups` and
+ // `person` are all stripped. Re-enqueue as-is: the cyclotron worker
+ // rehydrates `groups`/`person` and the executor rebuilds `inputs`
+ // from the current hog function config, so the rerun runs against
+ // the latest config/secrets rather than a stored snapshot.
+ const persistedGlobals = parsedGlobals as HogFunctionInvocationGlobalsWithInputs
const invocation: CyclotronJobInvocationHogFunction = {
// Preserve invocation_id so lifecycle rows collapse under the
// ReplacingMergeTree on the same key.
id: row.invocation_id,
state: {
- globals: globalsWithInputs,
+ globals: persistedGlobals,
timings: [],
// `attempts` is the fetch-retry counter and is reset to 0
// for the rerun run. `rerunAttempts` (read from the
diff --git a/nodejs/src/cdp/services/hog-executor.service.ts b/nodejs/src/cdp/services/hog-executor.service.ts
index 83918bdb2c07..0c338847a036 100644
--- a/nodejs/src/cdp/services/hog-executor.service.ts
+++ b/nodejs/src/cdp/services/hog-executor.service.ts
@@ -407,8 +407,12 @@ export class HogExecutorService {
let execRes: ExecResult | undefined = undefined
try {
- // NOTE: As of the mappings work, we added input generation to the caller, reducing the amount of data passed into the function
- // This is just a fallback to support the old format - once fully migrated we can remove the building and just use the globals
+ // Build inputs here when the invocation arrives without them.
+ // This is a supported path, not a transitional fallback: the
+ // rerun pipeline deliberately re-enqueues invocations with only
+ // the bare globals so the run resolves inputs against the
+ // current hog function config. Callers that pre-resolve inputs
+ // (e.g. the mappings path) skip the rebuild.
if (invocation.state.globals.inputs) {
globals = invocation.state.globals
} else {
diff --git a/nodejs/src/cdp/services/monitoring/hog-invocation-results.service.test.ts b/nodejs/src/cdp/services/monitoring/hog-invocation-results.service.test.ts
index b4b29b211a36..a347c32c4223 100644
--- a/nodejs/src/cdp/services/monitoring/hog-invocation-results.service.test.ts
+++ b/nodejs/src/cdp/services/monitoring/hog-invocation-results.service.test.ts
@@ -5,7 +5,11 @@ import { IngestionOutputs } from '~/ingestion/outputs/ingestion-outputs'
import { parseJSON } from '../../../utils/json-parse'
import { createExampleInvocation } from '../../_tests/fixtures'
import { CdpOutput } from '../../cdp-services'
-import { HogInvocationResultRow, HogInvocationResultsService } from './hog-invocation-results.service'
+import {
+ HogInvocationResultRow,
+ HogInvocationResultsService,
+ decodeInvocationGlobals,
+} from './hog-invocation-results.service'
const buildOutputsMock = (): jest.Mocked<IngestionOutputs<CdpOutput>> => {
return {
@@ -88,18 +92,43 @@ describe('HogInvocationResultsService', () => {
const rows = parseProducedRows(outputs)
expect(rows).toHaveLength(1)
- const globals = parseJSON(rows[0].invocation_globals) as Record<string, any>
+ const globals = (await decodeInvocationGlobals(rows[0].invocation_globals)) as Record<string, any>
- // The event/person/project context we care about is preserved.
+ // The event context we care about is preserved.
expect(globals.event?.uuid).toBeDefined()
- expect(globals.person?.id).toBeDefined()
+ expect(globals.project?.id).toBeDefined()
// But `inputs` is gone entirely.
expect(globals).not.toHaveProperty('inputs')
- // And the serialized blob does not mention the secret anywhere
+ // And the decoded payload does not mention the secret anywhere
// (catches the case where a future schema change moves inputs
// under a different key without us noticing).
- expect(rows[0].invocation_globals).not.toContain('sk-super-secret')
- expect(rows[0].invocation_globals).not.toContain('abc123')
+ const decoded = JSON.stringify(globals)
+ expect(decoded).not.toContain('sk-super-secret')
+ expect(decoded).not.toContain('abc123')
+ })
+
+ it('strips groups and person from invocation_globals — rebuilt downstream on rerun', async () => {
+ const invocation = createExampleInvocation({}, {
+ groups: {
+ organization: {
+ id: 'org-1',
+ type: 'organization',
+ index: 0,
+ url: 'http://localhost',
+ properties: { plan: 'enterprise', seats: 500 },
+ },
+ },
+ } as any)
+ service.queueLifecycleRow(invocation, 'running')
+ await service.flush()
+
+ const rows = parseProducedRows(outputs)
+ const globals = (await decodeInvocationGlobals(rows[0].invocation_globals)) as Record<string, any>
+ expect(globals).not.toHaveProperty('groups')
+ expect(globals).not.toHaveProperty('person')
+ // The event — the rerun trigger — is kept.
+ expect(globals.event?.uuid).toBeDefined()
+ expect(globals.project?.id).toBeDefined()
})
it('marks is_retry=1 and attempts=N when state.rerunAttempts is set', async () => {
@@ -251,6 +280,42 @@ describe('HogInvocationResultsService', () => {
})
})
+ describe('invocation_globals compression', () => {
+ it('produces invocation_globals as a compressed blob that round-trips back to the event', async () => {
+ const invocation = createExampleInvocation({}, {
+ event: {
+ uuid: 'event-uuid-rt',
+ event: '$pageview',
+ elements_chain: '',
+ distinct_id: 'distinct-rt',
+ url: 'http://localhost',
+ properties: { $current_url: 'https://posthog.com', big: 'x'.repeat(5000) },
+ timestamp: '2026-05-01T00:00:00Z',
+ },
+ } as any)
+ service.queueLifecycleRow(invocation, 'running')
+ await service.flush()
+
+ const rows = parseProducedRows(outputs)
+ const stored = rows[0].invocation_globals
+ // On the wire the field is a base64 blob — never raw JSON.
+ expect(stored.startsWith('{')).toBe(false)
+ // A repetitive 5KB event compresses well below its raw size.
+ expect(stored.length).toBeLessThan(JSON.stringify(invocation.state.globals.event).length)
+ // And it decodes back to the original event payload intact.
+ const globals = (await decodeInvocationGlobals(stored)) as Record<string, any>
+ expect(globals.event).toEqual(invocation.state.globals.event)
+ })
+
+ it('decodes legacy uncompressed (raw JSON) rows unchanged', async () => {
+ const legacy = JSON.stringify({ event: { uuid: 'legacy-uuid' }, project: { id: 7 } })
+ expect(await decodeInvocationGlobals(legacy)).toEqual({
+ event: { uuid: 'legacy-uuid' },
+ project: { id: 7 },
+ })
+ })
+ })
+
// Silence unused import linter noise — DateTime is imported for future tests
// that exercise queueScheduledAt explicitly.
void DateTime
diff --git a/nodejs/src/cdp/services/monitoring/hog-invocation-results.service.ts b/nodejs/src/cdp/services/monitoring/hog-invocation-results.service.ts
index d066d53e6eb8..bde2ba9d603f 100644
--- a/nodejs/src/cdp/services/monitoring/hog-invocation-results.service.ts
+++ b/nodejs/src/cdp/services/monitoring/hog-invocation-results.service.ts
@@ -1,9 +1,12 @@
+import { promisify } from 'node:util'
+import { gunzip, gzip } from 'node:zlib'
import { Counter, Gauge } from 'prom-client'
import { HOG_INVOCATION_RESULTS_OUTPUT, HogInvocationResultsOutput } from '~/ingestion/common/outputs'
import { IngestionOutputs } from '~/ingestion/outputs/ingestion-outputs'
import { safeClickhouseString } from '../../../utils/db/utils'
+import { parseJSON } from '../../../utils/json-parse'
import { logger } from '../../../utils/logger'
import { captureException } from '../../../utils/posthog'
import type { CdpOutput } from '../../cdp-services'
@@ -68,7 +71,7 @@ export interface HogInvocationResultRow {
event_uuid: string
distinct_id: string
person_id: string
- invocation_globals: string // pre-serialized JSON
+ invocation_globals: string // globals JSON (inputs/groups/person stripped) — gzip+base64'd on produce
version: string // microsecond-precision UInt64; serialized as string to dodge JS's 53-bit precision
is_deleted: 0 | 1
}
@@ -201,15 +204,16 @@ const stripInputs = <T>(value: T): T => {
return out as T
}
-// The full payload that the rerun path needs to rehydrate the invocation.
-// For hog functions this is the globals tree (event, person, groups, etc.) —
-// with `inputs` stripped, see `stripInputs`. For hog flows it's the workflow
-// context (event, personId, variables, actionStepCount). Worker-side ZSTD
-// compression on the ClickHouse column keeps the storage cost down; we
-// serialize plain JSON here.
+// The payload the rerun path needs to rehydrate the invocation, kept minimal.
+// `inputs`, `groups` and `person` are all dropped: the cyclotron worker
+// rehydrates `groups`/`person` (loadHogFunctions) and the executor rebuilds
+// `inputs` when an invocation arrives without them — so the rerun reconstructs
+// everything from the event against the latest config. `inputs` must be
+// dropped anyway for security (resolved secrets — see `stripInputs`).
const serializeInvocationGlobals = (invocation: CyclotronJobInvocation): string => {
if (isHogFunctionInvocation(invocation)) {
- return JSON.stringify(stripInputs(invocation.state.globals))
+ const { groups: _groups, person: _person, ...globals } = invocation.state.globals
+ return JSON.stringify(stripInputs(globals))
}
if (isHogFlowInvocation(invocation)) {
// Hog flow state can carry a per-action `currentAction.hogFunctionState.globals.inputs`
@@ -219,6 +223,31 @@ const serializeInvocationGlobals = (invocation: CyclotronJobInvocation): string
return '{}'
}
+const gzipAsync = promisify(gzip)
+const gunzipAsync = promisify(gunzip)
+
+// `invocation_globals` is the bulk of every lifecycle row. Warpstream meters
+// the uncompressed message bytes, so gzipping this one field before produce
+// directly cuts cyclotron throughput. The row envelope stays plain JSON — only
+// this field is opaque — so the ClickHouse Kafka engine still parses the
+// message as JSONEachRow. `decodeInvocationGlobals` is the inverse.
+const compressInvocationGlobals = async (globalsJson: string): Promise<string> => {
+ return (await gzipAsync(globalsJson)).toString('base64')
+}
+
+/**
+ * Inverse of `compressInvocationGlobals`. Used by the rerun paginator to read
+ * `invocation_globals` back off ClickHouse. Rows written before field
+ * compression landed are still raw JSON — base64 can never start with `{`, so
+ * the prefix is an unambiguous discriminator for the legacy fallback.
+ */
+export const decodeInvocationGlobals = async (stored: string): Promise<unknown> => {
+ if (stored.startsWith('{')) {
+ return parseJSON(stored)
+ }
+ return parseJSON((await gunzipAsync(Buffer.from(stored, 'base64'))).toString('utf8'))
+}
+
const sumDurationMs = (invocation: CyclotronJobInvocation): number | null => {
if (!isHogFunctionInvocation(invocation)) {
return null
@@ -456,8 +485,15 @@ export class HogInvocationResultsService {
hogInvocationResultsPendingMessages.set(0)
await Promise.all(
- rows.map((row) => {
- const value = Buffer.from(safeClickhouseString(JSON.stringify(row)))
+ rows.map(async (row) => {
+ const value = Buffer.from(
+ safeClickhouseString(
+ JSON.stringify({
+ ...row,
+ invocation_globals: await compressInvocationGlobals(row.invocation_globals),
+ })
+ )
+ )
return this.outputs
.produce(HOG_INVOCATION_RESULTS_OUTPUT, {
// Partition by invocation_id so all rows for a single