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): catch lockfile breakage before the merge queue (#102919)

Georges-Antoine Assi812b6ce14e3a
diff --git a/tools/hogli-commands/hogli_commands/ci_preflight.py b/tools/hogli-commands/hogli_commands/ci_preflight.py
index 33b3f306da83..166d07ae0fd6 100644
--- a/tools/hogli-commands/hogli_commands/ci_preflight.py
+++ b/tools/hogli-commands/hogli_commands/ci_preflight.py
@@ -49,6 +49,7 @@ from hogli_commands.change_detection import changed_files, matches_globs
from hogli_commands.complexity_lint import PYTHON_SCOPE, TEST_WARN_AT, TYPESCRIPT_SCOPE, WARN_AT
from hogli_commands.depot_mirrors import mirror_violations
from hogli_commands.devenv.generator import TRACKED_MPROCS_FILES
+from hogli_commands.lockfile_merge import LOCKFILE_GLOBS, missing_resolutions
from hogli_commands.size_lint import SCOPE as SIZE_SCOPE
Requirement = Literal["node", "desktop-node", "stack", "clickhouse", "python-env"]
@@ -106,8 +107,7 @@ DIFF_CHECKS: list[DiffCheck] = [
triggers=[
"package.json",
"*/package.json",
- "pnpm-lock.yaml",
- "*/pnpm-lock.yaml",
+ *LOCKFILE_GLOBS,
"pnpm-workspace.yaml",
"*/pnpm-workspace.yaml",
"patches/*",
@@ -542,14 +542,55 @@ def _commit_age_days(ref: str) -> int | None:
return max(0, (datetime.now(when.tzinfo) - when).days)
-def _merge_conflicts() -> list[str] | None:
- """Files that would conflict if master were merged right now, computed without
- touching the working tree (``git merge-tree``, git >= 2.38). None = can't tell."""
- result = _git_run("merge-tree", "--write-tree", "--name-only", "HEAD", _MASTER_REF)
+@dataclass(frozen=True, kw_only=True, slots=True)
+class MergePreview:
+ """The tree merging master would produce, and the files that would conflict."""
+
+ tree_oid: str
+ conflicts: list[str]
+
+
+def _merge_preview() -> MergePreview | None:
+ """The tree merging master would produce, and the files that would conflict.
+
+ Computed without touching the working tree (``git merge-tree``, git >= 2.38).
+ None = can't tell. The tree is written to the object store, so a caller can
+ read the merged content of any file out of it.
+
+ ``--no-messages`` drops the trailing "Auto-merging"/"CONFLICT" prose, which
+ otherwise lands in the same stream as the file names and counts as conflicted
+ files: one conflicted file reads as three without it.
+ """
+ result = _git_run("merge-tree", "--write-tree", "--name-only", "--no-messages", "HEAD", _MASTER_REF)
if result is None or result.returncode not in (0, 1):
return None
+ lines = result.stdout.splitlines()
+ if not lines or not lines[0].strip():
+ return None
# returncode 1 = conflicts; first output line is the merged tree OID.
- return [line for line in result.stdout.splitlines()[1:] if line] if result.returncode == 1 else []
+ conflicts = [line for line in lines[1:] if line] if result.returncode == 1 else []
+ return MergePreview(tree_oid=lines[0].strip(), conflicts=conflicts)
+
+
+def _lockfile_breakage(preview: MergePreview, branch_files: list[str], master_files: list[str]) -> list[str]:
+ """Dependencies the merged lockfiles name but no longer resolve.
+
+ Only a lockfile both sides edited can break this way, and one git already
+ reports as conflicted is covered by the conflict risk. The repo keeps a
+ lockfile per pnpm workspace, so every path that matches is checked.
+ """
+ breakage: list[str] = []
+ for path in sorted(set(_matching_lockfiles(branch_files)) & set(_matching_lockfiles(master_files))):
+ if path in preview.conflicts:
+ continue
+ merged = _git("show", f"{preview.tree_oid}:{path}", timeout=20.0)
+ if merged:
+ breakage.extend(missing_resolutions(merged))
+ return breakage
+
+
+def _matching_lockfiles(files: list[str]) -> list[str]:
+ return [f for f in files if matches_globs(f, list(LOCKFILE_GLOBS))]
def _changed_on_master(merge_base: str) -> list[str]:
@@ -562,13 +603,23 @@ def _changed_on_master(merge_base: str) -> list[str]:
_MIGRATION_GLOB = ["*/migrations/*.py"]
-def _staleness_risks(branch_files: list[str], master_files: list[str], conflicts: list[str] | None) -> list[str]:
+def _staleness_risks(
+ branch_files: list[str],
+ master_files: list[str],
+ conflicts: list[str] | None,
+ lockfile_breakage: list[str],
+) -> list[str]:
"""Concrete ways merging master late will break this branch — each a failure
class that recurs on unrebased PRs: textual conflicts, migration collisions,
generated-file drift, and CI workflows changing underneath the branch."""
risks: list[str] = []
if conflicts:
risks.append(f"merging master conflicts in {len(conflicts)} file(s) (e.g. {conflicts[0]})")
+ if lockfile_breakage:
+ risks.append(
+ f"merging master leaves {len(lockfile_breakage)} dependency(s) unresolved in pnpm-lock.yaml "
+ f"(e.g. {lockfile_breakage[0][:60]}) — regenerate with pnpm install --no-frozen-lockfile"
+ )
branch_apps = {str(Path(f).parent) for f in branch_files if matches_globs(f, _MIGRATION_GLOB)}
master_apps = {str(Path(f).parent) for f in master_files if matches_globs(f, _MIGRATION_GLOB)}
collisions = sorted(branch_apps & master_apps)
@@ -602,8 +653,11 @@ def _staleness(branch_files: list[str]) -> tuple[Status, str, dict[str, Any]]:
return "pass", "even with master", {"stale": False, "behind_commits": 0, "branch_age_days": 0}
age_days = _commit_age_days(merge_base) # merge-base age ≈ time since the branch last synced with master
- conflicts = _merge_conflicts()
- risks = _staleness_risks(branch_files, _changed_on_master(merge_base), conflicts)
+ preview = _merge_preview()
+ conflicts = None if preview is None else preview.conflicts
+ master_files = _changed_on_master(merge_base)
+ breakage = _lockfile_breakage(preview, branch_files, master_files) if preview else []
+ risks = _staleness_risks(branch_files, master_files, conflicts, breakage)
if behind >= _env_int("HOGLI_PREFLIGHT_STALE_COMMITS", _STALE_COMMITS_DEFAULT):
risks.append(f"{behind} commits (≈ PRs) behind")
elif age_days is not None and age_days >= _env_int("HOGLI_PREFLIGHT_STALE_DAYS", _STALE_DAYS_DEFAULT):
@@ -615,6 +669,7 @@ def _staleness(branch_files: list[str]) -> tuple[Status, str, dict[str, Any]]:
"branch_age_days": age_days,
"merge_conflict_files": len(conflicts) if conflicts is not None else None,
"staleness_risks": len(risks),
+ "lockfile_unresolved": len(breakage),
}
if risks:
return "advisory", f"{' · '.join(risks)} — merge master in: git merge {_MASTER_REF}", props
@@ -650,6 +705,7 @@ def _emit_telemetry(summary: dict[str, Any]) -> None:
"branch_age_days",
"merge_conflict_files",
"staleness_risks",
+ "lockfile_unresolved",
)
props: dict[str, Any] = {k: summary[k] for k in keys if k in summary}
props["results"] = {r["check"]: r["status"] for r in summary["results"]}
diff --git a/tools/hogli-commands/hogli_commands/lockfile_merge.py b/tools/hogli-commands/hogli_commands/lockfile_merge.py
new file mode 100644
index 000000000000..317b792cadc4
--- /dev/null
+++ b/tools/hogli-commands/hogli_commands/lockfile_merge.py
@@ -0,0 +1,146 @@
+"""Detects a pnpm lockfile that git merged cleanly into an inconsistent state.
+
+`pnpm-lock.yaml` is one file holding two coupled halves: `importers:` names the
+version each workspace package resolved to, and `packages:`/`snapshots:` hold an
+entry per resolved version. A branch that bumps a dependency edits both halves.
+When master bumps the same dependency, git merges the two edits without a
+conflict, because they land in different regions of a 46k-line file. The merged
+lockfile can then name a version in `importers:` that no longer has an entry, and
+pnpm refuses it with ERR_PNPM_LOCKFILE_MISSING_DEPENDENCY.
+
+Nothing catches that before the merge happens. The branch's own lockfile is
+valid, master's is valid, and only their merge is not, so the failure first
+appears in the merge queue where the Docker build runs `--frozen-lockfile`.
+
+This reads the lockfile rather than running `pnpm install --frozen-lockfile`
+because the merged lockfile exists only as a git tree. Running pnpm against it
+would mean materializing that tree and every `package.json` in it to disk first,
+then a possible registry round-trip, on a path that runs before every push. The
+answer is already in the file: an importer version with no matching resolution
+key is exactly what `--frozen-lockfile` rejects.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Iterator
+from dataclasses import dataclass
+
+# The paths the `lockfile` preflight check already watches, so the two cannot
+# disagree about where this repo keeps lockfiles. It has six, not one.
+LOCKFILE_GLOBS = ("pnpm-lock.yaml", "*/pnpm-lock.yaml")
+
+# Versions that resolve to a path or another workspace package rather than to a
+# registry snapshot, so the resolution sections have nothing to hold for them.
+_NON_REGISTRY_PREFIXES = ("link:", "file:", "workspace:")
+
+_DEPENDENCY_BLOCKS = ("dependencies:", "devDependencies:", "optionalDependencies:")
+
+# The layout below is the one pnpm writes for lockfileVersion 9. Reading a
+# version this parser does not know would mistake an unrecognized layout for a
+# lockfile that resolves nothing, and report every dependency as broken.
+_SUPPORTED_LOCKFILE_MAJOR = "9"
+
+
+@dataclass(frozen=True, kw_only=True, slots=True)
+class _ImporterDependency:
+ """One dependency an importer declares, and the version it resolved to."""
+
+ package: str
+ version: str
+
+
+def _unquote(text: str) -> str:
+ if len(text) >= 2 and text[0] == text[-1] and text[0] in "'\"":
+ return text[1:-1]
+ return text
+
+
+def _key_before_colon(stripped: str) -> str | None:
+ """The mapping key on a lockfile line, unquoted, or None for a non-key line.
+
+ An unquoted key can itself contain ':' when the version is a tarball URL, so
+ it ends either at the end of the line or at the first ': ' before a value.
+ """
+ if stripped.startswith(("'", '"')):
+ quote = stripped[0]
+ end = stripped.find(quote, 1)
+ return None if end == -1 else stripped[1:end]
+ if stripped.endswith(":"):
+ return stripped[:-1]
+ key, sep, _ = stripped.partition(": ")
+ return key if sep else None
+
+
+def _is_supported_layout(lockfile: str) -> bool:
+ """Whether this parser knows the layout, read from the leading version key."""
+ # pnpm writes lockfileVersion first, so only the head is worth splitting: the
+ # whole file is 46k lines and this needs one of them.
+ for line in lockfile.split("\n", 8)[:8]:
+ if line.startswith("lockfileVersion:"):
+ version = _unquote(line[len("lockfileVersion:") :].strip())
+ return version.split(".")[0] == _SUPPORTED_LOCKFILE_MAJOR
+ if line and not line[0].isspace():
+ break
+ return False
+
+
+def _section_lines(lines: list[str], *sections: str) -> Iterator[tuple[int, str]]:
+ """Indent and content of each non-blank line inside the named top-level sections."""
+ in_section = False
+ for line in lines:
+ if line and not line[0].isspace():
+ in_section = line.startswith(sections)
+ elif in_section and line.strip():
+ yield len(line) - len(line.lstrip(" ")), line.strip()
+
+
+def _resolved_keys(lines: list[str]) -> set[str]:
+ """Every version key the lockfile defines, from both resolution sections.
+
+ A tarball dependency lands in `packages:` with no `snapshots:` entry, so
+ reading one section alone reports live dependencies as missing.
+ """
+ return {
+ key
+ for indent, stripped in _section_lines(lines, "snapshots:", "packages:")
+ if indent == 2 and (key := _key_before_colon(stripped))
+ }
+
+
+def _importer_dependencies(lines: list[str]) -> Iterator[_ImporterDependency]:
+ """Every dependency the importer blocks declare."""
+ in_block = False
+ package = ""
+ for indent, stripped in _section_lines(lines, "importers:"):
+ if indent == 2:
+ in_block = False
+ elif indent == 4:
+ in_block = stripped in _DEPENDENCY_BLOCKS
+ elif indent == 6 and in_block:
+ package = _key_before_colon(stripped) or ""
+ elif indent == 8 and in_block and stripped.startswith("version:"):
+ version = _unquote(stripped[len("version:") :].strip())
+ if package and version and not version.startswith(_NON_REGISTRY_PREFIXES):
+ yield _ImporterDependency(package=package, version=version)
+
+
+def missing_resolutions(lockfile: str) -> list[str]:
+ """Versions an importer resolves to that the lockfile does not define.
+
+ Empty for any lockfile pnpm would accept, and empty for a lockfile whose
+ layout this parser does not recognize, because a guess either way is worse
+ than staying quiet. A non-empty result names the keys `--frozen-lockfile`
+ reports, and needs no install to compute.
+ """
+ if not _is_supported_layout(lockfile):
+ return []
+ lines = lockfile.splitlines()
+ keys = _resolved_keys(lines)
+ missing = set()
+ for dependency in _importer_dependencies(lines):
+ key = f"{dependency.package}@{dependency.version}"
+ # An aliased dependency ("npm:@scope/[email protected]") carries the full spec
+ # in its version, so that string is the key rather than name@version.
+ if key not in keys and dependency.version not in keys:
+ missing.add(key)
+ return sorted(missing)
diff --git a/tools/hogli-commands/hogli_commands/tests/test_ci_preflight.py b/tools/hogli-commands/hogli_commands/tests/test_ci_preflight.py
index 23ce7626d2ab..909ade7d5545 100644
--- a/tools/hogli-commands/hogli_commands/tests/test_ci_preflight.py
+++ b/tools/hogli-commands/hogli_commands/tests/test_ci_preflight.py
@@ -234,7 +234,7 @@ class TestStalenessRisks:
conflicts: list[str] | None,
expected_fragments: list[str],
) -> None:
- risks = _staleness_risks(branch_files, master_files, conflicts)
+ risks = _staleness_risks(branch_files, master_files, conflicts, [])
assert len(risks) == len(expected_fragments)
for fragment, risk in zip(expected_fragments, risks):
assert fragment in risk
diff --git a/tools/hogli-commands/hogli_commands/tests/test_lockfile_merge.py b/tools/hogli-commands/hogli_commands/tests/test_lockfile_merge.py
new file mode 100644
index 000000000000..873b46740111
--- /dev/null
+++ b/tools/hogli-commands/hogli_commands/tests/test_lockfile_merge.py
@@ -0,0 +1,100 @@
+from __future__ import annotations
+
+import pytest
+
+from hogli.manifest import REPO_ROOT
+from hogli_commands.lockfile_merge import _is_supported_layout, missing_resolutions
+
+LOCKFILE_HEAD = """lockfileVersion: {version}
+
+importers:
+
+ .:
+ dependencies:
+"""
+
+
+def _lockfile(importer_deps: str, packages: str = "", snapshots: str = "", version: str = "'9.0'") -> str:
+ head = LOCKFILE_HEAD.format(version=version)
+ return f"{head}{importer_deps}\npackages:\n\n{packages}\nsnapshots:\n\n{snapshots}"
+
+
+class TestLockfileMerge:
+ """A clean git merge of two valid lockfiles can produce an invalid one. These
+ lock the shapes that made the first parser report live dependencies as broken,
+ because a false positive here warns on every push."""
+
+ @pytest.mark.parametrize(
+ "importer_deps,packages,snapshots,version,expected",
+ [
+ pytest.param(
+ " posthog-js:\n specifier: 'catalog:'\n version: 1.433.6([email protected])\n",
+ "",
+ "'9.0'",
+ id="version-master-replaced-is-reported",
+ ),
+ pytest.param(
+ " posthog-js:\n specifier: 'catalog:'\n version: 1.433.9([email protected])\n",
+ "",
+ "'9.0'",
+ [],
+ id="peer-suffixed-version-resolves",
+ ),
+ pytest.param(
+ " '@posthog/mcp-analytics':\n specifier: 'catalog:'\n version: '@posthog/[email protected]'\n",
+ "",
+ " '@posthog/[email protected]': {}\n",
+ "'9.0'",
+ [],
+ id="aliased-dependency-resolves-by-version-alone",
+ ),
+ pytest.param(
+ " uWebSockets.js:\n specifier: https://example.com/a.tar.gz\n version: https://example.com/a.tar.gz\n",
+ " uWebSockets.js@https://example.com/a.tar.gz:\n resolution: {tarball: https://example.com/a.tar.gz}\n",
+ "",
+ "'9.0'",
+ [],
+ id="tarball-url-key-containing-a-colon-resolves",
+ ),
+ pytest.param(
+ " local-thing:\n specifier: workspace:*\n version: link:../local-thing\n",
+ "",
+ "",
+ "'9.0'",
+ [],
+ id="workspace-link-needs-no-resolution",
+ ),
+ pytest.param(
+ " posthog-js:\n specifier: 'catalog:'\n version: 1.433.9\n",
+ "",
+ "",
+ "'9.0'",
+ id="a-lockfile-that-resolves-nothing-is-broken-not-clean",
+ ),
+ pytest.param(
+ " posthog-js:\n specifier: 'catalog:'\n version: 1.433.9\n",
+ "",
+ "",
+ "'10.0'",
+ [],
+ id="an-unknown-layout-is-not-this-parsers-to-judge",
+ ),
+ ],
+ )
+ def test_detects_only_genuinely_unresolved_dependencies(
+ self, importer_deps: str, packages: str, snapshots: str, version: str, expected: list[str]
+ ) -> None:
+ assert missing_resolutions(_lockfile(importer_deps, packages, snapshots, version)) == expected
+
+ def test_the_repos_own_lockfile_is_clean(self) -> None:
+ # A parser regression that reports a false positive here would warn on
+ # every push, so this guards the checked-in lockfile rather than a fixture.
+ lockfile = (REPO_ROOT / "pnpm-lock.yaml").read_text()
+ # Asserted first: an unsupported layout makes the line below pass while
+ # the check does nothing, so a pnpm major bump must fail here instead.
+ assert _is_supported_layout(lockfile)
+ assert missing_resolutions(lockfile) == []