: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
perf(ci): cache compiled hog bytecode across node test runs (#88431)
Ben Whiteaf44b53a2626
diff --git a/.github/scripts/hog_compiler_fingerprint.py b/.github/scripts/hog_compiler_fingerprint.pynew file mode 100644index 000000000000..b2e5fb578623--- /dev/null+++ b/.github/scripts/hog_compiler_fingerprint.py@@ -0,0 +1,62 @@+#!/usr/bin/env python3+"""Print a cache-key fingerprint of the hog compiler, as `hash=<hex>` for $GITHUB_OUTPUT.++The Jest suites cache compiled hog bytecode keyed by the snippet's source, which stays correct+only while the compiler emits the same bytecode for that source. A fixed list of paths cannot+express that: the closure already reaches `posthog/celery.py` and `posthog/schema_enums.py`, and+nothing stops it reaching further. So import the compiler and hash whatever it actually loaded.+"""++import os+import sys+import hashlib+from collections.abc import Iterable++REPO_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))+++def select_paths(module_files: Iterable[str | None], repo_root: str, self_file: str) -> list[str]:+ """Repo-relative paths of the loaded first-party modules, minus this script.++ Third-party packages are pinned by uv.lock and none of them shape emitted bytecode, so they+ stay out: including them would invalidate the cache on every dependency bump.++ This script is dropped by path rather than by module name, because multiprocessing registers+ the entry module a second time as `__mp_main__` — excluding `__main__` alone lets it back in,+ and then every edit here invalidates every cache.+ """+ prefix = repo_root + os.sep+ paths = {+ os.path.relpath(path, repo_root)+ for path in module_files+ if path and path.startswith(prefix) and "site-packages" not in path+ }+ return sorted(paths - {os.path.relpath(self_file, repo_root)})+++def main() -> None:+ # Running a script puts its own directory on the path, not the repo root.+ sys.path.insert(0, REPO_ROOT)+ # This import is what populates the closure read below.+ from posthog.hogql.compiler.bytecode import create_bytecode # noqa: F401++ paths = select_paths(+ (getattr(module, "__file__", None) for module in list(sys.modules.values())),+ REPO_ROOT,+ os.path.abspath(__file__),+ )+ if not paths:+ raise SystemExit("no first-party compiler modules found — refusing to emit an empty key")++ digest = hashlib.sha256()+ for path in paths:+ digest.update(path.encode())+ with open(os.path.join(REPO_ROOT, path), "rb") as handle:+ digest.update(handle.read())++ sys.stdout.write(f"hash={digest.hexdigest()[:16]}\n")+ sys.stderr.write(f"fingerprinted {len(paths)} compiler modules\n")+++if __name__ == "__main__":+ main()diff --git a/.github/scripts/test_hog_compiler_fingerprint.py b/.github/scripts/test_hog_compiler_fingerprint.pynew file mode 100644index 000000000000..db83207d3b82--- /dev/null+++ b/.github/scripts/test_hog_compiler_fingerprint.py@@ -0,0 +1,39 @@+"""Tests for the module selection behind the hog bytecode cache key.++Run with: uv run --with pytest pytest .github/scripts/test_hog_compiler_fingerprint.py+"""++import sys+from pathlib import Path++import pytest++sys.path.insert(0, str(Path(__file__).parent))++from hog_compiler_fingerprint import select_paths++REPO = "/repo"+SELF = "/repo/.github/scripts/hog_compiler_fingerprint.py"+++class TestSelectPaths:+ @pytest.mark.parametrize(+ "case,module_files,expected",+ [+ ("first party", ["/repo/posthog/hogql/ast.py"], ["posthog/hogql/ast.py"]),+ ("third party", ["/repo/.venv/lib/python3.13/site-packages/django/db.py"], []),+ ("outside the repo", ["/usr/lib/python3.13/os.py"], []),+ ("no file", [None], []),+ # A key that moves when this script gets a comment would invalidate every entry for+ # nothing, and multiprocessing re-registers the entry module, so excluding it by+ # module name misses the second copy.+ ("this script, once per module alias", [SELF, SELF], []),+ ],+ )+ def test_selects(self, case: str, module_files: list[str | None], expected: list[str]) -> None:+ assert select_paths(module_files, REPO, SELF) == expected, case++ def test_deduplicates_and_sorts(self) -> None:+ files = ["/repo/posthog/celery.py", "/repo/common/hogvm/python/operation.py", "/repo/posthog/celery.py"]++ assert select_paths(files, REPO, SELF) == ["common/hogvm/python/operation.py", "posthog/celery.py"]diff --git a/.github/workflows/ci-nodejs.yml b/.github/workflows/ci-nodejs.ymlindex ebc0e939227b..0912fc351ed5 100644--- a/.github/workflows/ci-nodejs.yml+++ b/.github/workflows/ci-nodejs.yml@@ -464,6 +464,23 @@ jobs:SHARD_COUNT: 3run: bin/turbo --filter=@posthog/nodejs prepare+ # `compileHog` shells out to `python3 -m posthog.hogql.cli` once per snippet, ~2s of+ # interpreter start each, and the CDP template suites compile hundreds. Entries are keyed+ # by the snippet's own source, so a restored one can only be right for that source. What+ # the source cannot cover is the compiler changing its output, hence the fingerprint.+ - name: Fingerprint the hog compiler+ id: hog-compiler+ run: python .github/scripts/hog_compiler_fingerprint.py >> "$GITHUB_OUTPUT"++ - name: Restore compiled hog bytecode+ uses: actions/cache/restore@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3+ with:+ path: nodejs/.tmp/hog-bytecode.json+ key: hog-bytecode-${{ matrix.shard }}-${{ steps.hog-compiler.outputs.hash }}-${{ github.sha }}+ # Prefix match, so master's newest entry for this shard is reused. Deliberately+ # does not fall back past the fingerprint: older bytecode would be stale.+ restore-keys: hog-bytecode-${{ matrix.shard }}-${{ steps.hog-compiler.outputs.hash }}-+- name: Test with Jestid: run-jest# continue-on-error so the quarantine gate below is the verdict — it passes when@@ -507,6 +524,15 @@ jobs:JEST_JUNIT_ADD_FILE_ATTRIBUTE: 'true'run: cd nodejs && pnpm run test:postgres-parity+ # Master only, so PR runs read the cache without each writing an entry nobody else can+ # reuse. Saves after a failing run too — the snippets it did compile are still valid.+ - name: Save compiled hog bytecode+ if: ${{ !cancelled() && github.ref == 'refs/heads/master' }}+ uses: actions/cache/save@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3+ with:+ path: nodejs/.tmp/hog-bytecode.json+ key: hog-bytecode-${{ matrix.shard }}-${{ steps.hog-compiler.outputs.hash }}-${{ github.sha }}+# Best-effort Trunk upload (continue-on-error); the "Fail on test failure" step below is# the verdict, so a Trunk outage can't red a passing shard. Internal PRs only (needs the# secret).diff --git a/.github/workflows/ci-scripts.yml b/.github/workflows/ci-scripts.ymlindex 51702506e4fa..a8774eb4952c 100644--- a/.github/workflows/ci-scripts.yml+++ b/.github/workflows/ci-scripts.yml@@ -65,6 +65,12 @@ jobs:if: ${{ hashFiles('.github/scripts/test_optimize_test_durations.py') != '' }}run: python -m pytest .github/scripts/test_optimize_test_durations.py -v -c /dev/null -p no:cacheprovider --noconftest+ # A wrong fingerprint is silent: the Jest bytecode cache either serves stale entries or+ # never hits, and nothing goes red either way. hashFiles guard for unrebased PRs.+ - name: Hog compiler fingerprint tests (Python)+ if: ${{ hashFiles('.github/scripts/test_hog_compiler_fingerprint.py') != '' }}+ run: python -m pytest .github/scripts/test_hog_compiler_fingerprint.py -v -c /dev/null -p no:cacheprovider --noconftest+# hashFiles guard so an unrebased PR predating this script doesn't fail here.- name: Workflow-run trace reporter tests (Python)if: ${{ hashFiles('.github/scripts/test_report_workflow_run_traces.py') != '' }}diff --git a/nodejs/src/cdp/templates/compiler.ts b/nodejs/src/cdp/templates/compiler.tsindex fec32486889a..6dfb7c33978d 100644--- a/nodejs/src/cdp/templates/compiler.ts+++ b/nodejs/src/cdp/templates/compiler.ts@@ -11,7 +11,9 @@ import { HogBytecode } from '../types'import { Semaphore } from '../utils/sempahore'const ROOT_DIR = path.join(__dirname, '..', '..', '..', '..')-const CACHE_FILE = path.join(__dirname, '.tmp/cache.json')+// Outside src/, which turbo hashes as an input of this package's test task: a cache written+// in there makes every run that compiles a new snippet change the hash of the task writing it.+const CACHE_FILE = path.join(ROOT_DIR, 'nodejs', '.tmp', 'hog-bytecode.json')let CACHE: Record<string, HogBytecode> | null = nullconst CONCURRENT_WORKERS = 10