: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(llm-gateway): declare the tables the gateway reads (#81387)
Brandon26cf7f2dd1e2
diff --git a/.agents/skills/auditing-llm-gateway-parity/SKILL.md b/.agents/skills/auditing-llm-gateway-parity/SKILL.mdindex 4b4e3a024312..9d2ef98ec0b8 100644--- a/.agents/skills/auditing-llm-gateway-parity/SKILL.md+++ b/.agents/skills/auditing-llm-gateway-parity/SKILL.md@@ -24,6 +24,7 @@ For the Python gateway, inspect:- `services/llm-gateway/src/llm_gateway/api/` for routes and wire behavior- `services/llm-gateway/src/llm_gateway/auth/` for accepted credentials+- `services/llm-gateway/src/llm_gateway/db/required_tables.py` for the tables the gateway may read; a change adding a table read needs its posthog-cloud-infra SELECT grant landed in every environment first- `services/llm-gateway/src/llm_gateway/products/config.py` for trusted product policy, models, and billing- `services/llm-gateway/src/llm_gateway/rate_limiting/` for budgets and limits- `services/llm-gateway/src/llm_gateway/callbacks/` for event attributiondiff --git a/.agents/skills/qa-team/references/incident-patterns.md b/.agents/skills/qa-team/references/incident-patterns.mdindex c732f91f25ce..7eb330da2b3e 100644--- a/.agents/skills/qa-team/references/incident-patterns.md+++ b/.agents/skills/qa-team/references/incident-patterns.md@@ -134,6 +134,7 @@ This document grounds QA review agents with real-world failure modes.- Hardcoded configuration requiring a full deploy cycle to change- Deployment rollback failing due to permission misconfiguration- Missing alerts for customer-facing services (multi-hour detection gaps)+- Application code adding reads of a resource its deployed least-privilege role has no grant for, with grants maintained in a separate infra repo; every test passes because suites run with privileged roles, and the mismatch first executes in production**Review signals:**@@ -142,6 +143,7 @@ This document grounds QA review agents with real-world failure modes.- Infrastructure changes to networking, CNI, service mesh- Config values that should be runtime-adjustable but are hardcoded- Missing alerting for new services or endpoints+- A first read of a new database table (or queue, bucket, secret) in a service whose runtime role has an explicit grant allowlist in another repo (e.g. `services/llm-gateway`, allowlist in posthog-cloud-infra)## Pattern 8: Cross-Service & Queue Processing Failuresdiff --git a/AGENTS.md b/AGENTS.mdindex 0e9b41078593..df2a90bc0be5 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -185,7 +185,7 @@ See [.agents/security.md](.agents/security.md) for security guidelines — least- **Object storage is SeaweedFS — do not add new MinIO dependencies.** Both S3-compatible stores in the dev/CI stack are SeaweedFS: the `objectstorage` service (S3 API on `:19000`) backs general object storage (`OBJECT_STORAGE_*` settings — exports, media uploads, error-tracking source maps, query cache, tasks), and the `seaweedfs` service (S3 API on `:8333`) backs session replay v2 (`SESSION_RECORDING_V2_S3_*` settings). MinIO now survives only as migration tooling: `docker-compose.hobby.yml` keeps it as a source for `bin/migrate-storage-hobby`, and `bin/upgrade-objectstorage` starts a throwaway MinIO to salvage objects off the pre-swap volume. Outside that, don't add docker-compose services, scripts, tests, or docs that stand up a `minio/minio` container. Code that talks to object storage should go through the existing `OBJECT_STORAGE_*` / `SESSION_RECORDING_V2_S3_*` config and a standard S3 client rather than hardcoding an endpoint — that keeps backends swappable. Note the `objectstorage` service registers its credentials at runtime via a bootstrap loop and returns `InvalidAccessKeyId` until that completes, so anything depending on it must wait for its readiness sentinel rather than just for the container to start.- **Temporal activity payloads have a ~2 MiB hard limit — pass large data by reference, not by value.** Activity inputs and outputs are serialized across a gRPC boundary that Temporal caps at ~2 MiB per payload (the server rejects larger payloads via `blobSizeLimitError`). As a conservative field-level rule, if a field could exceed ~256 KB once serialized (serialized query results, exported file contents, LLM context, rendered HTML, image bytes, unbounded `list[dict[str, Any]]`), write it to Postgres / S3 / object storage from _inside_ the activity and return only the reference (row ID, S3 key). The workflow already has access to any row ID created earlier in the same run; it does not need the content to flow back through. Shuttling large data through the workflow on the way to persistence is a foreseeable failure mode that produces `PayloadSizeError` (`TMPRL1103`) the moment the underlying data crosses the limit.- **Outbound calls to a third-party API that need rate-limiting or egress telemetry belong in `posthog/egress/` — add a `<domain>/` incarnation (GitHub is the reference) and route callers through its gated, recorded transport, never hand-rolled `requests`. See `posthog/egress/README.md`.**-- **`services/llm-gateway` is under an unofficial code freeze while callers move to [`PostHog/ai-gateway`](https://github.com/PostHog/ai-gateway).** New callers and features belong on the Go gateway by default. A Python gateway change needs a documented parity blocker for an active caller and must stay limited to that blocker. Read [`services/llm-gateway/PARITY.md`](services/llm-gateway/PARITY.md). Invoke `/auditing-llm-gateway-parity` for gateway contract changes and parity refreshes, `/finding-llm-gateway-migration-candidates` when deciding what to migrate next, and `/migrating-llm-gateway-callers` when moving a selected caller.+- **`services/llm-gateway` is under an unofficial code freeze while callers move to [`PostHog/ai-gateway`](https://github.com/PostHog/ai-gateway).** New callers and features belong on the Go gateway by default. A Python gateway change needs a documented parity blocker for an active caller and must stay limited to that blocker. Read [`services/llm-gateway/PARITY.md`](services/llm-gateway/PARITY.md). Invoke `/auditing-llm-gateway-parity` for gateway contract changes and parity refreshes, `/finding-llm-gateway-migration-candidates` when deciding what to migrate next, and `/migrating-llm-gateway-callers` when moving a selected caller. The gateway's Postgres role reads only an allowlisted set of tables, with grants maintained in posthog-cloud-infra: a new table read needs the SELECT grant landed there for every environment first, then a declaration in `services/llm-gateway/src/llm_gateway/db/required_tables.py`, which a test binds to the package's SQL.## Code Stylediff --git a/services/llm-gateway/README.md b/services/llm-gateway/README.mdindex 0e6b90edea0b..bdb53d0b78f6 100644--- a/services/llm-gateway/README.md+++ b/services/llm-gateway/README.md@@ -60,6 +60,14 @@ python manage.py setup_local_api_key --add-scopes llm_gateway:read`--add-scopes` merges into existing scopes without removing any.`--scopes` replaces all scopes on the key.+## Database access++The gateway connects to the PostHog Postgres as a least-privilege role whose SELECT+grants are a per-table allowlist maintained in posthog-cloud-infra. The tables the+gateway reads are declared in `src/llm_gateway/db/required_tables.py`, and+`tests/test_required_tables.py` binds that declaration to the SQL in the package. To+add a table read, land the grant in every environment first, then declare the table.+## User attributionWhen using an OAuth Access Token, the user who's token it is is the user used for analytics and rate limiting.diff --git a/services/llm-gateway/src/llm_gateway/db/required_tables.py b/services/llm-gateway/src/llm_gateway/db/required_tables.pynew file mode 100644index 000000000000..0b6f891c58cf--- /dev/null+++ b/services/llm-gateway/src/llm_gateway/db/required_tables.py@@ -0,0 +1,25 @@+"""Tables the gateway references in the PostHog Postgres database.++The gateway's role has SELECT only on a per-table allowlist in+posthog-cloud-infra (terraform, users.tf); a query outside it fails in+deployed environments only, since tests mock the database. Land the grant+in every environment before declaring a table here.+``tests/test_required_tables.py`` binds this set to the package's SQL.+"""++REQUIRED_TABLES: frozenset[str] = frozenset(+ {+ # Personal API key authentication+ "posthog_personalapikey",+ "posthog_user",+ # OAuth access token authentication+ "posthog_oauthaccesstoken",+ # Project-scope check+ "posthog_team",+ "posthog_organization",+ "posthog_organizationmembership",+ "ee_accesscontrol",+ "ee_role",+ "ee_rolemembership",+ }+)diff --git a/services/llm-gateway/tests/test_required_tables.py b/services/llm-gateway/tests/test_required_tables.pynew file mode 100644index 000000000000..3096fac45971--- /dev/null+++ b/services/llm-gateway/tests/test_required_tables.py@@ -0,0 +1,38 @@+"""Binds REQUIRED_TABLES to the package's SQL; drift otherwise first fails in production."""++import re+from pathlib import Path++from llm_gateway.db.required_tables import REQUIRED_TABLES++SRC_ROOT = Path(__file__).parent.parent / "src" / "llm_gateway"++# DELETE FROM is covered by FROM.+TABLE_REF = re.compile(r"\b(?:FROM|JOIN|INTO|UPDATE)\s+((?:posthog_|ee_)[a-z0-9_]+)", re.IGNORECASE)+++def referenced_tables() -> set[str]:+ tables: set[str] = set()+ for path in SRC_ROOT.rglob("*.py"):+ tables.update(match.lower() for match in TABLE_REF.findall(path.read_text(encoding="utf-8")))+ return tables+++def test_sql_table_references_match_declaration() -> None:+ referenced = referenced_tables()+ assert referenced, "table extraction found no SQL references; the regex or source layout changed"++ undeclared = referenced - REQUIRED_TABLES+ stale = REQUIRED_TABLES - referenced+ assert not undeclared, (+ f"SQL references tables missing from REQUIRED_TABLES: {sorted(undeclared)}. "+ "The gateway role cannot read a table without a SELECT grant in "+ "posthog-cloud-infra (terraform/environments/<env>/**/users.tf). "+ "Land the grant in every environment first, then declare the table in "+ "llm_gateway/db/required_tables.py."+ )+ assert not stale, (+ f"REQUIRED_TABLES declares tables no SQL references: {sorted(stale)}. "+ "Remove them from llm_gateway/db/required_tables.py so the declaration "+ "stays trustworthy (revoking the grant in posthog-cloud-infra is optional)."+ )