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.

feat(llm-gateway): verify table privileges at readiness (#81389)

Brandonaad983910786
diff --git a/AGENTS.md b/AGENTS.md
index df2a90bc0be5..295f7b486d86 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. 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.
+- **`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. The readiness probe verifies the connected role holds every declared grant on every probe, so a missing grant holds a rollout, and a revoked grant unreadies the running fleet, instead of serving 500s.
## Code Style
diff --git a/services/llm-gateway/README.md b/services/llm-gateway/README.md
index bdb53d0b78f6..027c58b5fd15 100644
--- a/services/llm-gateway/README.md
+++ b/services/llm-gateway/README.md
@@ -65,8 +65,10 @@ python manage.py setup_local_api_key --add-scopes llm_gateway:read
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.
+`tests/test_required_tables.py` binds that declaration to the SQL in the package.
+`/_readiness` verifies the connected role holds every declared grant on every probe,
+so a revoked grant unreadies serving pods as well as new rollouts. To add a table
+read, land the grant in every environment first, then declare the table.
## User attribution
diff --git a/services/llm-gateway/src/llm_gateway/api/health.py b/services/llm-gateway/src/llm_gateway/api/health.py
index d732fff42bbf..f615ce0d1677 100644
--- a/services/llm-gateway/src/llm_gateway/api/health.py
+++ b/services/llm-gateway/src/llm_gateway/api/health.py
@@ -2,7 +2,7 @@ import logging
from fastapi import APIRouter, HTTPException, Request
-from llm_gateway.db.postgres import acquire_connection
+from llm_gateway.db.postgres import acquire_connection, missing_table_privileges
logger = logging.getLogger(__name__)
@@ -18,11 +18,21 @@ async def root() -> dict[str, str]:
async def readiness(request: Request) -> dict[str, str]:
try:
async with acquire_connection(request.app.state.db_pool) as conn:
- await conn.fetchval("SELECT 1")
- return {"status": "ready"}
+ missing = await missing_table_privileges(conn)
except Exception:
logger.exception("Readiness check failed: database connection error")
raise HTTPException(status_code=503, detail="Database not ready") from None
+ if missing:
+ # Runs on every probe: a revoked grant unreadies serving pods too,
+ # deliberately, since every declared table is on the auth path. The
+ # body matches the connection-failure branch (the probe may be
+ # public); this log line carries the table names.
+ logger.error(
+ "Readiness check failed: role lacks SELECT on %s; grants are the users.tf allowlist in posthog-cloud-infra",
+ ", ".join(missing),
+ )
+ raise HTTPException(status_code=503, detail="Database not ready")
+ return {"status": "ready"}
@health_router.get("/_liveness")
diff --git a/services/llm-gateway/src/llm_gateway/db/postgres.py b/services/llm-gateway/src/llm_gateway/db/postgres.py
index 246865518f0b..7695ae13c3f0 100644
--- a/services/llm-gateway/src/llm_gateway/db/postgres.py
+++ b/services/llm-gateway/src/llm_gateway/db/postgres.py
@@ -4,10 +4,25 @@ from contextlib import asynccontextmanager
import asyncpg
+from llm_gateway.db.required_tables import REQUIRED_TABLES
from llm_gateway.metrics.prometheus import DB_POOL_EXHAUSTED
POOL_ACQUIRE_TIMEOUT = 5.0
+# An absent relation is excluded (to_regclass NULL, COALESCE TRUE): schema
+# absence is a different failure than a revoked grant.
+MISSING_PRIVILEGES_QUERY = """
+ SELECT t.table_name
+ FROM unnest($1::text[]) AS t(table_name)
+ WHERE NOT COALESCE(has_table_privilege(current_user, to_regclass(t.table_name), 'SELECT'), TRUE)
+"""
+
+
+async def missing_table_privileges(conn: asyncpg.Connection) -> list[str]:
+ """Return the REQUIRED_TABLES the connected role cannot SELECT from."""
+ rows = await conn.fetch(MISSING_PRIVILEGES_QUERY, sorted(REQUIRED_TABLES))
+ return [row["table_name"] for row in rows]
+
async def init_db_pool(database_url: str, min_size: int = 2, max_size: int = 10) -> asyncpg.Pool:
return await asyncpg.create_pool(
diff --git a/services/llm-gateway/tests/conftest.py b/services/llm-gateway/tests/conftest.py
index 332e566caa7a..6bc24d12f3e2 100644
--- a/services/llm-gateway/tests/conftest.py
+++ b/services/llm-gateway/tests/conftest.py
@@ -78,6 +78,7 @@ def mock_db_pool() -> MagicMock:
conn = AsyncMock()
conn.fetchrow = AsyncMock(return_value=None)
conn.fetchval = AsyncMock(return_value=1)
+ conn.fetch = AsyncMock(return_value=[])
pool.acquire = AsyncMock(return_value=conn)
pool.release = AsyncMock()
return pool
diff --git a/services/llm-gateway/tests/test_health.py b/services/llm-gateway/tests/test_health.py
index f5887340a515..ba522e131c77 100644
--- a/services/llm-gateway/tests/test_health.py
+++ b/services/llm-gateway/tests/test_health.py
@@ -3,6 +3,7 @@ from unittest.mock import AsyncMock, MagicMock
import pytest
from fastapi.testclient import TestClient
+from llm_gateway.db.required_tables import REQUIRED_TABLES
from llm_gateway.main import create_app
@@ -22,6 +23,14 @@ class TestHealthEndpoints:
app.state.db_pool = pool
return TestClient(app)
+ @pytest.fixture
+ def client_with_missing_privileges(self, mock_db_pool: MagicMock) -> TestClient:
+ app = create_app()
+ conn = mock_db_pool.acquire.return_value
+ conn.fetch = AsyncMock(return_value=[{"table_name": "posthog_team"}, {"table_name": "ee_role"}])
+ app.state.db_pool = mock_db_pool
+ return TestClient(app)
+
@pytest.mark.parametrize(
"endpoint,expected_status,expected_body",
[
@@ -46,6 +55,25 @@ class TestHealthEndpoints:
assert response.status_code == 503
assert response.json()["detail"] == "Database not ready"
+ def test_readiness_fails_when_privileges_missing(
+ self, client_with_missing_privileges: TestClient, caplog: pytest.LogCaptureFixture
+ ) -> None:
+ response = client_with_missing_privileges.get("/_readiness")
+ assert response.status_code == 503
+ # Same body as the connection-failure branch, deliberately.
+ assert response.json()["detail"] == "Database not ready"
+ assert "posthog_team, ee_role" in caplog.text
+ assert "posthog-cloud-infra" in caplog.text
+
+ def test_readiness_checks_every_required_table(
+ self, client_with_healthy_db: TestClient, mock_db_pool: MagicMock
+ ) -> None:
+ client_with_healthy_db.get("/_readiness")
+ conn = mock_db_pool.acquire.return_value
+ conn.fetch.assert_awaited_once()
+ checked_tables = conn.fetch.await_args.args[1]
+ assert checked_tables == sorted(REQUIRED_TABLES)
+
def test_liveness_succeeds_when_db_unavailable(self, client_with_unhealthy_db: TestClient) -> None:
response = client_with_unhealthy_db.get("/_liveness")
assert response.status_code == 200