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(hogbox-preview): serve parallel requests in the preview web container (#111957)

Frank Hamand177f01e11329
diff --git a/posthog/wsgi.py b/posthog/wsgi.py
index 2324bfae1ef3..0ff9dfbb20ee 100644
--- a/posthog/wsgi.py
+++ b/posthog/wsgi.py
@@ -109,4 +109,9 @@ def application(environ, start_response):
# when the server calls the app off it. Inert unless the env flag is set.
install_memory_probe_handler()
_prewarmed = True
+ from products.tasks.backend.facade.streams import handle_task_run_event_ingest_wsgi # noqa: PLC0415
+
+ response = handle_task_run_event_ingest_wsgi(environ, start_response)
+ if response is not None:
+ return response
return _django_application(environ, start_response)
diff --git a/products/tasks/backend/facade/streams.py b/products/tasks/backend/facade/streams.py
index 51c93edf12b5..b3b6ba6250e2 100644
--- a/products/tasks/backend/facade/streams.py
+++ b/products/tasks/backend/facade/streams.py
@@ -15,7 +15,10 @@ from products.tasks.backend.logic.stream.backlog import (
parse_log_cursor,
session_update_type,
)
-from products.tasks.backend.logic.stream.event_ingest import handle_task_run_event_ingest
+from products.tasks.backend.logic.stream.event_ingest import (
+ handle_task_run_event_ingest,
+ handle_task_run_event_ingest_wsgi,
+)
from products.tasks.backend.logic.stream.redis_stream import (
TASK_RUN_STREAM_WAIT_DELAY_INCREMENT_SECONDS,
TASK_RUN_STREAM_WAIT_INITIAL_DELAY_SECONDS,
@@ -42,6 +45,7 @@ __all__ = [
"format_log_cursor",
"get_task_run_stream_key",
"handle_task_run_event_ingest",
+ "handle_task_run_event_ingest_wsgi",
"parse_log_cursor",
"reset_task_run_stream",
"run_stream_presence_gated",
diff --git a/products/tasks/backend/logic/stream/event_ingest.py b/products/tasks/backend/logic/stream/event_ingest.py
index fa22ecf859dc..ab6ed1de3542 100644
--- a/products/tasks/backend/logic/stream/event_ingest.py
+++ b/products/tasks/backend/logic/stream/event_ingest.py
@@ -3,17 +3,18 @@ from __future__ import annotations
import re
import json
import math
-from collections.abc import AsyncGenerator, Awaitable, Callable
+from collections.abc import AsyncGenerator, Awaitable, Callable, Iterable
from dataclasses import dataclass
from datetime import datetime
-from typing import Literal, cast
+from http import HTTPStatus
+from typing import BinaryIO, Literal, cast
from uuid import NAMESPACE_URL, uuid5
from django.conf import settings
from django.db import InterfaceError, OperationalError, close_old_connections
import structlog
-from asgiref.sync import sync_to_async
+from asgiref.sync import async_to_sync, sync_to_async
from jwt import PyJWTError
from posthog.ph_client import ph_scoped_capture
@@ -70,6 +71,9 @@ BUDGET_STEER_MODES = frozenset({"publish", "wrap_up"})
ASGIMessage = dict[str, object]
ASGIReceive = Callable[[], Awaitable[ASGIMessage]]
ASGISend = Callable[[ASGIMessage], Awaitable[None]]
+WSGIStartResponse = Callable[[str, list[tuple[str, str]]], object]
+
+WSGI_READ_CHUNK_BYTES = 64 * 1024
class ClientDisconnected(Exception):
@@ -192,6 +196,50 @@ async def handle_task_run_event_ingest(scope: ASGIMessage, receive: ASGIReceive,
return True
+def handle_task_run_event_ingest_wsgi(
+ environ: dict[str, object], start_response: WSGIStartResponse
+) -> Iterable[bytes] | None:
+ path = environ.get("PATH_INFO")
+ if not isinstance(path, str) or _match_event_ingest_route(path) is None:
+ return None
+
+ body_stream = cast(BinaryIO, environ["wsgi.input"])
+ sent: list[ASGIMessage] = []
+
+ async def receive() -> ASGIMessage:
+ chunk = body_stream.read(WSGI_READ_CHUNK_BYTES)
+ return {"type": "http.request", "body": chunk, "more_body": bool(chunk)}
+
+ async def send(message: ASGIMessage) -> None:
+ sent.append(message)
+
+ scope: ASGIMessage = {
+ "type": "http",
+ "method": environ.get("REQUEST_METHOD"),
+ "path": path,
+ "headers": [
+ (_wsgi_header_name(key).encode("latin-1"), value.encode("latin-1"))
+ for key, value in environ.items()
+ if isinstance(value, str) and (key.startswith("HTTP_") or key in ("CONTENT_TYPE", "CONTENT_LENGTH"))
+ ],
+ }
+ async_to_sync(handle_task_run_event_ingest)(scope, receive, send)
+ if not sent:
+ return []
+
+ status = cast(int, sent[0]["status"])
+ headers = [
+ (name.decode("latin-1"), value.decode("latin-1"))
+ for name, value in cast(list[tuple[bytes, bytes]], sent[0].get("headers", []))
+ ]
+ start_response(f"{status} {HTTPStatus(status).phrase}", headers)
+ return [cast(bytes, message.get("body", b"")) for message in sent[1:]]
+
+
+def _wsgi_header_name(environ_key: str) -> str:
+ return environ_key.removeprefix("HTTP_").replace("_", "-").lower()
+
+
async def _ingest_event_lines(
redis_stream: TaskRunRedisStream,
claims: SandboxEventIngestTokenPayload,
diff --git a/products/tasks/backend/tests/test_event_ingest.py b/products/tasks/backend/tests/test_event_ingest.py
index a82b22d814d8..07b8be88ac19 100644
--- a/products/tasks/backend/tests/test_event_ingest.py
+++ b/products/tasks/backend/tests/test_event_ingest.py
@@ -2,6 +2,7 @@ import json
import asyncio
import threading
from collections.abc import Sequence
+from io import BytesIO
from pathlib import Path
from uuid import NAMESPACE_URL, uuid5
@@ -30,6 +31,7 @@ from products.tasks.backend.logic.stream.event_ingest import (
STREAM_COMPLETE_CONTROL_TYPE,
_is_session_update,
handle_task_run_event_ingest,
+ handle_task_run_event_ingest_wsgi,
)
from products.tasks.backend.logic.stream.redis_stream import (
TASK_RUN_STREAM_SEQUENCE_TIMEOUT,
@@ -753,6 +755,40 @@ class TestTaskRunEventIngest(TestCase):
self.assertEqual(body["last_accepted_seq"], 2)
self.assertEqual(self._read_notification_methods(), ["first", "second"])
+ @parameterized.expand([("authorized", True, 200, ["first", "second"]), ("missing_token", False, 401, [])])
+ @override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)
+ def test_wsgi_ingest_matches_the_asgi_handler(
+ self, _name: str, authorized: bool, expected_status: int, expected_methods: list[str]
+ ) -> None:
+ lines = [
+ {"seq": 1, "event": {"type": "notification", "notification": {"method": "first"}}},
+ {"seq": 2, "event": {"type": "notification", "notification": {"method": "second"}}},
+ ]
+ environ: dict[str, object] = {
+ "REQUEST_METHOD": "POST",
+ "PATH_INFO": self._ingest_url(),
+ "wsgi.input": BytesIO("".join(json.dumps(line) + "\n" for line in lines).encode()),
+ }
+ if authorized:
+ environ["HTTP_AUTHORIZATION"] = f"Bearer {self._create_token()}"
+ statuses: list[str] = []
+
+ with patch.object(TaskRun, "heartbeat_workflow"):
+ response = handle_task_run_event_ingest_wsgi(environ, lambda status, _headers: statuses.append(status))
+
+ assert response is not None
+ self.assertEqual(int(statuses[0].split()[0]), expected_status)
+ self.assertIn("last_accepted_seq" if authorized else "error", json.loads(b"".join(response)))
+ self.assertEqual(self._read_notification_methods(), expected_methods)
+
+ def test_wsgi_ingest_ignores_other_paths(self) -> None:
+ environ: dict[str, object] = {
+ "REQUEST_METHOD": "GET",
+ "PATH_INFO": "/api/projects/1/tasks/",
+ "wsgi.input": BytesIO(),
+ }
+ self.assertIsNone(handle_task_run_event_ingest_wsgi(environ, lambda _status, _headers: None))
+
@override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)
def test_presence_gated_ingest_accepts_events_without_mirroring_them(self) -> None:
self.task_run.state = {**(self.task_run.state or {}), "stream_presence_gated": True}
diff --git a/tools/hogbox-preview/STARTUP.md b/tools/hogbox-preview/STARTUP.md
index 368cabf650c3..4e4775869ea2 100644
--- a/tools/hogbox-preview/STARTUP.md
+++ b/tools/hogbox-preview/STARTUP.md
@@ -59,6 +59,9 @@ pays for it:
Applied in `stack.py` `write_override` and in the golden's own bake
(hogland `scripts/posthog-preview-setup.sh`). The 118s→18s figure in the table
above predates granian and has not been re-measured.
+ One ASGI worker serves one sync request at a time, so the preview also sets
+ `GRANIAN_INTERFACE=wsgi` with `GRANIAN_BLOCKING_THREADS=16`. The single worker
+ then serves a page's parallel API calls from its thread pool.
- **Tighter poll intervals** (`run_long`/`wait_http_ok` 10s → 3s): each completed
step otherwise sits on up to 10s of dead air before we notice; a handful of
steps adds up.
diff --git a/tools/hogbox-preview/hogbox_preview/stack.py b/tools/hogbox-preview/hogbox_preview/stack.py
index a41834f10fbe..f16b35c8ddf3 100644
--- a/tools/hogbox-preview/hogbox_preview/stack.py
+++ b/tools/hogbox-preview/hogbox_preview/stack.py
@@ -365,9 +365,12 @@ class PostHogPreviewStack:
# a public preview URL can't be used to forge sessions on another.
f" - SECRET_KEY={self.secret_key}",
f" - OIDC_RSA_PRIVATE_KEY={self.oidc_private_key}",
- # A preview serves one user, and each worker costs a full Django import
- # at boot, so one worker reaches a serving /_health much sooner.
+ # Each worker costs a full Django import at boot, so a preview runs one.
+ # Under ASGI one worker serves one sync request at a time, and a page
+ # load fires dozens in parallel. WSGI serves them from a thread pool.
" - GRANIAN_WORKERS=1",
+ " - GRANIAN_INTERFACE=wsgi",
+ " - GRANIAN_BLOCKING_THREADS=16",
# master's Django hard-requires the personhog service for group-type
# lookups (require_personhog_client() raises "personhog client not
# configured" without it — #65968). Same addr the dev/hobby composes