: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): stop an empty clickhouse_event from 500ing a test invocation (#92664)
Daniel Marchukdcde9e5edcc5
diff --git a/nodejs/src/cdp/cdp-api.serial.test.ts b/nodejs/src/cdp/cdp-api.serial.test.tsindex 48b19b720df0..1980e8d94599 100644--- a/nodejs/src/cdp/cdp-api.serial.test.ts+++ b/nodejs/src/cdp/cdp-api.serial.test.ts@@ -160,10 +160,19 @@ describe('CDP API', () => {expect(res.status).toEqual(404)})- it('errors if missing values', async () => {+ it.each([+ ['nothing at all', {}],+ ['an empty clickhouse_event', { clickhouse_event: {} }],+ ['a clickhouse_event with no timestamp', { clickhouse_event: { event: '$pageview' } }],+ ['a clickhouse_event with a numeric timestamp', { clickhouse_event: { event: '$pageview', timestamp: 1 } }],+ [+ 'a clickhouse_event with an unparseable timestamp',+ { clickhouse_event: { event: '$pageview', timestamp: 'not-a-date' } },+ ],+ ])('errors if the body carries %s', async (_name, body) => {const res = await supertest(app).post(`/api/projects/${hogFunction.team_id}/hog_functions/${hogFunction.id}/invocations`)- .send({})+ .send(body)expect(res.status).toEqual(400)expect(res.body).toEqual({@@ -171,6 +180,26 @@ describe('CDP API', () => {})})+ it('still converts a clickhouse_event that has a timestamp but no event name', async () => {+ const res = await supertest(app)+ .post(`/api/projects/${hogFunction.team_id}/hog_functions/${hogFunction.id}/invocations`)+ .send({+ clickhouse_event: { uuid: new UUIDT().toString(), timestamp: '2021-09-28 14:00:00.000' },+ mock_async_functions: true,+ })++ expect(res.status).toEqual(200)+ })++ it('uses the given globals when clickhouse_event carries no event', async () => {+ const res = await supertest(app)+ .post(`/api/projects/${hogFunction.team_id}/hog_functions/${hogFunction.id}/invocations`)+ .send({ globals, clickhouse_event: {}, mock_async_functions: true })++ expect(res.status).toEqual(200)+ expect(res.body.errors).toEqual([])+ })+it("does not error if hog function is 'new'", async () => {const res = await supertest(app).post(`/api/projects/${hogFunction.team_id}/hog_functions/new/invocations`)diff --git a/nodejs/src/cdp/cdp-api.ts b/nodejs/src/cdp/cdp-api.tsindex 66ca2496d596..6ed2f7cc69eb 100644--- a/nodejs/src/cdp/cdp-api.ts+++ b/nodejs/src/cdp/cdp-api.ts@@ -66,6 +66,7 @@ import { HOG_FUNCTION_TEMPLATES } from './templates'import { HogFunctionInvocationGlobals, HogFunctionType, MinimalLogEntry } from './types'import {convertToHogFunctionInvocationGlobals,+ isConvertibleClickHouseEvent,isNativeHogFunction,isSegmentPluginHogFunction,sanitizeLogMessage,@@ -469,7 +470,7 @@ export class CdpApi {return res.status(404).json({ error: 'Team not found' })}- globals = clickhouse_event+ globals = isConvertibleClickHouseEvent(clickhouse_event)? convertToHogFunctionInvocationGlobals(clickhouse_event, team, this.config.SITE_URL): globals@@ -748,7 +749,7 @@ export class CdpApi {return res.status(404).json({ error: 'Hog flow not found' })}- const globals: HogFunctionInvocationGlobals | null = clickhouse_event+ const globals: HogFunctionInvocationGlobals | null = isConvertibleClickHouseEvent(clickhouse_event)? convertToHogFunctionInvocationGlobals(clickhouse_event,team,diff --git a/nodejs/src/cdp/utils.ts b/nodejs/src/cdp/utils.tsindex 1fe7b430f0e4..9ee88a26d93e 100644--- a/nodejs/src/cdp/utils.ts+++ b/nodejs/src/cdp/utils.ts@@ -4,9 +4,9 @@ import { gunzip, gzip } from 'zlib'import { parseJSON } from '~/common/utils/json-parse'import { sanitizeForUTF8 } from '~/common/utils/strings'-import { UUIDT, castTimestampOrNow, clickHouseTimestampToISO } from '~/common/utils/utils'+import { UUIDT, castTimestampOrNow, clickHouseTimestampToDateTime } from '~/common/utils/utils'-import { RawClickHouseEvent, Team, TimestampFormat } from '../types'+import { ClickHouseTimestamp, ISOTimestamp, RawClickHouseEvent, Team, TimestampFormat } from '../types'import { CdpInternalEvent } from './schema'import { HogFunctionInvocationGlobals, HogFunctionType, LogEntry, LogEntrySerialized, MinimalLogEntry } from './types'@@ -30,6 +30,29 @@ export const getPersonDisplayName = (team: Team, distinctId: string, properties:return (customIdentifier || String(distinctId))?.trim()}+// TRICKY: the timestamp can be an ISO one, for example when it comes from the test api, so both+// formats are accepted. Returns null rather than throwing, because a test-invocation body can carry+// a `clickhouse_event` that is not an event at all, such as the `{}` a caller sends for an optional+// field it has no value for.+export function parseClickHouseEventTimestamp(timestamp: unknown): ISOTimestamp | null {+ if (typeof timestamp !== 'string') {+ return null+ }+ if (DateTime.fromISO(timestamp).isValid) {+ return timestamp as ISOTimestamp+ }+ const parsed = clickHouseTimestampToDateTime(timestamp as ClickHouseTimestamp)+ return parsed.isValid ? (parsed.toISO() as ISOTimestamp) : null+}++export function isConvertibleClickHouseEvent(event: unknown): event is RawClickHouseEvent {+ return (+ !!event &&+ typeof event === 'object' &&+ parseClickHouseEventTimestamp((event as RawClickHouseEvent).timestamp) !== null+ )+}+// that we can keep to as a contractexport function convertToHogFunctionInvocationGlobals(event: RawClickHouseEvent,@@ -53,17 +76,8 @@ export function convertToHogFunctionInvocationGlobals(}}- // TRICKY: the timsestamp can sometimes be an ISO for example if coming from the test api- // so we need to handle that case- const eventTimestamp = DateTime.fromISO(event.timestamp).isValid- ? event.timestamp- : clickHouseTimestampToISO(event.timestamp)-- const eventCapturedAt = event.captured_at- ? DateTime.fromISO(event.captured_at).isValid- ? event.captured_at- : clickHouseTimestampToISO(event.captured_at)- : null+ const eventTimestamp = parseClickHouseEventTimestamp(event.timestamp)!+ const eventCapturedAt = parseClickHouseEventTimestamp(event.captured_at)const context: HogFunctionInvocationGlobals = {project: {diff --git a/products/cdp/backend/api/hog_function.py b/products/cdp/backend/api/hog_function.pyindex db59eacf7684..991cd1abf38d 100644--- a/products/cdp/backend/api/hog_function.py+++ b/products/cdp/backend/api/hog_function.py@@ -7,6 +7,7 @@ from django.db import transactionfrom django.db.models import Q, QuerySetfrom django.utils import timezone+import requestsimport structlogimport posthoganalyticsfrom django_filters import BaseInFilter, CharFilter, FilterSet@@ -175,6 +176,23 @@ def _named_warehouse_tables(entries: Any) -> list[Any]:]+def _worker_error_messages(response: requests.Response) -> list[str]:+ """The CDP worker's own description of a failed test invocation, as a list of messages."""+ try:+ body = response.json()+ except ValueError:+ body = None+ if isinstance(body, dict):+ for key in ("errors", "error", "detail"):+ value = body.get(key)+ if isinstance(value, list):+ return [str(item) for item in value]+ if value:+ return [str(value)]+ text = (response.text or "").strip()+ return [text] if text else [f"The worker returned {response.status_code}."]++def _without(value: Any, keys: tuple[str, ...]) -> Any:return {k: v for k, v in value.items() if k not in keys} if isinstance(value, dict) else value@@ -1185,7 +1203,9 @@ class HogFunctionViewSet()if res.status_code != 200:- return Response({"status": "error"}, status=res.status_code)+ # The worker's own message is the only description of the failure. Dropping it leaves the+ # caller with a bare status code and nothing to act on.+ return Response({"status": "error", "errors": _worker_error_messages(res)}, status=res.status_code)return Response(res.json())diff --git a/products/cdp/backend/api/test/test_hog_function.py b/products/cdp/backend/api/test/test_hog_function.pyindex 5b99dafad5bd..d80c58b780e4 100644--- a/products/cdp/backend/api/test/test_hog_function.py+++ b/products/cdp/backend/api/test/test_hog_function.py@@ -2157,6 +2157,30 @@ class TestHogFunctionAPI(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):"value": "http://localhost:2080/0e02d917-563f-4050-9725-aad881b69937",}+ @parameterized.expand(+ [+ ("errors_list", {"errors": ["Missing event"]}, ["Missing event"]),+ ("error_string", {"error": "Missing event"}, ["Missing event"]),+ ("no_body", None, ["Bad Gateway"]),+ ]+ )+ def test_failed_test_invocation_relays_the_worker_error(self, _name, worker_body, expected):+ with patch(+ "products.cdp.backend.api.hog_function.create_hog_invocation_test"+ ) as mock_create_hog_invocation_test:+ mock_create_hog_invocation_test.return_value = MagicMock(+ status_code=400 if worker_body else 502,+ json=(lambda: worker_body) if worker_body else MagicMock(side_effect=ValueError),+ text="Bad Gateway" if not worker_body else "",+ )++ response = self.client.post(+ f"/api/projects/{self.team.id}/hog_functions/new/invocations/",+ data={"configuration": {**EXAMPLE_FULL}},+ )++ assert response.json() == {"status": "error", "errors": expected}+# warehouse_source_webhook is intentionally omitted: it's excluded from the viewset queryset# entirely (see test_warehouse_source_webhook_excluded), so its rerun endpoint 404s before the# rerunnable-type guard is ever reached — it can't exercise the 400 this test asserts.