: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(data-warehouse): guard presentation layer against per-source branches (#71543)
Tom Owers3cdad51c80b7
diff --git a/.agents/skills/implementing-warehouse-sources/SKILL.md b/.agents/skills/implementing-warehouse-sources/SKILL.mdindex 83491362a7ed..1826108ad3a8 100644--- a/.agents/skills/implementing-warehouse-sources/SKILL.md+++ b/.agents/skills/implementing-warehouse-sources/SKILL.md@@ -106,6 +106,21 @@ For API-backed sources, use this split:This keeps endpoint behavior declarative and easy to extend.+### Source behaviour goes in the source, never in the API layer++The `data_warehouse` presentation layer (`products/data_warehouse/backend/presentation/views/external_data_source.py`, `external_data_schema.py`) must stay source-agnostic.+Do **not** add `if source_type == ExternalDataSourceType.X` / `source.is_direct_<engine>` branches there — a CI guard (`.github/scripts/check-dwh-source-agnostic.py`) blocks new ones.++When a source needs behaviour the API must invoke, expose it on the source instead:++- **A boolean/value the API reads** → add a flag on `_BaseSource` with a safe default (like `supports_column_selection`, `connection_host_fields`, `has_managed_hogql_schema`), and let the API branch on the flag.+- **Methods only some sources have** (CDC, xmin, webhooks, custom manifests) → a capability mixin the source opts into; the API dispatches with `isinstance(source, <Capability>)`.+- **Direct-query engine behaviour** (how a SQL engine resolves a table location, builds its `DataWarehouseTable`, maps columns) is keyed on the engine, not the source type — dispatch on `source.direct_engine` through the engine adapter/registry (`posthog/hogql/direct_sql/` for query concerns, the `data_warehouse` engine registry for materialization), never `source_type`.++Keep source-domain semantics (how to talk to the engine, how it names things, whether filters push down) on the source; the warehouse-domain work it drives (`DataWarehouseTable` rows, managed viewsets, hog functions) stays in `data_warehouse`, keyed off what the source or adapter returns.+Source capabilities never import `data_warehouse` types.+See `products/data_warehouse/backend/presentation/README.md`.+For REST sources that mix top-level and fan-out endpoints, keep endpoint metadata in `settings.py` and route in `{source}.py` with this priority:1. endpoint-specific custom iterators (only when required),diff --git a/.depot/workflows/ci-backend.yml b/.depot/workflows/ci-backend.ymlindex 113f5d2b2ff5..1c74602f0b27 100644--- a/.depot/workflows/ci-backend.yml+++ b/.depot/workflows/ci-backend.yml@@ -917,6 +917,8 @@ jobs:run: python .github/scripts/check-version-specifiers.py- name: Check IDOR model coveragerun: python .github/scripts/check-idor-model-coverage.py+ - name: Check DWH presentation layer stays source-agnostic+ run: python .github/scripts/check-dwh-source-agnostic.py- name: Check operator parityrun: python .github/scripts/check-operator-parity.py- name: Check module boundaries (tach)diff --git a/.github/scripts/check-dwh-source-agnostic.py b/.github/scripts/check-dwh-source-agnostic.pynew file mode 100644index 000000000000..29cf0583f9c0--- /dev/null+++ b/.github/scripts/check-dwh-source-agnostic.py@@ -0,0 +1,169 @@+#!/usr/bin/env python3+# ruff: noqa: T201 allow print statements+"""+CI guard: the data-warehouse API/presentation layer must stay source-agnostic.++Per-source behaviour (``if source_type == ExternalDataSourceType.POSTGRES``,+``source.is_direct_snowflake``, …) keeps getting bolted onto the DWH views. Every+such branch splits "how source X behaves" between the source class and the API+layer, and grows the views without bound. The API should ask *what a source+supports* and delegate the *how*, never naming a concrete source type. Depending+on the concern that means a capability flag / mixin on the source+(``products/warehouse_sources/.../sources/common``) or an engine-keyed adapter+dispatched on ``source.direct_engine`` for direct-query behaviour. See+``products/data_warehouse/backend/presentation/README.md``.++This is a shrink-only baseline (the same shape as the IDOR fail-closed guard):++- Each forbidden reference is counted per ``(file, token)``.+- A NEW ``(file, token)`` key, or a HIGHER count for an existing one, fails CI —+ that's a new per-source branch.+- A LOWER count (a family migrated to a capability) is reported as an+ opportunity to shrink the baseline; regenerate to bank the win.++The baseline is the mechanical output of ``--regenerate-baseline`` — do not hand+edit it, or it degrades into a curated allowlist.++Usage:+ python check-dwh-source-agnostic.py+ python check-dwh-source-agnostic.py --regenerate-baseline++Exit codes:+ 0 - No new per-source branches (may pass with shrink warnings)+ 1 - New per-source branch(es) added to the presentation layer+"""++import re+import sys+import argparse+from pathlib import Path++REPO_ROOT = Path(__file__).resolve().parent.parent.parent+SCAN_ROOT = REPO_ROOT / "products/data_warehouse/backend/presentation"+BASELINE_FILE = SCAN_ROOT / "source_agnostic_baseline.txt"++# Structural signals that the API layer is naming a concrete source type. Kept+# deliberately narrow (enum member refs + the model's `is_direct_*` engine+# properties) — the two patterns the branches always take. Bare imports+# (`from ... import ExternalDataSourceType`) don't match: they carry no `.MEMBER`.+FORBIDDEN_PATTERNS = [+ re.compile(r"\bExternalDataSourceType\.[A-Z][A-Z0-9_]*\b"),+ re.compile(r"\bSourceType\.[A-Z][A-Z0-9_]*\b"),+ re.compile(r"\bis_direct_(?:postgres|mysql|snowflake|redshift)\b"),+]++BASELINE_HEADER = (+ "# Per-source branches still living in the DWH presentation layer.\n"+ "#\n"+ "# DO NOT EDIT BY HAND. This file is the mechanical output of\n"+ "# `--regenerate-baseline`. Hand-adding entries turns it back into a curated\n"+ "# allowlist and defeats the shrink-only guarantee.\n"+ "#\n"+ "# Auto-generated by .github/scripts/check-dwh-source-agnostic.py\n"+ "# Regenerate: python .github/scripts/check-dwh-source-agnostic.py --regenerate-baseline\n"+ "#\n"+ "# Each line is `<count>\\t<token>\\t<relpath>`. Migrate a family to a capability\n"+ "# mixin (see .../sources/common/capabilities.py), then regenerate to shrink.\n"+)+++def scan_current() -> dict[tuple[str, str], int]:+ """Count forbidden per-source references, keyed on (relpath, matched token)."""+ counts: dict[tuple[str, str], int] = {}+ for path in sorted(SCAN_ROOT.rglob("*.py")):+ if path.name.startswith("test_") or "/tests/" in path.as_posix():+ continue+ relpath = path.relative_to(REPO_ROOT).as_posix()+ text = path.read_text()+ for pattern in FORBIDDEN_PATTERNS:+ for match in pattern.finditer(text):+ key = (relpath, match.group(0))+ counts[key] = counts.get(key, 0) + 1+ return counts+++def read_baseline() -> dict[tuple[str, str], int]:+ if not BASELINE_FILE.exists():+ return {}+ baseline: dict[tuple[str, str], int] = {}+ for line in BASELINE_FILE.read_text().splitlines():+ line = line.strip()+ if not line or line.startswith("#"):+ continue+ count_str, token, relpath = line.split("\t")+ baseline[(relpath, token)] = int(count_str)+ return baseline+++def write_baseline(counts: dict[tuple[str, str], int]) -> None:+ lines = sorted(f"{count}\t{token}\t{relpath}" for (relpath, token), count in counts.items())+ body = "\n".join(lines) + ("\n" if lines else "")+ BASELINE_FILE.write_text(BASELINE_HEADER + body)+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument(+ "--regenerate-baseline",+ action="store_true",+ help="Rewrite the baseline from the current presentation-layer state.",+ )+ args = parser.parse_args()++ current = scan_current()++ print("=" * 60)+ print("DWH source-agnostic presentation-layer guard")+ print("=" * 60)++ if args.regenerate_baseline:+ write_baseline(current)+ total = sum(current.values())+ print(f"\n Regenerated {BASELINE_FILE.relative_to(REPO_ROOT)}")+ print(f" {total} per-source reference(s) across {len(current)} (file, token) pair(s).")+ return 0++ baseline = read_baseline()++ new_branches: list[tuple[str, str, int, int]] = [] # relpath, token, baseline_count, current_count+ for key, count in sorted(current.items()):+ base = baseline.get(key, 0)+ if count > base:+ new_branches.append((key[0], key[1], base, count))++ shrunk: list[tuple[str, str, int, int]] = []+ for key, base in sorted(baseline.items()):+ count = current.get(key, 0)+ if count < base:+ shrunk.append((key[0], key[1], base, count))++ print(f"\n Baseline: {sum(baseline.values())} references")+ print(f" Current: {sum(current.values())} references")++ if new_branches:+ joined = ", ".join(f"{token} in {relpath}" for relpath, token, _, _ in new_branches)+ print(f"::error::New per-source branch(es) in the DWH presentation layer: {joined}")+ print(f"\n ❌ ERROR: {len(new_branches)} new per-source reference(s):")+ for relpath, token, base, count in new_branches:+ print(f" - {token} ({base} → {count}) in {relpath}")+ print("\n The API/presentation layer must not name a concrete source type.")+ print(" Expose the behaviour on the source (a _BaseSource capability flag or a")+ print(" capability mixin) or, for direct-query engine behaviour, an engine-keyed")+ print(" adapter dispatched on source.direct_engine — never a source-type branch.")+ print(" See products/data_warehouse/backend/presentation/README.md.")+ return 1++ if shrunk:+ print(f"\n ✅ {len(shrunk)} reference(s) migrated since baseline (regenerate to shrink):")+ for relpath, token, base, count in shrunk:+ print(f" - {token} ({base} → {count}) in {relpath}")+ print("\n Run: python .github/scripts/check-dwh-source-agnostic.py --regenerate-baseline")+ print("\n⚠️ PASSED with shrink opportunities.")+ return 0++ print("\n✅ No new per-source branches. Baseline matches.")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/.github/workflows/ci-backend.yml b/.github/workflows/ci-backend.ymlindex 0577e975a505..5b31cf21c0e9 100644--- a/.github/workflows/ci-backend.yml+++ b/.github/workflows/ci-backend.yml@@ -1083,6 +1083,9 @@ jobs:- name: Check IDOR model coveragerun: python .github/scripts/check-idor-model-coverage.py+ - name: Check DWH presentation layer stays source-agnostic+ run: python .github/scripts/check-dwh-source-agnostic.py+- name: Check operator parityrun: python .github/scripts/check-operator-parity.pydiff --git a/products/data_warehouse/backend/presentation/README.md b/products/data_warehouse/backend/presentation/README.mdnew file mode 100644index 000000000000..695ffbd85a81--- /dev/null+++ b/products/data_warehouse/backend/presentation/README.md@@ -0,0 +1,57 @@+# Data warehouse presentation layer++## The presentation layer stays source-agnostic++The source/schema views here (`views/external_data_source.py`, `views/external_data_schema.py`)+must not branch on a concrete source type. No:++```python+if source_type == ExternalDataSourceType.POSTGRES: ...+elif source.is_direct_snowflake: ...+```++Every such branch splits "how source X behaves" between the source class and the API+layer, and grows the views without bound as new sources land. The API asks _what a+source supports_ and delegates the _how_.++### Where the behaviour goes++Pick the mechanism by the kind of concern:++1. **Source-domain behaviour** (how to talk to the upstream system, whether it supports a+ feature) → the source class under+ `products/warehouse_sources/backend/temporal/data_imports/sources`:+ - **A boolean/value the API reads** → a flag on `_BaseSource` with a safe default+ (like `supports_column_selection`, `connection_host_fields`, `has_managed_hogql_schema`).+ Branch on the flag.+ - **Methods only some sources have** (CDC, xmin, webhooks, custom manifests) → a capability+ mixin the source opts into; the API dispatches with `isinstance(source, <Capability>)`.++2. **Direct-query engine behaviour** (how a SQL engine resolves a table location, builds and+ reprojects its `DataWarehouseTable`, maps columns) → an **engine-keyed adapter**, dispatched+ on `source.direct_engine` (via `DIRECT_ENGINE_BY_SOURCE_TYPE` / `is_direct_capable`), never on+ `source_type`. The engine, not the source type, is the axis of variation, and the same engine+ can back more than one source. Query-side engine behaviour already lives in the+ `posthog/hogql/direct_sql/` adapter registry; the warehouse-side materialization+ (`get_*_source_location`, `upsert_direct_*_table`, `reproject_direct_*_table`,+ `*_columns_to_dwh_columns`) belongs behind the matching `data_warehouse` engine registry.++Whatever the mechanism, source-domain semantics live on the source and warehouse-domain work+(`DataWarehouseTable` rows, managed viewsets, hog functions) stays here, keyed off what the+source / adapter returns. Source capabilities never import `data_warehouse` types.++### Enforcement++`.github/scripts/check-dwh-source-agnostic.py` is a shrink-only CI guard (run in+`ci-backend.yml`). It counts every `ExternalDataSourceType.<NAME>` / `SourceType.<NAME>` /+`is_direct_<engine>` reference in this directory against a baseline+(`source_agnostic_baseline.txt`). A new reference fails CI; migrating a family lets you shrink+the baseline:++```bash+python .github/scripts/check-dwh-source-agnostic.py --regenerate-baseline+```++The baseline only shrinks. When it hits zero, delete the guard.++See `implementing-warehouse-sources` for how to add behaviour to a source.diff --git a/products/data_warehouse/backend/presentation/source_agnostic_baseline.txt b/products/data_warehouse/backend/presentation/source_agnostic_baseline.txtnew file mode 100644index 000000000000..4897b2ec6e17--- /dev/null+++ b/products/data_warehouse/backend/presentation/source_agnostic_baseline.txt@@ -0,0 +1,25 @@+# Per-source branches still living in the DWH presentation layer.+#+# DO NOT EDIT BY HAND. This file is the mechanical output of+# `--regenerate-baseline`. Hand-adding entries turns it back into a curated+# allowlist and defeats the shrink-only guarantee.+#+# Auto-generated by .github/scripts/check-dwh-source-agnostic.py+# Regenerate: python .github/scripts/check-dwh-source-agnostic.py --regenerate-baseline+#+# Each line is `<count>\t<token>\t<relpath>`. Migrate a family to a capability+# mixin (see .../sources/common/capabilities.py), then regenerate to shrink.+1 is_direct_postgres products/data_warehouse/backend/presentation/views/external_data_source.py+2 ExternalDataSourceType.MYSQL products/data_warehouse/backend/presentation/views/external_data_source.py+2 ExternalDataSourceType.POSTGRES products/data_warehouse/backend/presentation/views/external_data_schema.py+3 ExternalDataSourceType.REDSHIFT products/data_warehouse/backend/presentation/views/external_data_source.py+3 ExternalDataSourceType.SNOWFLAKE products/data_warehouse/backend/presentation/views/external_data_source.py+3 is_direct_mysql products/data_warehouse/backend/presentation/views/external_data_source.py+3 is_direct_postgres products/data_warehouse/backend/presentation/views/external_data_schema.py+3 is_direct_redshift products/data_warehouse/backend/presentation/views/external_data_schema.py+3 is_direct_redshift products/data_warehouse/backend/presentation/views/external_data_source.py+3 is_direct_snowflake products/data_warehouse/backend/presentation/views/external_data_schema.py+3 is_direct_snowflake products/data_warehouse/backend/presentation/views/external_data_source.py+4 ExternalDataSourceType.GITHUB products/data_warehouse/backend/presentation/views/external_data_source.py+6 ExternalDataSourceType.CUSTOM products/data_warehouse/backend/presentation/views/external_data_source.py+6 ExternalDataSourceType.POSTGRES products/data_warehouse/backend/presentation/views/external_data_source.py