: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
chore(tests): stop unit tests inheriting production hog timeouts (#100555)
Georges-Antoine Asside6db018b390
diff --git a/.agents/skills/writing-tests/SKILL.md b/.agents/skills/writing-tests/SKILL.mdindex 7ec9cdd15cc6..62c063f00e8e 100644--- a/.agents/skills/writing-tests/SKILL.md+++ b/.agents/skills/writing-tests/SKILL.md@@ -185,6 +185,17 @@ Escalating to the next rung is the last resort, not the default.The library may also read a different clock than the one you sampled — delta-rs time travel resolves a datetime against the `_delta_log` commit files' mtimes, not the `timestamp` that `DeltaTable.history()` reports.Such a test passes on macOS and fails every rerun on a fast Linux runner, so retries don't save it and it blames whichever PR is in the merge queue.Set the times yourself — `os.utime` on the file, an explicit `created_at` on the row — minutes apart, and pick a cutoff between them. That is also the production shape, where the two events are seconds apart.+- **A test must not inherit a production timeout, latency budget, or retry deadline.**+ Code that carries a time budget reads it from config, and a test that calls that code without overriding it asserts how fast the CI runner is.+ Nothing at the call site shows this.+ `tester.invoke(...)` in a hog template test takes its 550ms budget from `CDP_WATCHER_HOG_COST_TIMING_UPPER_MS`, and `executeLogTransformation(bytecode, record, globals, {})` takes 10ms from `DEFAULT_LOG_TRANSFORMATION_TIMEOUT_MS`; both are defined two files away and neither is named in the test.+ Such a test passes with a wide margin on an idle laptop and fails on a loaded shard, where it reports the timeout as a wrong result: a hog transformation that runs out of budget returns `status: 'failed'`, so the assertion reads `Expected: "mutated" / Received: "failed"` and names neither the clock nor the budget.+ Pass the budget explicitly, large enough that it cannot bind. The test then asserts behavior, and the production number stays a production decision.+ Assert the whole result object rather than one field of it: `expect(outcome).toMatchObject({ status: 'mutated' })` prints the error on failure, `expect(outcome.status).toEqual('mutated')` hides it.+- **Don't assert wall-clock duration.**+ `expect(elapsedMs).toBeLessThan(2000)` measures the runner, not the code, and on shared CI the runner is whatever else is running on it.+ It is usually dead as well: when the code under test already has a shorter internal budget, that budget trips first, so the duration assertion can never be the one that fails.+ If a unit test must cover scale, assert the output at scale — every key present, nothing truncated — and leave the timing to a benchmark.- **No real network / live external services.** Mock the boundary.- **No cross-test ordering.**Tests must pass in any order and in isolation; don't rely on state a previous test left behind.diff --git a/.agents/skills/writing-tests/references/mistakes-we-make.md b/.agents/skills/writing-tests/references/mistakes-we-make.mdindex 7f258d987b0a..70c22908f03f 100644--- a/.agents/skills/writing-tests/references/mistakes-we-make.md+++ b/.agents/skills/writing-tests/references/mistakes-we-make.md@@ -69,6 +69,11 @@ Reach for the right tool instead of writing a test that proves nothing.The catch is an `assertNumQueries` / query-count bound or reviewing the printed predicate — not a happy-path test.Honest note: in our own history these shipped verified by hand, not by an automated bound — [#61864](https://github.com/PostHog/posthog/pull/61864) (unbound `team_id` → scan) pins only an RPC name through a mock, and [#62417](https://github.com/PostHog/posthog/pull/62417) (indexed column wrapped in `toString`) asserts input validation, not query shape. That gap is exactly what a query-bound test would close.+- **Performance regressions.**+ A wall-clock assertion in the unit suite measures the runner it lands on, not the code.+ [#93974](https://github.com/PostHog/posthog/pull/93974) guarded a linear flatten with `expect(elapsedMs).toBeLessThan(2000)`, but the hog VM's own 550ms budget trips first, so that assertion could never be the one to fail. The case still flaked on loaded runners and kicked unrelated PRs out of the merge queue.+ A complexity guard belongs in a benchmark. In the unit suite, assert the output at scale instead, with the execution budget raised so it cannot bind.+- **Migration / apply-time ordering.**Code reads a table before its migration creates it — [#59873](https://github.com/PostHog/posthog/pull/59873), a ClickHouse migration read `posthog_instancesetting` before it existed under parallel migration.No checked-in test guards this; the safety net is CI migration replay, which exercises the ordering. Don't write a unit test pretending to.@@ -86,5 +91,5 @@ Reach for the right tool instead of writing a test that proves nothing.These dominate incident _volume_ but are prevented by monitoring, capacity, and alerting — never a unit test.-- **Resource exhaustion under load** — OOM, connection-pool starvation, event-loop blocking. Load-dependent; prevention is capacity and alerting. (A _known_ accidental O(n) can get a targeted perf test; the load itself cannot.)+- **Resource exhaustion under load** — OOM, connection-pool starvation, event-loop blocking. Load-dependent; prevention is capacity and alerting. (A _known_ accidental O(n) can get a targeted benchmark; neither the load nor a wall-clock assertion in the unit suite can stand in for one.)- **Infrastructure / third-party failure** — node crashes, DNS or network changes, disk exhaustion, upstream-provider outages. Root cause sits below the application; remediation is runbooks and monitoring.diff --git a/nodejs/src/cdp/templates/_transformations/flatten-properties/flatten-properties.template.test.ts b/nodejs/src/cdp/templates/_transformations/flatten-properties/flatten-properties.template.test.tsindex 1cfbea8748f2..124821e9752d 100644--- a/nodejs/src/cdp/templates/_transformations/flatten-properties/flatten-properties.template.test.ts+++ b/nodejs/src/cdp/templates/_transformations/flatten-properties/flatten-properties.template.test.ts@@ -2,8 +2,10 @@ import { HogFunctionInvocationGlobals } from '../../../types'import { TemplateTester } from '../../test/test-helpers'import { template } from './flatten-properties.template'+const NON_BINDING_TIMEOUT_MS = 10_000+describe('flatten-properties.template', () => {- const tester = new TemplateTester(template)+ const tester = new TemplateTester(template, { executionTimeoutMs: NON_BINDING_TIMEOUT_MS })beforeEach(async () => {await tester.beforeEach()@@ -92,18 +94,14 @@ describe('flatten-properties.template', () => {expect(properties).toEqual({ any: [{ nested: 'property' }] })})- it('flattens a very wide payload in linear time', async () => {+ it('flattens every key of a very wide payload', async () => {const wide: Record<string, any> = {}for (let i = 0; i < 5000; i++) {wide[`k${i}`] = { nested: i }}- const start = performance.now()const properties = await invoke({ outer: wide })- const elapsedMs = performance.now() - startexpect(properties.outer__k0__nested).toBe(0)expect(properties.outer__k4999__nested).toBe(4999)- // The host-side flatten is linear, so this stays well under the transformation time budget.- expect(elapsedMs).toBeLessThan(2000)})})diff --git a/nodejs/src/cdp/templates/_transformations_log/transformation-log-templates.test.ts b/nodejs/src/cdp/templates/_transformations_log/transformation-log-templates.test.tsindex ab62df0890a7..c23a62b00a56 100644--- a/nodejs/src/cdp/templates/_transformations_log/transformation-log-templates.test.ts+++ b/nodejs/src/cdp/templates/_transformations_log/transformation-log-templates.test.ts@@ -35,6 +35,8 @@ const createRecord = (overrides: Partial<LogRecord> = {}): LogRecord => ({...overrides,})+const NON_BINDING_TIMEOUT_MS = 5_000+const run = async (code: string,record: LogRecord,@@ -42,7 +44,7 @@ const run = async (): Promise<{ outcome: LogTransformationOutcome; record: LogRecord }> => {const bytecode = await compileHog(code)const globals = buildLogRecordGlobals(record, PROJECT, inputs)- const outcome = executeLogTransformation(bytecode, record, globals, {})+ const outcome = executeLogTransformation(bytecode, record, globals, { timeoutMs: NON_BINDING_TIMEOUT_MS })return { outcome, record }}@@ -50,45 +52,44 @@ describe('transformation_log templates', () => {describe('default', () => {it('returns the record unchanged', async () => {const { outcome, record } = await run(logDefaultTemplate.code, createRecord())- expect(outcome.status).toEqual('mutated')+ expect(outcome).toMatchObject({ status: 'mutated' })expect(record.body).toEqual('user [email protected] logged in')})})describe('pii-scrub', () => {- it('redacts emails, API keys, and bearer tokens from the body', async () => {- const body = 'login [email protected] key sk_live_abcdef123456 auth Bearer abcdef012345 done'- const { outcome, record } = await run(logPiiScrubTemplate.code, createRecord({ body }), {+ test.each([+ {+ name: 'redacts emails, API keys, and bearer tokens from the body',+ body: 'login [email protected] key sk_live_abcdef123456 auth Bearer abcdef012345 done',replacement: '[REDACTED]',- })- expect(outcome.status).toEqual('mutated')- expect(record.body).toEqual('login [REDACTED] key [REDACTED] auth [REDACTED] done')- })-- it('redacts a base64 bearer token, whose alphabet includes + / and =', async () => {- // Standard base64 credentials are the common case and were surviving: the- // token pattern stopped at the first character outside its class, leaving too- // few characters to meet the length floor, so nothing matched at all.- const body = 'auth Bearer YWJjZGVm+Z2hpamts/bW5vcHFy== done'- const { record } = await run(logPiiScrubTemplate.code, createRecord({ body }), {+ expected: 'login [REDACTED] key [REDACTED] auth [REDACTED] done',+ },+ {+ // Standard base64 credentials are the common case and were surviving: the+ // token pattern stopped at the first character outside its class, leaving too+ // few characters to meet the length floor, so nothing matched at all.+ name: 'redacts a base64 bearer token, whose alphabet includes + / and =',+ body: 'auth Bearer YWJjZGVm+Z2hpamts/bW5vcHFy== done',replacement: '[REDACTED]',- })- expect(record.body).toEqual('auth [REDACTED] done')- })-- it('honors a custom replacement value', async () => {- const { record } = await run(logPiiScrubTemplate.code, createRecord({ body: 'x [email protected] y' }), {+ expected: 'auth [REDACTED] done',+ },+ {+ name: 'honors a custom replacement value',+ body: 'x [email protected] y',replacement: '***',- })- expect(record.body).toEqual('x *** y')- })-- it('leaves a null body untouched', async () => {- const { outcome, record } = await run(logPiiScrubTemplate.code, createRecord({ body: null }), {+ expected: 'x *** y',+ },+ {+ name: 'leaves a null body untouched',+ body: null,replacement: '[REDACTED]',- })- expect(outcome.status).toEqual('mutated')- expect(record.body).toBeNull()+ expected: null,+ },+ ])('$name', async ({ body, replacement, expected }) => {+ const { outcome, record } = await run(logPiiScrubTemplate.code, createRecord({ body }), { replacement })+ expect(outcome).toMatchObject({ status: 'mutated' })+ expect(record.body).toEqual(expected)})})@@ -97,21 +98,21 @@ describe('transformation_log templates', () => {const { outcome } = await run(logDropBySeverityTemplate.code, createRecord({ severity_text: 'debug' }), {severitiesToDrop: 'debug,trace',})- expect(outcome.status).toEqual('dropped')+ expect(outcome).toMatchObject({ status: 'dropped' })})it('keeps severities not in the list', async () => {const { outcome } = await run(logDropBySeverityTemplate.code, createRecord({ severity_text: 'error' }), {severitiesToDrop: 'debug,trace',})- expect(outcome.status).toEqual('mutated')+ expect(outcome).toMatchObject({ status: 'mutated' })})it('matches case-insensitively against the lowercased severity', async () => {const { outcome } = await run(logDropBySeverityTemplate.code, createRecord({ severity_text: 'debug' }), {severitiesToDrop: 'DEBUG',})- expect(outcome.status).toEqual('dropped')+ expect(outcome).toMatchObject({ status: 'dropped' })})})@@ -122,7 +123,7 @@ describe('transformation_log templates', () => {createRecord({ attributes: { user_email: '"[email protected]"', keep: '"me"' } }),{ attributeKeys: 'user_email' })- expect(outcome.status).toEqual('mutated')+ expect(outcome).toMatchObject({ status: 'mutated' })const attributes = record.attributes ?? {}expect(parseJSON(attributes.user_email)).toMatch(/^[a-f0-9]{64}$/)expect(attributes.keep).toEqual('"me"')@@ -134,7 +135,7 @@ describe('transformation_log templates', () => {createRecord({ attributes: { keep: '"me"' } }),{ attributeKeys: 'user_email,user.id' })- expect(outcome.status).toEqual('mutated')+ expect(outcome).toMatchObject({ status: 'mutated' })expect(record.attributes).toEqual({ keep: '"me"' })})})diff --git a/nodejs/src/cdp/templates/test/test-helpers.ts b/nodejs/src/cdp/templates/test/test-helpers.tsindex 756fc83e6bff..b0f27558cf95 100644--- a/nodejs/src/cdp/templates/test/test-helpers.ts+++ b/nodejs/src/cdp/templates/test/test-helpers.ts@@ -184,13 +184,19 @@ export class TemplateTester {public mockTeamManager = {getTeam: jest.fn().mockResolvedValue({ id: 1, secret_api_token: 'test-secret-token' }),}- constructor(private _template: HogFunctionTemplate) {+ constructor(+ private _template: HogFunctionTemplate,+ options: { executionTimeoutMs?: number } = {}+ ) {this.template = {..._template,bytecode: [],}this.mockHub = { ...defaultConfig } as any+ if (options.executionTimeoutMs !== undefined) {+ this.mockHub.CDP_WATCHER_HOG_COST_TIMING_UPPER_MS = options.executionTimeoutMs+ }this.hogExecutor = this.createHogExecutor()this.nativeExecutor = new NativeDestinationExecutorService(defaultConfig)