Skip to content

The agent that grows with you

fix(pm): flush a generation tree before its selection record names it

ethernet97b0ab42e899
diff --git a/pm/environments.py b/pm/environments.py
index 6095b238fa3..a7af2aab27e 100644
--- a/pm/environments.py
+++ b/pm/environments.py
@@ -121,11 +121,36 @@ def store_root(project_root: Path) -> Path:
return get_default_hermes_root() / "tools"
+def flush_before_selecting() -> None:
+ """Make a finished generation tree durable before a selection record names it.
+
+ The selection record (the install's facts.json, a side environment's
+ active.json) is written last, atomically and fsynced, so it doubles as the
+ generation's completion marker -- but only if every file it vouches for
+ reached the disk first. Otherwise a power loss can persist the record while
+ the tree's data is still in the page cache, selecting a half-written venv.
+ One filesystem-wide sync instead of an fsync per file: a venv holds tens of
+ thousands of files, and per-file flushes cost minutes on slow disks.
+
+ Windows has no whole-filesystem flush reachable from Python (os.sync does
+ not exist there), and FlushFileBuffers per file is the slow path rejected
+ above. There the record's atomic write is the only guarantee: it is never
+ torn, but NTFS journals metadata, not file contents, so power loss right
+ after a publish can still leave the selected tree with incomplete files.
+ """
+ sync = getattr(os, "sync", None)
+ if sync is not None:
+ sync()
+
+
def selected_venv(project_root: Path) -> Path:
"""Use the committed environment, or the original install before first sync.
A broken committed selection is an error, not permission to load an older
dependency set silently. Reading this function never creates user state.
+ The record itself is the completion marker: it is only written after
+ ``flush_before_selecting``, so the ``pyvenv.cfg`` probe below is a sanity
+ check against a vanished tree, not the durability guarantee.
"""
path = runtime_facts_path(project_root)
try:
diff --git a/pm/install.py b/pm/install.py
index bb515252577..a797e43a16c 100644
--- a/pm/install.py
+++ b/pm/install.py
@@ -654,6 +654,9 @@ def sync_venv(extras: Optional[list[str]] = None, *, explicit: bool = False, plu
if change is not None:
change.publish(paths.repo_root())
if not current:
+ if result.get("environment") is not None:
+ from pm.environments import flush_before_selecting
+ flush_before_selecting()
facts.record_state("venv", stamp, enabled, **result)
if change is not None:
finish_publication(paths.repo_root())
diff --git a/pm/operations.py b/pm/operations.py
index 85130287864..4dbdbf20680 100644
--- a/pm/operations.py
+++ b/pm/operations.py
@@ -309,6 +309,8 @@ def _ensure_generation(
python = build(generation, base_python)
if executable is not None and _tool(python, executable) is None:
raise InstallError(name, f"installed requirements do not provide {executable!r}")
+ from pm.environments import flush_before_selecting
+ flush_before_selecting()
_write(root / "active.json", {"generation": generation.name,
"inputs": identity(base_python), **record})
except BaseException:
diff --git a/tests/pm/test_generation_durability.py b/tests/pm/test_generation_durability.py
new file mode 100644
index 00000000000..559f4ccad11
--- /dev/null
+++ b/tests/pm/test_generation_durability.py
@@ -0,0 +1,74 @@
+"""A generation's selection record is its completion marker, so it may only be
+written after the finished tree has been flushed to disk. Otherwise a power loss
+mid-publish can persist the (fsynced) record while the venv's files are still in
+the page cache, and the next boot selects a half-written environment.
+"""
+from __future__ import annotations
+
+import os
+
+
+def _flush_probe(monkeypatch, observe):
+ """Replace the filesystem-wide flush with one that records what was on disk
+ when it ran; ``raising=False`` so the contract is exercised on Windows too."""
+ seen: list = []
+ monkeypatch.setattr(os, "sync", lambda: seen.append(observe()), raising=False)
+ return seen
+
+
+def test_install_selection_is_committed_only_after_its_tree_is_flushed(tmp_path, monkeypatch):
+ import pm.install as install
+ from pm import paths
+ from pm.environments import install_state_dir, runtime_facts_path, selected_venv
+
+ store = tmp_path / "tools"
+ store.mkdir()
+ monkeypatch.setattr("pm.paths.store_root", lambda: store)
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ monkeypatch.setattr(paths, "repo_root", lambda: repo)
+ venv = install.get_package("venv")
+ monkeypatch.setattr(venv, "expected_stamp", lambda extras, **kwargs: "stamp")
+ candidate = install_state_dir(repo) / "environments" / "fresh" / "venv"
+
+ def apply(*args, **kwargs):
+ candidate.mkdir(parents=True)
+ (candidate / "pyvenv.cfg").write_text("home = fixture\n", encoding="utf-8")
+ return {"environment": candidate}
+
+ monkeypatch.setattr(venv, "apply", apply)
+
+ def committed() -> bool:
+ return runtime_facts_path(repo).is_file() and selected_venv(repo) == candidate.resolve()
+
+ flushes = _flush_probe(monkeypatch, lambda: (candidate / "pyvenv.cfg").is_file() and not committed())
+ install.sync_venv([], explicit=True)
+
+ assert flushes == [True], "the tree must be flushed after it is complete and before it is selected"
+ assert selected_venv(repo) == candidate.resolve()
+
+
+def test_side_environment_selection_is_committed_only_after_its_tree_is_flushed(tmp_path, monkeypatch):
+ from pm import _uv, operations
+
+ base = tmp_path / "base" / "python"
+ base.parent.mkdir()
+ base.touch()
+ monkeypatch.setattr(_uv, "_toolchain", lambda **kwargs: (None, base))
+ root = tmp_path / "side"
+ built: list = []
+
+ def build(generation, base_python):
+ environment = generation / "venv"
+ python = operations._python(environment)
+ python.parent.mkdir(parents=True)
+ python.touch()
+ (environment / "pyvenv.cfg").write_text("home = fixture\n", encoding="utf-8")
+ built.append(environment)
+ return python
+
+ flushes = _flush_probe(monkeypatch, lambda: bool(built) and not (root / "active.json").exists())
+ python = operations._ensure_generation("proof", root, {}, build, record={}, explicit=True)
+
+ assert flushes == [True], "the tree must be flushed after it is complete and before it is selected"
+ assert operations.environment_python("proof", root=root) == python