: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): add enforce mode to the self-loop guard (depth-counter) (#65548)
Daniel Marchuk1097f88f9aa7
diff --git a/nodejs/src/cdp/config.ts b/nodejs/src/cdp/config.tsindex 380822d39cb6..eecc2994b375 100644--- a/nodejs/src/cdp/config.ts+++ b/nodejs/src/cdp/config.ts@@ -227,9 +227,9 @@ export function getDefaultCdpConfig(): CdpConfig {CDP_FETCH_RETRIES: 3,CDP_FETCH_BACKOFF_BASE_MS: 1000,CDP_FETCH_BACKOFF_MAX_MS: 30000,- // Observe-only by default: detect self-loops and emit metrics without blocking.- // Valid values: 'disabled' | 'warn'. A blocking 'enforce' mode will be added in a- // follow-up PR once cdp_self_loop_guard_total production data is in.+ // Observe-only by default. Values: 'disabled' | 'warn' | 'enforce'. 'warn' detects+ // and emits cdp_self_loop_guard_total without blocking; 'enforce' bounds true loops+ // at SELF_LOOP_MAX_DEPTH hops. Roll out warn -> enforce per environment.CDP_SELF_LOOP_GUARD_MODE: 'warn',CDP_OVERFLOW_QUEUE_ENABLED: false,HOG_FUNCTION_MONITORING_APP_METRICS_TOPIC: KAFKA_APP_METRICS_2,diff --git a/nodejs/src/cdp/services/hog-executor.service.test.ts b/nodejs/src/cdp/services/hog-executor.service.test.tsindex ace8730d2be9..58182e46d6dd 100644--- a/nodejs/src/cdp/services/hog-executor.service.test.ts+++ b/nodejs/src/cdp/services/hog-executor.service.test.ts@@ -21,7 +21,7 @@ import { compileHog } from '../templates/compiler'import { HOG_EXAMPLES, HOG_FILTERS_EXAMPLES, HOG_INPUTS_EXAMPLES } from '../_tests/examples'import { createExampleInvocation, createHogExecutionGlobals, createHogFunction } from '../_tests/fixtures'import { EXTEND_OBJECT_KEY, isConnectionLevelError } from './hog-executor.service'-import { selfLoopGuardCounter } from './self-loop-guard'+import { SELF_LOOP_DEPTH_PROPERTY, selfLoopGuardCounter } from './self-loop-guard'// Mock before importing fetchjest.mock('~/utils/request', () => {@@ -1983,20 +1983,49 @@ describe('Hog Executor', () => {} as any)}- const setMode = (mode: 'disabled' | 'warn'): void => {+ const setMode = (mode: 'disabled' | 'warn' | 'enforce'): void => {;(executor as any).config.selfLoopGuardMode = mode}const ownTokenCaptureBody = (): string =>JSON.stringify({ api_key: OWN_TOKEN, event: 'replicated', distinct_id: 'u1', properties: {} })- // The detected count is the production signal that drives the enforce decision,- // so assert it actually moves - not just the human-facing log.- const readDetectedCount = async (): Promise<number> => {+ // Seed this destination's own self-loop depth (keyed by its function id).+ const setSelfLoopDepth = (invocation: CyclotronJobInvocationHogFunction, depth: number): void => {+ invocation.state.globals.event.properties = {+ ...invocation.state.globals.event.properties,+ [SELF_LOOP_DEPTH_PROPERTY]: { [invocation.hogFunction.id]: depth },+ }+ }++ // Seed a high depth for a DIFFERENT function - simulates an event that passed+ // through an unrelated deep chain. Must not count toward this destination.+ const setOtherFunctionDepth = (invocation: CyclotronJobInvocationHogFunction, depth: number): void => {+ invocation.state.globals.event.properties = {+ ...invocation.state.globals.event.properties,+ [SELF_LOOP_DEPTH_PROPERTY]: { 'some-other-function-id': depth },+ }+ }++ // Capture the body sent to the (mocked) ingest endpoint without a real network call.+ const captureIngestFetch = (): { getBody: () => string | undefined } => {+ let sentBody: string | undefined+ ;(fetch as jest.Mock).mockImplementationOnce((_url: string, options: any) => {+ sentBody = options.body+ return Promise.resolve({ status: 200, headers: {}, text: () => Promise.resolve('ok') })+ })+ return { getBody: () => sentBody }+ }++ const readActionCount = async (mode: string, action: string): Promise<number> => {const metric = await selfLoopGuardCounter.get()- return metric.values.find((v) => v.labels.mode === 'warn' && v.labels.action === 'detected')?.value ?? 0+ return metric.values.find((v) => v.labels.mode === mode && v.labels.action === action)?.value ?? 0}+ // The detected count is the production signal that drives the enforce decision,+ // so assert it actually moves - not just the human-facing log.+ const readDetectedCount = (): Promise<number> => readActionCount('warn', 'detected')+it('detects a self-referential ingest fetch and logs + meters it without blocking (warn)', async () => {setMode('warn')mockOwnTeam()@@ -2058,6 +2087,100 @@ describe('Hog Executor', () => {// Detection failing must not surface as a destination error.expect(result.error).toBeUndefined()})++ // Every hop under the cap is allowed and its outgoing body stamped with this+ // destination's next depth - including hop 0 (a fresh external event), which a+ // legitimate run always is.+ it.each([+ { case: 'fresh hop 0 (a legitimate external run)', depth: 0, stampedTo: 1 },+ { case: 'mid-chain under the cap', depth: 2, stampedTo: 3 },+ { case: 'the last hop under the cap', depth: 9, stampedTo: 10 },+ ])('enforce: allows + stamps the next hop ($case)', async ({ depth, stampedTo }) => {+ setMode('enforce')+ mockOwnTeam()+ const invocation = await createFetchInvocation({+ url: INGEST_URL,+ method: 'POST',+ body: ownTokenCaptureBody(),+ })+ setSelfLoopDepth(invocation, depth)+ const sent = captureIngestFetch()+ const blockedBefore = await readActionCount('enforce', 'blocked')++ const result = await executor.executeFetch(invocation)++ // Fetch proceeds, body carries this destination's incremented depth, nothing blocked.+ expect(result.error).toBeUndefined()+ expect(parseJSON(sent.getBody()!).properties[SELF_LOOP_DEPTH_PROPERTY][invocation.hogFunction.id]).toBe(+ stampedTo+ )+ expect(await readActionCount('enforce', 'blocked')).toBe(blockedBefore)+ })++ // The whole point of per-function depth: an event that arrived carrying a huge+ // depth for a DIFFERENT function is treated as depth 0 here, so a legitimately+ // running destination is never blocked by an unrelated deep chain.+ it('enforce: does NOT block when the high depth belongs to another function', async () => {+ setMode('enforce')+ mockOwnTeam()+ const invocation = await createFetchInvocation({+ url: INGEST_URL,+ method: 'POST',+ body: ownTokenCaptureBody(),+ })+ setOtherFunctionDepth(invocation, 50)+ const sent = captureIngestFetch()+ const blockedBefore = await readActionCount('enforce', 'blocked')++ const result = await executor.executeFetch(invocation)++ // Allowed, stamped as this destination's first hop, not blocked.+ expect(result.error).toBeUndefined()+ expect(parseJSON(sent.getBody()!).properties[SELF_LOOP_DEPTH_PROPERTY][invocation.hogFunction.id]).toBe(+ 1+ )+ expect(await readActionCount('enforce', 'blocked')).toBe(blockedBefore)+ })++ it('enforce: breaks the chain once it reaches the cap', async () => {+ setMode('enforce')+ mockOwnTeam()+ const invocation = await createFetchInvocation({+ url: INGEST_URL,+ method: 'POST',+ body: ownTokenCaptureBody(),+ })+ setSelfLoopDepth(invocation, 10)+ mockRequest.mockClear()+ const blockedBefore = await readActionCount('enforce', 'blocked')++ const result = await executor.executeFetch(invocation)++ // Blocked: error set, finished, no fetch attempted, metric moved.+ expect(result.error).toBeInstanceOf(Error)+ expect(result.finished).toBe(true)+ expect(mockRequest).not.toHaveBeenCalled()+ expect(await readActionCount('enforce', 'blocked')).toBe(blockedBefore + 1)+ expect(cleanLogs(result.logs.map((l) => l.message))).toEqual(+ expect.arrayContaining([expect.stringContaining('event-forwarding loop has already repeated')])+ )+ })++ it('enforce: leaves a normal external fetch untouched', async () => {+ setMode('enforce')+ mockOwnTeam()+ const invocation = await createFetchInvocation({+ url: `${baseUrl}/test`,+ method: 'POST',+ body: ownTokenCaptureBody(),+ })+ mockRequest.mockClear()++ const result = await executor.executeFetch(invocation)++ expect(result.error).toBeUndefined()+ expect(mockRequest).toHaveBeenCalled()+ })})})diff --git a/nodejs/src/cdp/services/hog-executor.service.ts b/nodejs/src/cdp/services/hog-executor.service.tsindex a8388c80d565..80d8a3621246 100644--- a/nodejs/src/cdp/services/hog-executor.service.ts+++ b/nodejs/src/cdp/services/hog-executor.service.ts@@ -37,7 +37,10 @@ import { HogInputsService } from './hog-inputs.service'import { EmailService } from './messaging/email.service'import { RecipientTokensService } from './messaging/recipient-tokens.service'import {+ SELF_LOOP_MAX_DEPTH,SelfLoopGuardMode,+ getSelfLoopDepth,+ injectSelfLoopDepth,isPostHogIngestUrl,isSelfReferentialIngestFetch,selfLoopGuardCounter,@@ -770,24 +773,46 @@ export class HogExecutorService {}}- // Observe-only detection of event-forwarding loops: a fetch back into this- // project's own ingestion endpoint re-enters the pipeline and can re-trigger this- // same function. We only measure for now (a follow-up will design enforcement from- // this signal). The ingest-URL check gates the team lookup so external fetches (the- // common case) pay nothing, and the whole block fails open - detection must never- // break a destination it was only meant to watch.- if (this.config.selfLoopGuardMode !== 'disabled' && isPostHogIngestUrl(params.url)) {+ // Bound event-forwarding loops: a fetch back into this project's own ingestion+ // endpoint re-enters the pipeline and can re-trigger this same function. The+ // ingest-URL check gates the team lookup so external fetches (the common case) pay+ // nothing, and the whole block fails open - the guard must never break a destination+ // it was only meant to protect.+ const guardMode = this.config.selfLoopGuardMode+ if (guardMode !== 'disabled' && isPostHogIngestUrl(params.url)) {try {const team = await this.asyncContext.teamManager.getTeam(invocation.teamId)if (team && isSelfReferentialIngestFetch({ url: params.url, body: params.body, team })) {- selfLoopGuardCounter.inc({ mode: this.config.selfLoopGuardMode, action: 'detected' })- addLog(- 'warn',- `This fetch targets a PostHog ingestion endpoint using this project's own API key, which can form an event-forwarding loop. To capture an event back into this project use the 'postHogCapture' helper, or to enrich incoming events use a transformation.`- )+ // Depth is counted per function id, so this destination is bounded only+ // by how many times IT has re-fed itself - an event that merely passed+ // through other functions can never trip the guard for it.+ const functionId = invocation.hogFunction.id+ const depth = getSelfLoopDepth(invocation.state.globals.event?.properties, functionId)++ if (guardMode === 'warn') {+ selfLoopGuardCounter.inc({ mode: guardMode, action: 'detected' })+ addLog(+ 'warn',+ `This fetch targets a PostHog ingestion endpoint using this project's own API key, which can form an event-forwarding loop. To capture an event back into this project use the 'postHogCapture' helper, or to enrich incoming events use a transformation.`+ )+ } else if (depth >= SELF_LOOP_MAX_DEPTH) {+ // enforce, this destination has re-fed itself to the cap - break it.+ selfLoopGuardCounter.inc({ mode: guardMode, action: 'blocked' })+ addLog(+ 'error',+ `Refusing to fetch a PostHog ingestion endpoint using this project's own API key - this destination's event-forwarding loop has already repeated ${SELF_LOOP_MAX_DEPTH} times. To capture an event back into this project use the 'postHogCapture' helper, or to enrich incoming events use a transformation.`+ )+ result.error = new Error('Self-referential event-forwarding loop blocked at max depth')+ result.finished = true+ return result+ } else {+ // enforce, under the cap - stamp this destination's next hop and proceed.+ selfLoopGuardCounter.inc({ mode: guardMode, action: 'allowed_with_counter' })+ params.body = injectSelfLoopDepth(params.body, functionId, depth + 1)+ }}} catch (err) {- logger.warn('🦔', '[HogExecutor] Self-loop guard detection skipped due to an internal error', {+ logger.warn('🦔', '[HogExecutor] Self-loop guard skipped due to an internal error', {error: err,teamId: invocation.teamId,})diff --git a/nodejs/src/cdp/services/self-loop-guard.test.ts b/nodejs/src/cdp/services/self-loop-guard.test.tsindex 31d8ecaec54a..42abe8a15318 100644--- a/nodejs/src/cdp/services/self-loop-guard.test.ts+++ b/nodejs/src/cdp/services/self-loop-guard.test.ts@@ -1,5 +1,13 @@import { Team } from '../../types'-import { extractRequestApiKey, isPostHogIngestUrl, isSelfReferentialIngestFetch } from './self-loop-guard'+import { parseJSON } from '../../utils/json-parse'+import {+ SELF_LOOP_DEPTH_PROPERTY,+ extractRequestApiKey,+ getSelfLoopDepth,+ injectSelfLoopDepth,+ isPostHogIngestUrl,+ isSelfReferentialIngestFetch,+} from './self-loop-guard'// Synthetic, non-production values. OWN_TOKEN is the project the destination runs in;// OTHER_TOKEN is a different project (legitimate cross-project replication).@@ -152,4 +160,99 @@ describe('self-loop-guard', () => {expect(detect(args)).toBe(expected)})})++ describe('getSelfLoopDepth / injectSelfLoopDepth (per-function)', () => {+ const FN = '019c6797-f409-0000-6b4c-d452176ca3c8'+ const OTHER_FN = '019d9077-abe4-0000-cd1e-be1d3ab0289f'++ it("stamps this function's depth onto a single-event body, preserving existing properties", () => {+ const props = parseJSON(+ injectSelfLoopDepth(captureBody('alpha', { foo: 'bar' }), FN, 3) as string+ ).properties+ expect(props.foo).toBe('bar')+ expect(props[SELF_LOOP_DEPTH_PROPERTY]).toEqual({ [FN]: 3 })+ })++ it("stamps this function's depth onto every entry of a batch body", () => {+ const parsed = parseJSON(injectSelfLoopDepth(batchBody(['a', 'b']), FN, 5) as string)+ expect(parsed.batch.map((e: any) => e.properties[SELF_LOOP_DEPTH_PROPERTY][FN])).toEqual([5, 5])+ })++ it("preserves other functions' depths in the map - only its own entry is touched", () => {+ const seeded = JSON.stringify({+ api_key: OWN_TOKEN,+ event: 'alpha',+ properties: { [SELF_LOOP_DEPTH_PROPERTY]: { [OTHER_FN]: 7 } },+ })+ expect(+ parseJSON(injectSelfLoopDepth(seeded, FN, 1) as string).properties[SELF_LOOP_DEPTH_PROPERTY]+ ).toEqual({+ [OTHER_FN]: 7,+ [FN]: 1,+ })+ })++ it('round-trips: reads back the depth it stamped for the same function', () => {+ const props = parseJSON(injectSelfLoopDepth(captureBody('alpha'), FN, 4) as string).properties+ expect(getSelfLoopDepth(props, FN)).toBe(4)+ })++ // A seeded array passes a naive object check but JSON.stringify drops the stamped key,+ // which would let the loop run uncapped. The array must be discarded for a real map.+ it('replaces a seeded array depth map with a real object that survives serialization', () => {+ const seeded = JSON.stringify({+ api_key: OWN_TOKEN,+ event: 'alpha',+ properties: { [SELF_LOOP_DEPTH_PROPERTY]: [1, 2, 3] },+ })+ const props = parseJSON(injectSelfLoopDepth(seeded, FN, 1) as string).properties+ expect(props[SELF_LOOP_DEPTH_PROPERTY]).toEqual({ [FN]: 1 })+ expect(getSelfLoopDepth(props, FN)).toBe(1)+ })++ // The cross-block regression: a destination is bounded ONLY by its own re-entries.+ // A huge depth for a *different* function must read as 0 for ours, so a deep chain of+ // unrelated functions can never trip the guard for a legitimately-running destination.+ it.each([+ { case: 'no depth map at all', properties: {}, expected: 0 },+ {+ case: 'a different function deep in the map (cross-block case)',+ properties: { [SELF_LOOP_DEPTH_PROPERTY]: { [OTHER_FN]: 50 } },+ expected: 0,+ },+ { case: 'malformed (non-object) map', properties: { [SELF_LOOP_DEPTH_PROPERTY]: 9 }, expected: 0 },+ { case: 'this function present', properties: { [SELF_LOOP_DEPTH_PROPERTY]: { [FN]: 6 } }, expected: 6 },+ // Untrusted input: a project owner can seed these on the event to try to delay the cap.+ {+ case: 'a seeded negative depth (bypass attempt) clamps to 0',+ properties: { [SELF_LOOP_DEPTH_PROPERTY]: { [FN]: -999 } },+ expected: 0,+ },+ {+ case: 'a non-finite depth is ignored',+ properties: { [SELF_LOOP_DEPTH_PROPERTY]: { [FN]: Infinity } },+ expected: 0,+ },+ {+ case: 'a fractional depth floors to an integer',+ properties: { [SELF_LOOP_DEPTH_PROPERTY]: { [FN]: 6.9 } },+ expected: 6,+ },+ {+ case: 'an array map (bypass attempt) reads as 0',+ properties: { [SELF_LOOP_DEPTH_PROPERTY]: [] },+ expected: 0,+ },+ ])('getSelfLoopDepth: $case -> $expected', ({ properties, expected }) => {+ expect(getSelfLoopDepth(properties as Record<string, unknown>, FN)).toBe(expected)+ })++ it.each([+ { case: 'unparseable', body: 'not-json{{' },+ { case: 'empty string', body: '' },+ { case: 'null', body: null },+ ])('returns a non-capture body unchanged: $case', ({ body }) => {+ expect(injectSelfLoopDepth(body, FN, 1)).toBe(body)+ })+ })})diff --git a/nodejs/src/cdp/services/self-loop-guard.ts b/nodejs/src/cdp/services/self-loop-guard.tsindex da3c1b05ecd0..da9d87814bc7 100644--- a/nodejs/src/cdp/services/self-loop-guard.ts+++ b/nodejs/src/cdp/services/self-loop-guard.ts@@ -8,10 +8,22 @@ import { parseJSON } from '../../utils/json-parse'// re-triggers the same destination, the chain forms an event-forwarding loop that// doubles traffic on every hop.//-// This is the observe-only stage: it detects the shape and emits a metric so we can-// measure real production traffic before designing enforcement. Modes are kept separate-// so a follow-up can add an enforcing mode without changing the detection surface.-export type SelfLoopGuardMode = 'disabled' | 'warn'+// - 'disabled': no-op.+// - 'warn': detect the shape and emit a metric, but never block (observe-only).+// - 'enforce': bound the loop by counting how many times *this specific destination* has+// re-fed the pipeline - allow the first SELF_LOOP_MAX_DEPTH hops, then break it.+export type SelfLoopGuardMode = 'disabled' | 'warn' | 'enforce'++// Event property carrying the self-loop depth *per hog function*, keyed by function id:+// { "<functionId>": <hops this destination has re-fed itself> }+// Keying by function id is deliberate: a destination is bounded only by its OWN re-entries,+// so an event that merely passed through many unrelated functions can never trip the guard+// for a legitimately-running destination. Distinct from the shared+// `$hog_function_execution_count` that bounds the `postHogCapture` path.+export const SELF_LOOP_DEPTH_PROPERTY = '$hog_function_self_loop_depth'++// Max self-capture hops, for a single destination, before its loop is broken.+export const SELF_LOOP_MAX_DEPTH = 10// Only these paths re-enter the event pipeline. Observability (`/i/v1/logs`) and the// REST API (`/api/...`, `/decide`) do NOT re-trigger event processing, so a fetch to@@ -23,7 +35,7 @@ const API_KEY_FIELDS = ['api_key', 'token', 'api_token'] as constexport const selfLoopGuardCounter = new Counter({name: 'cdp_self_loop_guard_total',- help: 'Count of fetches the self-loop guard detected as self-referential, by mode',+ help: 'Count of fetches the self-loop guard acted on, by mode and action',labelNames: ['mode', 'action'],})@@ -31,7 +43,8 @@ export const isPostHogIngestUrl = (urlString: string): boolean => {try {const url = new URL(urlString)const host = url.hostname.toLowerCase()- if (host !== 'posthog.com' && !host.endsWith('.posthog.com')) {+ const isIngestHost = host === 'posthog.com' || host.endsWith('.posthog.com')+ if (!isIngestHost) {return false}const path = url.pathname.replace(/\/+$/, '') || '/'@@ -88,3 +101,73 @@ export const isSelfReferentialIngestFetch = (input: {const requestToken = extractRequestApiKey(input.body, input.url)return requestToken !== null && ownsToken(input.team, requestToken)}++// How many times the given hog function has already re-fed the pipeline on this chain,+// read from the per-function depth map. Returns 0 when absent or malformed.+//+// The depth rides on event properties a project owner can set, so it is untrusted: clamp+// to a non-negative integer. Without this, a seeded negative value (e.g. -999) would read+// straight through and delay the cap by ~1000 hops; non-finite values are ignored too.+export const getSelfLoopDepth = (+ properties: Record<string, unknown> | null | undefined,+ functionId: string+): number => {+ const map = properties?.[SELF_LOOP_DEPTH_PROPERTY]+ if (map && typeof map === 'object' && !Array.isArray(map)) {+ const depth = (map as Record<string, unknown>)[functionId]+ if (typeof depth === 'number' && Number.isFinite(depth)) {+ return Math.max(0, Math.floor(depth))+ }+ }+ return 0+}++// Stamp the given function's incremented self-loop depth onto the outgoing capture body so+// the re-ingested event carries it forward. Only this function's entry is touched - other+// functions' depths in the map are preserved. Handles single-event and batch shapes.+// Returns the body unchanged if it can't be parsed as a capture payload.+export const injectSelfLoopDepth = (+ body: string | null | undefined,+ functionId: string,+ depth: number+): string | null | undefined => {+ if (!body) {+ return body+ }+ let parsed: unknown+ try {+ parsed = parseJSON(body)+ } catch {+ return body+ }+ if (!parsed || typeof parsed !== 'object') {+ return body+ }+ const stamp = (event: Record<string, unknown>): void => {+ const properties = (event.properties && typeof event.properties === 'object' ? event.properties : {}) as Record<+ string,+ unknown+ >+ // Reject an array here: it passes `typeof === 'object'` but `JSON.stringify` drops the+ // non-index `functionId` property, so a seeded array would silently lose the depth and+ // let the loop run uncapped. Start fresh instead.+ const existing = properties[SELF_LOOP_DEPTH_PROPERTY]+ const depthMap = (+ existing && typeof existing === 'object' && !Array.isArray(existing) ? existing : {}+ ) as Record<string, unknown>+ depthMap[functionId] = depth+ properties[SELF_LOOP_DEPTH_PROPERTY] = depthMap+ event.properties = properties+ }+ const obj = parsed as Record<string, unknown>+ if (Array.isArray(obj.batch)) {+ for (const entry of obj.batch) {+ if (entry && typeof entry === 'object') {+ stamp(entry as Record<string, unknown>)+ }+ }+ } else {+ stamp(obj)+ }+ return JSON.stringify(parsed)+}