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.

chore(ci): run only affected dagster tests on PRs (#85566)

Paul D'Ambra1390120f0684
diff --git a/.github/workflows/ci-dagster.yml b/.github/workflows/ci-dagster.yml
index 85c2aa4484f6..37ce25231e9b 100644
--- a/.github/workflows/ci-dagster.yml
+++ b/.github/workflows/ci-dagster.yml
@@ -177,6 +177,10 @@ jobs:
- 'products/web_analytics/backend/**/*.py'
# Make sure we run if someone is explicitly change the workflow
- .github/workflows/ci-dagster.yml
+ # The test selector guards itself: selector changes run the
+ # suite (full mode), which executes its unit tests first
+ - tools/dagster_test_selection.py
+ - tools/test_dagster_test_selection.py
- .github/clickhouse-versions.json
# Composite action used to install sqlx-cli
- '.github/actions/setup-sqlx-cli/**'
@@ -213,6 +217,8 @@ jobs:
- 'posthog/dags/**'
- 'products/*/dags/**'
- .github/workflows/ci-dagster.yml
+ - tools/dagster_test_selection.py
+ - tools/test_dagster_test_selection.py
- name: Read ClickHouse versions from JSON
id: read-versions
@@ -307,18 +313,110 @@ jobs:
echo "migrations_key=posthog-schema-mig-${SCHEMA_CACHE_EPOCH}-${MIG_HASH}" >> $GITHUB_OUTPUT
fi
+ # Narrow ordinary PR runs to the dag tests the diff can affect (snob import
+ # graph with whole-tree fallbacks for conftest/non-Python changes). The
+ # merge-queue run keeps the broad filter and the full suite, so the merge
+ # gate is unchanged and a selection miss surfaces there. Fail-open: if this
+ # job fails or is skipped its outputs stay empty and the dagster job falls
+ # back to the full matrix. The run-ci-dagster label forces the full suite.
+ select-tests:
+ name: Select dagster tests
+ needs: [changes]
+ if: >-
+ github.event_name == 'pull_request'
+ && needs.changes.outputs.merge_queue != 'true'
+ && needs.changes.outputs.dagster_direct == 'true'
+ && !contains(github.event.pull_request.labels.*.name, 'run-ci-dagster')
+ runs-on: ubuntu-latest
+ timeout-minutes: 10
+ outputs:
+ mode: ${{ steps.classify.outputs.mode }}
+ test_paths: ${{ steps.classify.outputs.test_paths }}
+ matrix_include: ${{ steps.classify.outputs.matrix_include }}
+ steps:
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+ with:
+ fetch-depth: 1000
+ filter: blob:none
+
+ - name: Install uv
+ uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0
+ with:
+ version: '0.11.28'
+
+ # A broken selector must degrade to the full suite, never to a
+ # silently wrong subset — prove it healthy before trusting it.
+ - name: Guard the selector with its unit tests
+ id: selftest
+ continue-on-error: true
+ run: python3 tools/test_dagster_test_selection.py
+
+ - name: Run selector
+ id: select
+ continue-on-error: true
+ if: steps.selftest.outcome == 'success'
+ env:
+ BASE_REF: ${{ github.event.pull_request.base.ref }}
+ run: |
+ set -euo pipefail
+ git fetch --no-tags --depth=1000 --filter=blob:none origin "$BASE_REF:refs/remotes/origin/$BASE_REF"
+ uv run tools/dagster_test_selection.py --base-ref "origin/$BASE_REF" > /tmp/dagster-selection.json
+
+ - name: Classify selection
+ id: classify
+ env:
+ OLDEST_SUPPORTED: ${{ needs.changes.outputs.oldest_supported }}
+ SELECT_OUTCOME: ${{ steps.select.outcome }}
+ run: |
+ set -euo pipefail
+ if [[ "$SELECT_OUTCOME" != "success" ]] || [[ ! -s /tmp/dagster-selection.json ]]; then
+ echo "::warning::dagster test selector unavailable; running the full suite"
+ exit 0
+ fi
+ mode=$(jq -r '.mode' /tmp/dagster-selection.json)
+ echo "mode=$mode" >> "$GITHUB_OUTPUT"
+ {
+ echo "## Dagster test selection"
+ echo
+ echo "Mode: \`$mode\` — $(jq -r '.count' /tmp/dagster-selection.json) test files, $(jq -r '.selected_seconds' /tmp/dagster-selection.json)s of $(jq -r '.suite_seconds' /tmp/dagster-selection.json)s suite time"
+ jq -r '.reasons[]? | "- " + .' /tmp/dagster-selection.json
+ jq -r '.tests[]? | "- `" + . + "`"' /tmp/dagster-selection.json
+ } >> "$GITHUB_STEP_SUMMARY"
+ if [[ "$mode" != "selected" ]]; then
+ exit 0
+ fi
+ echo "test_paths=$(jq -r '.tests | join(" ")' /tmp/dagster-selection.json)" >> "$GITHUB_OUTPUT"
+ shards=$(jq -r '.shards' /tmp/dagster-selection.json)
+ image=$(echo "$OLDEST_SUPPORTED" | jq -r '.[0]')
+ # Same shape as the changes job's build-matrix step, with the
+ # shard count sized to the selection instead of fixed at 3.
+ include=$(jq -cn --arg image "$image" --argjson shards "$shards" '
+ [range(1; $shards + 1) | {
+ "clickhouse-server-image": $image,
+ concurrency: $shards,
+ group: .
+ }]
+ ')
+ echo "matrix_include=$include" >> "$GITHUB_OUTPUT"
+
dagster:
name: Dagster tests (${{ matrix.group }}/${{ matrix.concurrency }})
- needs: [changes]
+ needs: [changes, select-tests]
timeout-minutes: 40
strategy:
fail-fast: false
matrix:
- include: ${{ fromJson(needs.changes.outputs.matrix_include || '[]') }}
+ include: ${{ fromJson(needs.select-tests.outputs.matrix_include || needs.changes.outputs.matrix_include || '[]') }}
+ # !cancelled() lets this run when select-tests is skipped (master,
+ # merge queue) or failed (fall back to the full matrix); mode 'none'
+ # means the diff cannot affect any dagster test, so nothing runs and
+ # the merge-queue full suite remains the gate.
if: >-
- needs.changes.outputs.dagster_direct == 'true'
- || (needs.changes.outputs.merge_queue == 'true'
- && needs.changes.outputs.dagster == 'true')
+ ${{ !cancelled()
+ && needs.select-tests.outputs.mode != 'none'
+ && (needs.changes.outputs.dagster_direct == 'true'
+ || (needs.changes.outputs.merge_queue == 'true'
+ && needs.changes.outputs.dagster == 'true')) }}
runs-on: depot-ubuntu-24.04
env:
DOCKERHUB_USERNAME: ${{ vars.DOCKERHUB_USER }}
@@ -503,6 +601,8 @@ jobs:
posthog-test-durations-
- name: Run Dagster tests
+ env:
+ TEST_PATHS: ${{ needs.select-tests.outputs.test_paths }}
run: |
# Pick the split algorithm and granularity at runtime: optimal_chunks +
# file granularity only when the installed pytest-split offers them, else
@@ -515,7 +615,15 @@ jobs:
SPLITTING_ALGORITHM=optimal_chunks
SPLIT_GRANULARITY=(--split-granularity=file)
fi
- pytest posthog/dags products/**/dags \
+ # Selected mode: run only the test files chosen by the dagster
+ # selector. products/*/dags expands identically to the old
+ # products/**/dags (bash globs without globstar).
+ if [ -n "${TEST_PATHS:-}" ]; then
+ read -r -a TEST_TARGETS <<< "$TEST_PATHS"
+ else
+ TEST_TARGETS=(posthog/dags products/*/dags)
+ fi
+ pytest "${TEST_TARGETS[@]}" \
--reuse-db \
--splits ${{ matrix.concurrency }} --group ${{ matrix.group }} \
--durations=100 --durations-min=1.0 --store-durations \
diff --git a/tools/dagster_test_selection.py b/tools/dagster_test_selection.py
new file mode 100644
index 000000000000..71b09cc71e1b
--- /dev/null
+++ b/tools/dagster_test_selection.py
@@ -0,0 +1,392 @@
+#!/usr/bin/env -S uv run --script
+# /// script
+# requires-python = ">=3.12"
+# dependencies = [
+# "pytest-snob>=0.1.14",
+# ]
+# ///
+"""Select the dagster tests a diff can affect.
+
+Dagster tests reach code exclusively through imports (no URL routing, signals,
+or middleware indirection), so the snob import graph is a sound selector here,
+unlike for the Django suite. One conservative fallback covers everything the
+graph cannot see: when a changed file in a dags tree is a conftest, is not a
+Python file, or maps to no test via imports (deleted files, fixture-only
+modules), every test in that dags tree is selected.
+
+Modes:
+- "full": run the whole suite (infrastructure changed, too many files, or the
+ selection covers most of the suite anyway).
+- "selected": run only the listed test files, across the suggested shard count.
+- "none": no dagster test can be affected; skip the suite. The merge-queue run
+ always executes the full suite, so a miss here is caught before merge.
+
+Outputs JSON to stdout. Exit code is 0 even for full mode; the caller treats a
+non-zero exit or empty output as full mode (fail-open to today's behavior).
+"""
+
+from __future__ import annotations
+
+import os
+import re
+import ast
+import sys
+import json
+import math
+import argparse
+import subprocess
+from dataclasses import asdict, dataclass, field
+from pathlib import Path, PurePosixPath
+
+REPO_ROOT = Path(__file__).parent.parent.resolve()
+DURATIONS_PATH = REPO_ROOT / ".test_durations"
+
+# Mirrors the pytest invocation in ci-dagster.yml: posthog/dags products/*/dags.
+DAGS_TREE_GLOBS = ("posthog/dags", "products/*/dags")
+DAGS_TREE_PATTERN = re.compile(r"^(posthog/dags|products/[^/]+/dags)/")
+
+# Changes to these force a full run: they alter how every dagster test executes
+# (config, dependencies, the CI environment, or this selector itself).
+FULL_RUN_PATTERNS = (
+ ".github/workflows/ci-dagster.yml",
+ ".github/clickhouse-versions.json",
+ ".github/actions/setup-sqlx-cli/",
+ "tools/dagster_test_selection.py",
+ "tools/test_dagster_test_selection.py",
+ "tools/hogli/",
+ "tools/hogli-commands/hogli_commands/db_schema.py",
+ "tools/hogli-commands/hogli_commands/prechecks.py",
+ "tools/hogli-commands/hogli_commands/telemetry_props.py",
+ "tools/hogli-commands/hogli_commands/hint_hook.py",
+ "tools/hogli-commands/hogli_commands/hints.py",
+ "docker-compose",
+ "docker/postgres-init-scripts/",
+ "rust/persons_migrations/",
+ "bin/wait-for-docker",
+ "bin/ci-wait-for-docker",
+ "hogli.yaml",
+ "manage.py",
+ "pytest.ini",
+ "pyproject.toml",
+ "uv.lock",
+ "posthog/conftest.py",
+ "posthog/test/",
+)
+ROOT_CONFTEST = "conftest.py"
+
+MAX_CHANGED_FILES = 50
+
+# Matches the ~15 min per shard target in ci-dagster.yml's build-matrix step.
+TARGET_SECONDS_PER_SHARD = 900
+MAX_SHARDS = 3
+
+# Above this share of the suite's duration, a narrowed run saves nothing over
+# the full run and only adds selection risk.
+FULL_RUN_DURATION_FRACTION = 0.8
+
+
+@dataclass(frozen=True)
+class Selection:
+ mode: str
+ tests: list[str] = field(default_factory=list)
+ shards: int = 0
+ reasons: list[str] = field(default_factory=list)
+ fallback_trees: list[str] = field(default_factory=list)
+ changed_file_count: int = 0
+ selected_seconds: int = 0
+ suite_seconds: int = 0
+
+ @property
+ def count(self) -> int:
+ return len(self.tests)
+
+
+def dags_trees() -> list[str]:
+ trees: list[str] = []
+ for pattern in DAGS_TREE_GLOBS:
+ if "*" in pattern:
+ trees.extend(sorted(str(p.relative_to(REPO_ROOT)) for p in REPO_ROOT.glob(pattern) if p.is_dir()))
+ elif (REPO_ROOT / pattern).is_dir():
+ trees.append(pattern)
+ return trees
+
+
+def _is_test_file(path: str) -> bool:
+ return path.endswith(".py") and PurePosixPath(path).name.startswith("test_")
+
+
+def test_universe(trees: list[str]) -> set[str]:
+ universe: set[str] = set()
+ for tree in trees:
+ for path in (REPO_ROOT / tree).rglob("test_*.py"):
+ universe.add(str(path.relative_to(REPO_ROOT)))
+ return universe
+
+
+def tree_of(path: str) -> str | None:
+ """The dags tree a path belongs to, by shape — not by directory existence,
+ so files of a deleted tree still classify as dag changes."""
+ match = DAGS_TREE_PATTERN.match(path)
+ return match.group(1) if match else None
+
+
+def changed_files_from_git(base_ref: str) -> list[str]:
+ # --no-renames splits a rename into a delete + an add, so the removed path
+ # stays visible. The tree-fallback and removed-tree guards key on it; with
+ # rename detection on, git reports only the destination and both are bypassed.
+ result = subprocess.run(
+ ["git", "diff", "--no-renames", "--name-only", f"{base_ref}...HEAD"],
+ cwd=REPO_ROOT,
+ capture_output=True,
+ text=True,
+ check=True,
+ )
+ return [line for line in result.stdout.splitlines() if line.strip()]
+
+
+def normalize_repo_path(path: str) -> str:
+ path_obj = Path(path)
+ if path_obj.is_absolute():
+ try:
+ return str(path_obj.resolve().relative_to(REPO_ROOT.resolve()))
+ except ValueError:
+ return path
+ return str(PurePosixPath(path))
+
+
+def _module_name(path: str) -> str:
+ return path.removesuffix(".py").replace("/", ".")
+
+
+def _imported_modules(path: Path) -> set[str]:
+ try:
+ tree = ast.parse(path.read_text())
+ except (OSError, SyntaxError, UnicodeDecodeError):
+ return set()
+ modules: set[str] = set()
+ for node in ast.walk(tree):
+ if isinstance(node, ast.Import):
+ modules.update(alias.name for alias in node.names)
+ elif isinstance(node, ast.ImportFrom) and node.module:
+ modules.add(node.module)
+ modules.update(f"{node.module}.{alias.name}" for alias in node.names if alias.name != "*")
+ return modules
+
+
+def conftest_dependent_trees(changed_py_files: list[str], trees: list[str]) -> set[str]:
+ """Trees whose conftest imports one of the changed modules. Fixtures flow
+ through conftests without appearing in any test file's import graph, so
+ snob cannot see this reach — e.g. a product conftest importing shared
+ fixtures from posthog/dags/tests."""
+ changed_modules = {_module_name(path) for path in changed_py_files}
+ if not changed_modules:
+ return set()
+ dependent: set[str] = set()
+ for tree in trees:
+ for conftest in (REPO_ROOT / tree).rglob("conftest.py"):
+ imports = _imported_modules(conftest)
+ if imports & changed_modules or any(
+ imported.startswith(module + ".") for imported in imports for module in changed_modules
+ ):
+ dependent.add(tree)
+ break
+ return dependent
+
+
+_DYNAMIC_IMPORT_PATTERN = re.compile(r"importlib|__import__")
+
+
+def dynamic_import_tests(changed_trees: set[str], universe: set[str]) -> set[str]:
+ """Test files that load modules dynamically (importlib) see changes the
+ static import graph cannot attribute to them, so they run whenever any
+ Python file in their tree changes."""
+ selected: set[str] = set()
+ for test in universe:
+ if tree_of(test) not in changed_trees:
+ continue
+ try:
+ if _DYNAMIC_IMPORT_PATTERN.search((REPO_ROOT / test).read_text()):
+ selected.add(test)
+ except OSError:
+ continue
+ return selected
+
+
+def snob_tests(changed_py_files: list[str]) -> set[str]:
+ if not changed_py_files:
+ return set()
+ import snob_lib # noqa: PLC0415 — resolved by this script's PEP 723 deps, absent in stdlib-only test runs
+
+ return {normalize_repo_path(str(test)) for test in snob_lib.get_tests(changed_py_files)}
+
+
+def load_durations() -> dict[str, float]:
+ if not DURATIONS_PATH.exists():
+ return {}
+ try:
+ raw = json.loads(DURATIONS_PATH.read_text())
+ except (json.JSONDecodeError, OSError):
+ return {}
+ return {str(key): float(value) for key, value in raw.items()}
+
+
+def estimate_seconds(test_files: set[str], durations: dict[str, float]) -> float:
+ total = 0.0
+ for test_id, duration in durations.items():
+ if test_id.split("::", 1)[0] in test_files:
+ total += duration
+ return total
+
+
+def removed_tree_reasons(changed_files: list[str], trees: list[str]) -> list[str]:
+ """A deleted dags tree leaves no modules for snob to resolve reverse
+ dependencies against, so cross-tree import breakage is invisible to
+ selection — only a full run can catch it before the merge queue."""
+ removed = {tree_of(path) for path in changed_files} - {None} - set(trees)
+ return sorted(f"dags tree {tree} no longer exists; forcing a full run" for tree in removed)
+
+
+def full_run_reasons(changed_files: list[str]) -> list[str]:
+ reasons = [
+ f"{path} matches full-run pattern {pattern}"
+ for path in changed_files
+ for pattern in FULL_RUN_PATTERNS
+ if pattern in path
+ ]
+ reasons.extend(f"{path} is the root conftest" for path in changed_files if path == ROOT_CONFTEST)
+ if len(changed_files) > MAX_CHANGED_FILES:
+ reasons.append(f"too many changed files ({len(changed_files)} > {MAX_CHANGED_FILES})")
+ return sorted(reasons)
+
+
+@dataclass(frozen=True)
+class SelectedTests:
+ tests: set[str]
+ fallback_trees: set[str]
+
+
+def select_tests(
+ changed_files: list[str],
+ trees: list[str],
+ universe: set[str],
+ snob_fn=snob_tests,
+) -> SelectedTests:
+ selected: set[str] = set()
+ fallback_trees: set[str] = set()
+ outside_py: list[str] = []
+ in_tree_py: list[str] = []
+ changed_trees: set[str] = set()
+
+ for path in changed_files:
+ tree = tree_of(path)
+ if tree is None:
+ if path.endswith(".py"):
+ outside_py.append(path)
+ continue
+ if path.endswith(".md"):
+ continue
+ if not path.endswith(".py"):
+ # Snapshots, SQL, and YAML reach tests without imports — run
+ # everything in the tree.
+ fallback_trees.add(tree)
+ changed_trees.add(tree)
+ continue
+ in_tree_py.append(path)
+ changed_trees.add(tree)
+ if PurePosixPath(path).name == "conftest.py":
+ # Conftest fixtures reach every test in the tree without imports.
+ fallback_trees.add(tree)
+ continue
+ if _is_test_file(path):
+ selected.add(path)
+ continue
+ # Per-file snob calls keep attribution: a changed module no test
+ # imports (deleted or fixture-only) falls back to its whole tree.
+ covered = snob_fn([path]) & universe
+ if covered:
+ selected |= covered
+ else:
+ fallback_trees.add(tree)
+
+ selected |= snob_fn(outside_py) & universe
+ fallback_trees |= conftest_dependent_trees(in_tree_py, trees)
+ selected |= dynamic_import_tests(changed_trees, universe)
+ for tree in fallback_trees:
+ selected |= {test for test in universe if test.startswith(tree + "/")}
+ selected = {test for test in selected if (REPO_ROOT / test).is_file()}
+ return SelectedTests(tests=selected, fallback_trees=fallback_trees)
+
+
+def shard_count(selected_seconds: float, test_file_count: int) -> int:
+ # Never more shards than test files: pytest-split's file granularity would
+ # leave a shard with nothing to collect, and pytest exits nonzero on that.
+ ceiling = min(MAX_SHARDS, max(1, test_file_count))
+ if selected_seconds <= 0:
+ return 1
+ return min(ceiling, max(1, math.ceil(selected_seconds / TARGET_SECONDS_PER_SHARD)))
+
+
+def build_selection(changed_files: list[str], snob_fn=snob_tests) -> Selection:
+ trees = dags_trees()
+ universe = test_universe(trees)
+ durations = load_durations()
+ suite_seconds = round(estimate_seconds(universe, durations))
+
+ reasons = full_run_reasons(changed_files) + removed_tree_reasons(changed_files, trees)
+ if reasons:
+ return Selection(
+ mode="full",
+ reasons=reasons,
+ changed_file_count=len(changed_files),
+ suite_seconds=suite_seconds,
+ )
+
+ picked = select_tests(changed_files, trees, universe, snob_fn=snob_fn)
+ selected = picked.tests
+ selected_seconds = round(estimate_seconds(selected, durations))
+
+ if not selected:
+ return Selection(
+ mode="none",
+ changed_file_count=len(changed_files),
+ suite_seconds=suite_seconds,
+ )
+ if suite_seconds and selected_seconds >= FULL_RUN_DURATION_FRACTION * suite_seconds:
+ return Selection(
+ mode="full",
+ reasons=[f"selection covers most of the suite ({selected_seconds}s of {suite_seconds}s)"],
+ changed_file_count=len(changed_files),
+ selected_seconds=selected_seconds,
+ suite_seconds=suite_seconds,
+ )
+ return Selection(
+ mode="selected",
+ tests=sorted(selected),
+ shards=shard_count(selected_seconds, len(selected)),
+ fallback_trees=sorted(picked.fallback_trees),
+ changed_file_count=len(changed_files),
+ selected_seconds=selected_seconds,
+ suite_seconds=suite_seconds,
+ )
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--base-ref", required=True, help="Base ref for git diff, for example origin/master")
+ parser.add_argument("--pretty", action="store_true", help="Pretty-print JSON")
+ args = parser.parse_args()
+
+ os.chdir(REPO_ROOT)
+ try:
+ changed_files = changed_files_from_git(args.base_ref)
+ except subprocess.CalledProcessError as exc:
+ sys.stderr.write(f"Error: git diff against {args.base_ref!r} failed: {exc.stderr}\n")
+ sys.exit(1)
+
+ selection = build_selection(changed_files)
+ result = asdict(selection) | {"count": selection.count, "base_ref": args.base_ref}
+ sys.stdout.write(json.dumps(result, indent=2 if args.pretty else None, sort_keys=True) + "\n")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tools/test_dagster_test_selection.py b/tools/test_dagster_test_selection.py
new file mode 100644
index 000000000000..821262b2b03e
--- /dev/null
+++ b/tools/test_dagster_test_selection.py
@@ -0,0 +1,273 @@
+from __future__ import annotations
+
+import sys
+import json
+import tempfile
+import subprocess
+import importlib.util
+from pathlib import Path
+from types import ModuleType
+
+import unittest
+
+SCRIPT_PATH = Path(__file__).with_name("dagster_test_selection.py")
+
+
+def _load_module() -> ModuleType:
+ spec = importlib.util.spec_from_file_location("dagster_test_selection", SCRIPT_PATH)
+ assert spec is not None
+ assert spec.loader is not None
+ module = importlib.util.module_from_spec(spec)
+ sys.modules[spec.name] = module
+ spec.loader.exec_module(module)
+ return module
+
+
+class TestDagsterTestSelection(unittest.TestCase):
+ def setUp(self) -> None:
+ self._tmp = tempfile.TemporaryDirectory()
+ root = Path(self._tmp.name)
+ self.addCleanup(self._tmp.cleanup)
+
+ self.module = _load_module()
+ self.module.REPO_ROOT = root
+ self.module.DURATIONS_PATH = root / ".test_durations"
+ self.root = root
+
+ self._write("posthog/dags/deletes.py")
+ self._write("posthog/dags/tests/conftest.py")
+ self._write("posthog/dags/tests/test_deletes.py")
+ self._write("posthog/dags/tests/test_backups.py")
+ self._write("products/web_analytics/dags/cache_warming.py")
+ self._write("products/web_analytics/dags/tests/test_cache_warming.py")
+
+ def _write(self, path: str, content: str = "") -> None:
+ target = self.root / path
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_text(content)
+
+ def _select(self, changed: list[str], snob: dict[str, list[str]] | None = None):
+ snob_map = snob or {}
+
+ def fake_snob(files: list[str]) -> set[str]:
+ return {test for changed_file in files for test in snob_map.get(changed_file, [])}
+
+ return self.module.build_selection(changed, snob_fn=fake_snob)
+
+ def test_infrastructure_changes_force_full_mode(self) -> None:
+ for changed in (
+ "uv.lock",
+ "pytest.ini",
+ "pyproject.toml",
+ ".github/workflows/ci-dagster.yml",
+ ".github/clickhouse-versions.json",
+ ".github/actions/setup-sqlx-cli/action.yml",
+ "tools/dagster_test_selection.py",
+ "tools/test_dagster_test_selection.py",
+ "tools/hogli/hogli.py",
+ "tools/hogli-commands/hogli_commands/db_schema.py",
+ "tools/hogli-commands/hogli_commands/prechecks.py",
+ "tools/hogli-commands/hogli_commands/telemetry_props.py",
+ "tools/hogli-commands/hogli_commands/hint_hook.py",
+ "tools/hogli-commands/hogli_commands/hints.py",
+ "docker-compose.dev.yml",
+ "docker/postgres-init-scripts/init.sql",
+ "rust/persons_migrations/001_initial.sql",
+ "hogli.yaml",
+ "manage.py",
+ "posthog/conftest.py",
+ "conftest.py",
+ "posthog/test/base.py",
+ ):
+ with self.subTest(changed=changed):
+ selection = self._select([changed, "posthog/dags/deletes.py"])
+ self.assertEqual(selection.mode, "full")
+ self.assertTrue(selection.reasons)
+
+ def test_a_conftest_outside_dags_trees_does_not_force_full_mode(self) -> None:
+ selection = self._select(["products/web_analytics/backend/conftest.py"])
+ self.assertEqual(selection.mode, "none")
+
+ def test_too_many_changed_files_force_full_mode(self) -> None:
+ changed = [f"posthog/dags/file_{i}.py" for i in range(self.module.MAX_CHANGED_FILES + 1)]
+ selection = self._select(changed)
+ self.assertEqual(selection.mode, "full")
+
+ def test_changed_test_file_selects_itself(self) -> None:
+ selection = self._select(["posthog/dags/tests/test_deletes.py"])
+ self.assertEqual(selection.mode, "selected")
+ self.assertEqual(selection.tests, ["posthog/dags/tests/test_deletes.py"])
+
+ def test_changed_dag_module_selects_its_importing_tests(self) -> None:
+ selection = self._select(
+ ["posthog/dags/deletes.py"],
+ snob={"posthog/dags/deletes.py": ["posthog/dags/tests/test_deletes.py"]},
+ )
+ self.assertEqual(selection.mode, "selected")
+ self.assertEqual(selection.tests, ["posthog/dags/tests/test_deletes.py"])
+
+ def test_blind_spot_changes_fall_back_to_the_whole_tree(self) -> None:
+ for changed in (
+ "posthog/dags/tests/conftest.py",
+ "posthog/dags/tests/__snapshots__/test_deletes.ambr",
+ "posthog/dags/deleted_module.py",
+ ):
+ with self.subTest(changed=changed):
+ selection = self._select([changed])
+ self.assertEqual(selection.mode, "selected")
+ self.assertEqual(
+ selection.tests,
+ ["posthog/dags/tests/test_backups.py", "posthog/dags/tests/test_deletes.py"],
+ )
+ self.assertEqual(selection.fallback_trees, ["posthog/dags"])
+
+ def test_tree_fallback_stays_within_the_changed_tree(self) -> None:
+ selection = self._select(["products/web_analytics/dags/tests/conftest.py"])
+ self.assertEqual(selection.tests, ["products/web_analytics/dags/tests/test_cache_warming.py"])
+
+ def test_shared_conftest_changes_select_trees_whose_conftest_imports_it(self) -> None:
+ self._write(
+ "products/web_analytics/dags/tests/conftest.py",
+ "from posthog.dags.tests.conftest import cluster # noqa: F401\n",
+ )
+ selection = self._select(["posthog/dags/tests/conftest.py"])
+ self.assertIn("products/web_analytics/dags/tests/test_cache_warming.py", selection.tests)
+
+ def test_fixture_modules_used_by_another_trees_conftest_select_that_tree(self) -> None:
+ self._write("posthog/dags/tests/fixtures.py")
+ for import_line in (
+ "from posthog.dags.tests.fixtures import thing # noqa: F401\n",
+ "from posthog.dags.tests import fixtures # noqa: F401\n",
+ ):
+ with self.subTest(import_line=import_line):
+ self._write("products/web_analytics/dags/tests/conftest.py", import_line)
+ selection = self._select(
+ ["posthog/dags/tests/fixtures.py"],
+ snob={"posthog/dags/tests/fixtures.py": ["posthog/dags/tests/test_deletes.py"]},
+ )
+ self.assertIn("products/web_analytics/dags/tests/test_cache_warming.py", selection.tests)
+ self.assertIn("posthog/dags/tests/test_deletes.py", selection.tests)
+
+ def test_dynamic_import_tests_run_for_any_change_in_their_tree(self) -> None:
+ self._write(
+ "posthog/dags/tests/test_loggers.py",
+ "import importlib\n\ndef test_locations():\n importlib.import_module('posthog.dags.locations.x')\n",
+ )
+ selection = self._select(
+ ["posthog/dags/deletes.py"],
+ snob={"posthog/dags/deletes.py": ["posthog/dags/tests/test_deletes.py"]},
+ )
+ self.assertIn("posthog/dags/tests/test_loggers.py", selection.tests)
+ self.assertNotIn("posthog/dags/tests/test_backups.py", selection.tests)
+
+ def test_a_deleted_dags_tree_forces_full_mode(self) -> None:
+ selection = self._select(["products/removed_product/dags/some_dag.py"])
+ self.assertEqual(selection.mode, "full")
+ self.assertTrue(any("no longer exists" in reason for reason in selection.reasons))
+
+ def test_markdown_changes_in_a_dags_tree_select_nothing(self) -> None:
+ selection = self._select(["posthog/dags/README.md"])
+ self.assertEqual(selection.mode, "none")
+
+ def test_changes_outside_dags_trees_keep_only_dag_tests_from_snob(self) -> None:
+ selection = self._select(
+ ["posthog/models/team.py"],
+ snob={
+ "posthog/models/team.py": [
+ "posthog/dags/tests/test_deletes.py",
+ "posthog/api/test/test_team.py",
+ ]
+ },
+ )
+ self.assertEqual(selection.mode, "selected")
+ self.assertEqual(selection.tests, ["posthog/dags/tests/test_deletes.py"])
+
+ def test_changes_outside_dags_trees_with_no_dag_impact_select_nothing(self) -> None:
+ selection = self._select(["posthog/models/team.py"], snob={"posthog/models/team.py": []})
+ self.assertEqual(selection.mode, "none")
+
+ def test_deleted_test_files_are_dropped_from_the_selection(self) -> None:
+ selection = self._select(
+ ["posthog/dags/deletes.py"],
+ snob={"posthog/dags/deletes.py": ["posthog/dags/tests/test_deletes.py", "posthog/dags/tests/test_gone.py"]},
+ )
+ self.assertEqual(selection.tests, ["posthog/dags/tests/test_deletes.py"])
+
+ def test_selection_covering_most_of_the_suite_falls_back_to_full_mode(self) -> None:
+ self._write(
+ ".test_durations",
+ json.dumps(
+ {
+ "posthog/dags/tests/test_deletes.py::test_a": 900.0,
+ "posthog/dags/tests/test_backups.py::test_b": 100.0,
+ }
+ ),
+ )
+ selection = self._select(
+ ["posthog/dags/deletes.py"],
+ snob={"posthog/dags/deletes.py": ["posthog/dags/tests/test_deletes.py"]},
+ )
+ self.assertEqual(selection.mode, "full")
+
+ def test_shard_count_grows_with_selected_duration_but_never_exceeds_test_files(self) -> None:
+ for seconds, files, expected in (
+ (0, 5, 1),
+ (899, 5, 1),
+ (901, 5, 2),
+ (99999, 5, self.module.MAX_SHARDS),
+ (99999, 1, 1),
+ (901, 1, 1),
+ ):
+ with self.subTest(seconds=seconds, files=files):
+ self.assertEqual(self.module.shard_count(seconds, files), expected)
+
+ def test_renamed_module_reports_both_the_old_and_new_path(self) -> None:
+ repo = self.root / "repo"
+ (repo / "posthog" / "dags").mkdir(parents=True)
+ self.module.__dict__["REPO_ROOT"] = repo
+
+ def git(*args: str) -> str:
+ return subprocess.run(["git", *args], cwd=repo, capture_output=True, text=True, check=True).stdout.strip()
+
+ git("init", "-q")
+ git("config", "user.email", "[email protected]")
+ git("config", "user.name", "t")
+ (repo / "posthog" / "dags" / "foo.py").write_text("x\n")
+ git("add", "-A")
+ base = git("commit-tree", git("write-tree"), "-m", "base")
+ (repo / "posthog" / "dags" / "foo.py").unlink()
+ (repo / "posthog" / "dags" / "bar.py").write_text("x\n")
+ git("add", "-A")
+ head = git("commit-tree", git("write-tree"), "-p", base, "-m", "rename")
+ git("update-ref", "HEAD", head)
+
+ changed = self.module.changed_files_from_git(base)
+ self.assertIn("posthog/dags/foo.py", changed)
+ self.assertIn("posthog/dags/bar.py", changed)
+
+ def test_selected_mode_reports_shards_from_durations(self) -> None:
+ self._write(
+ ".test_durations",
+ json.dumps(
+ {
+ "posthog/dags/tests/test_deletes.py::test_a": 1000.0,
+ "posthog/dags/tests/test_backups.py::test_b": 1000.0,
+ "products/web_analytics/dags/tests/test_cache_warming.py::test_c": 8000.0,
+ }
+ ),
+ )
+ selection = self._select(
+ ["posthog/dags/deletes.py"],
+ snob={
+ "posthog/dags/deletes.py": [
+ "posthog/dags/tests/test_deletes.py",
+ "posthog/dags/tests/test_backups.py",
+ ]
+ },
+ )
+ self.assertEqual(selection.mode, "selected")
+ self.assertEqual(selection.shards, 2)
+
+
+if __name__ == "__main__":
+ unittest.main()