: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
fix(devex): share depot mirror check with preflight (#100640)
Raúl Negrón-Otero04c469dbde58
diff --git a/.github/workflows/ci-backend-shadow-drift.yml b/.github/workflows/ci-backend-shadow-drift.ymlindex 7ae0c1a65cbe..136e4c5e53a3 100644--- a/.github/workflows/ci-backend-shadow-drift.yml+++ b/.github/workflows/ci-backend-shadow-drift.yml@@ -4,9 +4,10 @@ name: Backend CI shadow drift check# without a matching update to the Depot shadow. The workflow is hand-maintained# (see its header comment for intentional deltas), while the actions are vendored;# without this check, canonical drifts silently and the Depot timing trial stops-# measuring the same work.+# measuring the same work. The check lives in depot_mirrors.py, which+# `hogli ci:preflight` also runs before a push.#-# Cheap to run — only triggers when one of the mirrored paths changes, so it costs ~nothing.+# Cheap to run: it triggers only on changes to the backend workflow, local actions, Depot files, or the check itself.# Always enforced (no variable gate): keeping the depot mirror in sync with canonical is# a structural invariant worth holding whether or not the shadow is currently sampling —# you want them already in sync the moment the shadow is switched on. The sampling rate@@ -16,22 +17,11 @@ name: Backend CI shadow drift checkon:pull_request:paths:+ - .github/workflows/ci-backend-shadow-drift.yml- .github/workflows/ci-backend.yml- - .depot/workflows/ci-backend.yml- - .github/actions/paths-filter/**- - .depot/actions/paths-filter/**- - .github/actions/pnpm-install/**- - .depot/actions/pnpm-install/**- - .github/actions/setup-pnpm/**- - .depot/actions/setup-pnpm/**- - .github/actions/setup-python-cached/**- - .depot/actions/setup-python-cached/**- - .github/actions/setup-sqlx-cli/**- - .depot/actions/setup-sqlx-cli/**- - .github/actions/setup-turbo/**- - .depot/actions/setup-turbo/**- - .github/actions/setup-uv/**- - .depot/actions/setup-uv/**+ - .github/actions/**+ - .depot/**+ - tools/hogli-commands/hogli_commands/depot_mirrors.pypermissions:contents: read@@ -59,40 +49,4 @@ jobs:# is the merge commit — diffing BASE_SHA..HEAD gives the PR's effective# changes. We only need to fetch BASE_SHA (HEAD is already local).git fetch --no-tags --depth=100 origin "$BASE_SHA"- # Every local action the depot workflow uses has a mirror under .depot/actions.- # The first group is kept byte-identical to canonical; the second carries- # intentional deltas documented in each mirror's header.- equal_mirrors="paths-filter setup-python-cached setup-sqlx-cli setup-turbo setup-uv"- delta_mirrors="pnpm-install setup-pnpm"- changed=$(git diff --name-only "$BASE_SHA" HEAD -- \- .github/workflows/ci-backend.yml \- .depot/workflows/ci-backend.yml \- .github/actions .depot/actions)- if echo "$changed" | grep -Fxq '.github/workflows/ci-backend.yml' && \- ! echo "$changed" | grep -Fxq '.depot/workflows/ci-backend.yml'; then- echo "::error::Canonical .github/workflows/ci-backend.yml changed without a matching update to .depot/workflows/ci-backend.yml."- echo "The depot shadow must stay apples-to-apples with canonical. Mirror the change into the depot file"- echo "(or, if the change is one of the intentional deltas listed in the depot file header, document why it is depot-exempt)."- exit 1- fi- if echo "$changed" | grep -Fxq '.depot/workflows/ci-backend.yml' && \- ! echo "$changed" | grep -Fxq '.github/workflows/ci-backend.yml'; then- echo "::notice::Only the depot shadow changed. That is allowed (e.g. tuning a depot-only knob), but worth a glance from the reviewer."- fi- for action in $equal_mirrors $delta_mirrors; do- for canonical_file in $(echo "$changed" | grep "^\.github/actions/$action/" || true); do- mirror_file=".depot/actions/$action/${canonical_file#".github/actions/$action/"}"- if ! echo "$changed" | grep -Fxq "$mirror_file"; then- echo "::error::Canonical $canonical_file changed without a matching update to $mirror_file."- echo "Mirror the action change so the Depot workflow runs the same steps."- exit 1- fi- done- done- for action in $equal_mirrors; do- if ! diff -qr ".github/actions/$action" ".depot/actions/$action"; then- echo "::error::The Depot $action action differs from its canonical copy."- exit 1- fi- done- echo "Shadow drift check passed."+ python3 tools/hogli-commands/hogli_commands/depot_mirrors.py "$BASE_SHA"diff --git a/tools/hogli-commands/hogli_commands/ci_preflight.py b/tools/hogli-commands/hogli_commands/ci_preflight.pyindex 77ac52c12391..fafb0da4bb95 100644--- a/tools/hogli-commands/hogli_commands/ci_preflight.py+++ b/tools/hogli-commands/hogli_commands/ci_preflight.py@@ -47,6 +47,7 @@ from hogli_commands.build import ()from hogli_commands.change_detection import changed_files, matches_globsfrom hogli_commands.complexity_lint import PYTHON_SCOPE, TEST_WARN_AT, TYPESCRIPT_SCOPE, WARN_AT+from hogli_commands.depot_mirrors import mirror_violationsfrom hogli_commands.devenv.generator import TRACKED_MPROCS_FILESfrom hogli_commands.size_lint import SCOPE as SIZE_SCOPE@@ -282,37 +283,9 @@ DIFF_CHECKS: list[DiffCheck] = []-@dataclass(frozen=True, kw_only=True, slots=True)-class CompanionCheck:- """Paths a CI gate requires to move together."""-- key: str- label: str- source: str- companion: str- escape_hatch: str # what to do when the change is deliberately one-sided- exact_mirror: bool = False---# Duplicated from .github/workflows/ci-backend-shadow-drift.yml so the failure lands-# pre-push instead of a CI round-trip. A test binds the two so they cannot drift.-COMPANION_CHECKS: list[CompanionCheck] = [- CompanionCheck(- key="shadow-drift",- label="depot shadow drift (.depot mirror of ci-backend.yml)",- source=".github/workflows/ci-backend.yml",- companion=".depot/workflows/ci-backend.yml",- escape_hatch="document it as an intentional delta in that file's header",- ),- CompanionCheck(- key="paths-filter-shadow-drift",- label="depot paths-filter drift (.depot mirror of the canonical action)",- source=".github/actions/paths-filter/**",- companion=".depot/actions/paths-filter/**",- escape_hatch="mirror the canonical action change",- exact_mirror=True,- ),-]+# A change under these paths can fail .github/workflows/ci-backend-shadow-drift.yml, which runs+# the same depot_mirrors check. Running it here lands the failure pre-push instead of in CI.+SHADOW_DRIFT_TRIGGERS = [".github/workflows/ci-backend.yml", ".github/actions/**", ".depot/**"]def _has_node_modules() -> bool:@@ -484,26 +457,6 @@ def _run_diff_check(chk: DiffCheck, do_fix: bool, against: str | None, strict: breturn "fail", " · ".join(lines[:3]) if lines else f"exit {result.returncode}"-def _run_companion_check(chk: CompanionCheck, files: list[str]) -> tuple[Status, str]:- if any(matches_globs(path, [chk.companion]) for path in files):- if chk.exact_mirror:- source_root = REPO_ROOT / chk.source.removesuffix("/**")- companion_root = REPO_ROOT / chk.companion.removesuffix("/**")- source_files = {path.relative_to(source_root): path for path in source_root.rglob("*") if path.is_file()}- companion_files = {- path.relative_to(companion_root): path for path in companion_root.rglob("*") if path.is_file()- }- if source_files.keys() != companion_files.keys():- return "fail", "mirror file sets differ"- differing = [- path for path in source_files if source_files[path].read_bytes() != companion_files[path].read_bytes()- ]- if differing:- return "fail", f"mirrors differ: {', '.join(str(path) for path in differing[:3])}"- return "pass", "both files updated"- return "fail", f"mirror the change into {chk.companion}, or {chk.escape_hatch}"--# Branch-freshness backstop thresholds. The risk signals in ``_staleness_risks``# are the primary advisory trigger; these are a secondary net for branches old# enough that generic (undetected) drift is likely. Deliberately aggressive to@@ -735,15 +688,7 @@ def ci_preflight(do_fix: bool, strict: bool, against: str | None, as_json: bool)chk.matched = [f for f in files if matches_globs(f, chk.triggers)]if chk.matched:triggered.append(chk)- triggered_companions = [- companion- for companion in COMPANION_CHECKS- if any(- matches_globs(path, [companion.source])- or (companion.exact_mirror and matches_globs(path, [companion.companion]))- for path in files- )- ]+ shadow_drift_triggered = any(matches_globs(path, SHADOW_DRIFT_TRIGGERS) for path in files)results: list[dict[str, Any]] = []failures = 0@@ -760,13 +705,18 @@ def ci_preflight(do_fix: bool, strict: bool, against: str | None, as_json: bool)click.secho(f" {_ICON[stale_status]} [staleness] branch freshness vs master", fg=_COLOR[stale_status])click.echo(f" {stale_detail}")- for companion in triggered_companions:- status, detail = _run_companion_check(companion, files)- failures += status == "fail"- results.append({"check": companion.key, "status": status, "files": 1, "detail": detail})+ if shadow_drift_triggered:+ violations = mirror_violations(REPO_ROOT, set(files))+ drift_status: Status = "fail" if violations else "pass"+ drift_detail = " · ".join(violations[:3]) if violations else "depot mirrors in sync"+ failures += drift_status == "fail"+ results.append({"check": "shadow-drift", "status": drift_status, "files": 1, "detail": drift_detail})if not as_json:- click.secho(f" {_ICON[status]} [{companion.key}] {companion.label}", fg=_COLOR[status])- click.echo(f" {detail}")+ click.secho(+ f" {_ICON[drift_status]} [shadow-drift] depot shadow drift (.depot mirrors of backend CI)",+ fg=_COLOR[drift_status],+ )+ click.echo(f" {drift_detail}")for chk in triggered:status, detail = _run_diff_check(chk, do_fix, against, strict)@@ -781,7 +731,7 @@ def ci_preflight(do_fix: bool, strict: bool, against: str | None, as_json: bool)summary = {"changed_files": len(files),- "triggered": [c.key for c in triggered_companions] + [c.key for c in triggered],+ "triggered": (["shadow-drift"] if shadow_drift_triggered else []) + [c.key for c in triggered],"failures": failures,"advisories": advisories,"mode": "fix" if do_fix else ("strict" if strict else "advisory"),@@ -791,7 +741,7 @@ def ci_preflight(do_fix: bool, strict: bool, against: str | None, as_json: bool)if as_json:click.echo(json.dumps(summary))else:- if not triggered and not triggered_companions:+ if not triggered and not shadow_drift_triggered:click.secho(" ✓ Nothing in this diff maps to a known CI failure class.", fg="green")click.echo()click.echo(diff --git a/tools/hogli-commands/hogli_commands/depot_mirrors.py b/tools/hogli-commands/hogli_commands/depot_mirrors.pynew file mode 100644index 000000000000..9eb0979491ef--- /dev/null+++ b/tools/hogli-commands/hogli_commands/depot_mirrors.py@@ -0,0 +1,69 @@+"""Keeps the Depot shadow of backend CI in sync with its canonical workflow and local actions.++`.github/workflows/ci-backend-shadow-drift.yml` runs this file with the runner's python3 before any+dependency install, and `hogli ci:preflight` imports it, so it must stay standard library only.+"""++from __future__ import annotations++import re+import sys+import subprocess+from pathlib import Path++CANONICAL_WORKFLOW = ".github/workflows/ci-backend.yml"+SHADOW_WORKFLOW = ".depot/workflows/ci-backend.yml"+# These mirrors carry intentional deltas that each mirror's header documents.+# Every other mirror stays byte-identical to its canonical action.+DELTA_MIRRORS = frozenset({"pnpm-install", "setup-pnpm"})+# Depot resolves both `./.github/actions/<name>` and `./.depot/actions/<name>` from .depot/actions/<name>.+LOCAL_ACTION_USE = re.compile(r"""uses:\s*['"]?\./\.(?:github|depot)/actions/([A-Za-z0-9_.-]+)""")+++def used_mirrors(root: Path) -> set[str]:+ return {name for path in (root / ".depot").rglob("*.y*ml") for name in LOCAL_ACTION_USE.findall(path.read_text())}+++def _file_bytes(directory: Path) -> dict[Path, bytes]:+ return {path.relative_to(directory): path.read_bytes() for path in directory.rglob("*") if path.is_file()}+++def mirror_violations(root: Path, changed: set[str]) -> list[str]:+ violations: list[str] = []+ if CANONICAL_WORKFLOW in changed and SHADOW_WORKFLOW not in changed:+ violations.append(+ f"{CANONICAL_WORKFLOW} changed without a matching update to {SHADOW_WORKFLOW}. "+ "Mirror the change, or document it as an intentional delta in the shadow's header."+ )+ for name in sorted(used_mirrors(root)):+ canonical = f".github/actions/{name}/"+ mirror = f".depot/actions/{name}/"+ if not (root / mirror).is_dir():+ violations.append(f"A Depot file uses the {name} action, but {mirror} does not exist.")+ continue+ violations.extend(+ f"{path} changed without a matching update to {mirror}{path.removeprefix(canonical)}."+ for path in sorted(changed)+ if path.startswith(canonical) and mirror + path.removeprefix(canonical) not in changed+ )+ if name not in DELTA_MIRRORS and _file_bytes(root / canonical) != _file_bytes(root / mirror):+ violations.append(f"{mirror} differs from its canonical copy {canonical}.")+ return violations+++def main(base_sha: str) -> int:+ diff = subprocess.run(["git", "diff", "--name-only", base_sha, "HEAD"], check=True, capture_output=True, text=True)+ changed = set(diff.stdout.splitlines())+ if SHADOW_WORKFLOW in changed and CANONICAL_WORKFLOW not in changed:+ sys.stdout.write(+ f"::notice::Only {SHADOW_WORKFLOW} changed. That is allowed, for example to tune a Depot-only knob.\n"+ )+ violations = mirror_violations(Path.cwd(), changed)+ sys.stdout.writelines(f"::error::{violation}\n" for violation in violations)+ if not violations:+ sys.stdout.write("The Depot shadow is in sync.\n")+ return 1 if violations else 0+++if __name__ == "__main__":+ sys.exit(main(sys.argv[1]))diff --git a/tools/hogli-commands/hogli_commands/tests/test_ci_preflight.py b/tools/hogli-commands/hogli_commands/tests/test_ci_preflight.pyindex 71540819086b..23ce7626d2ab 100644--- a/tools/hogli-commands/hogli_commands/tests/test_ci_preflight.py+++ b/tools/hogli-commands/hogli_commands/tests/test_ci_preflight.py@@ -9,13 +9,7 @@ from click.testing import CliRunnerfrom hogli.cli import clifrom hogli.manifest import REPO_ROOTfrom hogli_commands.change_detection import matches_globs-from hogli_commands.ci_preflight import (- COMPANION_CHECKS,- DIFF_CHECKS,- _pnpm_workspace_root,- _run_workspace_scoped,- _staleness_risks,-)+from hogli_commands.ci_preflight import DIFF_CHECKS, _pnpm_workspace_root, _run_workspace_scoped, _staleness_risksrunner = CliRunner()@@ -325,43 +319,29 @@ class TestWorkspaceScopedLockfile:assert "products/desktop: needs node" in detail-class TestShadowDriftCompanion:+class TestShadowDriftCheck:@pytest.mark.parametrize("changed,expected_exit,expected_fragment",[- ([".github/workflows/ci-backend.yml"], 1, "mirror the change into .depot/workflows/ci-backend.yml"),- ([".github/workflows/ci-backend.yml", ".depot/workflows/ci-backend.yml"], 0, "both files updated"),- # Depot-only is a notice in CI, never a failure. Blocking it would false-block depot tuning.- ([".depot/workflows/ci-backend.yml"], 0, ""),- (- [".github/actions/paths-filter/src/main.ts"],- 1,- "mirror the change into .depot/actions/paths-filter/**",- ),- (- [- ".github/actions/paths-filter/src/main.ts",- ".depot/actions/paths-filter/src/main.ts",- ],- 0,- "both files updated",- ),- ([".depot/actions/paths-filter/src/main.ts"], 0, "both files updated"),+ ([".github/actions/setup-uv/action.yml"], 1, "setup-uv drifted"),+ (["posthog/api/does_not_exist.py"], 0, None),],)@patch("hogli_commands.ci_preflight._emit_telemetry")@patch("hogli_commands.ci_preflight._staleness", return_value=("pass", "even with master", {}))@patch("hogli_commands.ci_preflight._fetch_master")@patch("hogli_commands.ci_preflight.shutil.which", return_value=None)- def test_verdict_matches_ci(+ @patch("hogli_commands.ci_preflight.mirror_violations", return_value=["setup-uv drifted"])+ def test_blocks_the_push_only_when_depot_paths_change(self,+ mock_violations: MagicMock,mock_which: MagicMock,mock_fetch: MagicMock,mock_stale: MagicMock,mock_emit: MagicMock,changed: list[str],expected_exit: int,- expected_fragment: str,+ expected_fragment: str | None,) -> None:with patch("hogli_commands.ci_preflight.changed_files", return_value=changed):result = runner.invoke(cli, ["ci:preflight", "--strict"])@@ -371,14 +351,3 @@ class TestShadowDriftCompanion:assert expected_fragment in result.outputelse:assert "shadow-drift" not in result.output-- def test_pair_matches_workflow(self) -> None:- import yaml- from hogli.manifest import REPO_ROOT-- workflow = yaml.safe_load((REPO_ROOT / ".github" / "workflows" / "ci-backend-shadow-drift.yml").read_text())- # `on` parses as the boolean True in YAML 1.1.- watched = set(workflow[True]["pull_request"]["paths"])- companion_paths = {path for companion in COMPANION_CHECKS for path in (companion.source, companion.companion)}-- assert watched == companion_pathsdiff --git a/tools/hogli-commands/hogli_commands/tests/test_depot_mirrors.py b/tools/hogli-commands/hogli_commands/tests/test_depot_mirrors.pynew file mode 100644index 000000000000..984e196b0403--- /dev/null+++ b/tools/hogli-commands/hogli_commands/tests/test_depot_mirrors.py@@ -0,0 +1,87 @@+from __future__ import annotations++import shutil+from collections.abc import Callable+from pathlib import Path++import pytest++from hogli_commands.depot_mirrors import mirror_violations++TREE = {+ ".depot/workflows/ci-backend.yml": "steps:\n - uses: ./.depot/actions/setup-uv\n - uses: './.github/actions/pnpm-install'\n",+ ".github/actions/setup-uv/action.yml": "name: uv\n",+ ".depot/actions/setup-uv/action.yml": "name: uv\n",+ ".github/actions/pnpm-install/action.yml": "name: pnpm\n",+ ".depot/actions/pnpm-install/action.yml": "name: pnpm with a depot delta\n",+ ".github/actions/semgrep-ci/action.yml": "name: not used by depot\n",+}+++class TestMirrorViolations:+ @pytest.mark.parametrize(+ "changed,mutate,expected",+ [+ pytest.param(+ {+ ".github/actions/setup-uv/action.yml",+ ".depot/actions/setup-uv/action.yml",+ ".github/actions/pnpm-install/action.yml",+ ".depot/actions/pnpm-install/action.yml",+ },+ None,+ None,+ id="in-sync-with-delta-mirror",+ ),+ pytest.param({".github/actions/semgrep-ci/action.yml"}, None, None, id="action-depot-does-not-use"),+ pytest.param(+ {".github/actions/setup-uv/action.yml"},+ None,+ "without a matching update to .depot/actions/setup-uv/action.yml",+ id="canonical-action-only",+ ),+ pytest.param(+ {".github/actions/pnpm-install/action.yml"},+ None,+ "without a matching update to .depot/actions/pnpm-install/action.yml",+ id="canonical-delta-action-only",+ ),+ pytest.param(+ set(),+ lambda root: (root / ".depot/actions/setup-uv/action.yml").write_text("drift\n"),+ ".depot/actions/setup-uv/ differs",+ id="exact-mirror-differs",+ ),+ pytest.param(+ {".depot/actions/pnpm-install/action.yml"},+ lambda root: shutil.rmtree(root / ".depot/actions/pnpm-install"),+ "but .depot/actions/pnpm-install/ does not exist",+ id="used-mirror-deleted",+ ),+ pytest.param(+ {".github/workflows/ci-backend.yml"},+ None,+ "without a matching update to .depot/workflows/ci-backend.yml",+ id="canonical-workflow-only",+ ),+ ],+ )+ def test_reports_drift(+ self,+ tmp_path: Path,+ changed: set[str],+ mutate: Callable[[Path], object] | None,+ expected: str | None,+ ) -> None:+ for relative, content in TREE.items():+ (tmp_path / relative).parent.mkdir(parents=True, exist_ok=True)+ (tmp_path / relative).write_text(content)+ if mutate:+ mutate(tmp_path)++ violations = mirror_violations(tmp_path, changed)++ if expected is None:+ assert violations == []+ else:+ assert any(expected in violation for violation in violations), violations