Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

perf(regression): stop rebuilding what an update did not change (#1594)

Call White51adb70a0ac7
diff --git a/core/show_runtime.py b/core/show_runtime.py
index 1ba647efc..f0c93ed27 100644
--- a/core/show_runtime.py
+++ b/core/show_runtime.py
@@ -2226,8 +2226,25 @@ class ShowRuntimeManager:
else:
if not self._run_install_command([*git, "-C", str(source_dir), "fetch", "--depth", "1", "origin", self.github_ref]):
return self._reuse_existing_github_runtime(existing_command)
+ fetched = self._git_revision(git, source_dir, "FETCH_HEAD")
+ if (
+ not self.force_install
+ and existing_command
+ and fetched
+ and self._read_github_build_marker(source_dir) == fetched
+ ):
+ # The runtime already on disk was built from exactly this
+ # commit, so `npm ci` and `npm run build` would spend a minute
+ # reproducing it byte for byte.
+ self._install_reason = None
+ return existing_command
if not self._run_install_command([*git, "-C", str(source_dir), "checkout", "FETCH_HEAD"]):
return self._reuse_existing_github_runtime(existing_command)
+ # From here on the artifact the marker describes is being replaced:
+ # ``npm ci`` empties node_modules and the build writes into dist. Drop
+ # the marker first so a failure anywhere below leaves "unknown" rather
+ # than a commit that no longer describes what is on disk.
+ self._write_github_build_marker(source_dir, None)
if not self._run_install_command([*npm, "ci"], cwd=source_dir):
return self._reuse_existing_github_runtime(existing_command)
if not self._run_install_command([*npm, "run", "build"], cwd=source_dir):
@@ -2236,8 +2253,54 @@ class ShowRuntimeManager:
if not command:
self._install_reason = "runtime_install_missing_bin"
return None
+ self._write_github_build_marker(source_dir, self._git_revision(git, source_dir, "HEAD"))
return command
+ def _github_build_marker_path(self, source_dir: Path) -> Path:
+ return source_dir / ".avibe-runtime-build"
+
+ def _read_github_build_marker(self, source_dir: Path) -> str | None:
+ """The commit that produced the runtime build currently on disk.
+
+ The marker describes the artifact that exists now, not whatever the
+ working tree happens to be checked out at. Both halves of that are
+ enforced by when it moves: it is cleared before a rebuild starts
+ replacing the artifact, and written again only once the build finished
+ and its entry point resolved. So a failed, interrupted, or partial
+ rebuild leaves no marker, and the next prepare rebuilds.
+ """
+ try:
+ revision = self._github_build_marker_path(source_dir).read_text(encoding="utf-8").strip()
+ except OSError:
+ return None
+ return revision or None
+
+ def _write_github_build_marker(self, source_dir: Path, revision: str | None) -> None:
+ marker = self._github_build_marker_path(source_dir)
+ try:
+ if revision:
+ marker.write_text(f"{revision}\n", encoding="utf-8")
+ else:
+ marker.unlink(missing_ok=True)
+ except OSError:
+ pass
+
+ def _git_revision(self, git: list[str], source_dir: Path, ref: str) -> str | None:
+ try:
+ result = subprocess.run(
+ [*git, "-C", str(source_dir), "rev-parse", ref],
+ capture_output=True,
+ text=True,
+ timeout=30,
+ check=False,
+ **isolated_subprocess_kwargs(),
+ )
+ except (OSError, subprocess.SubprocessError):
+ return None
+ if result.returncode != 0:
+ return None
+ return result.stdout.strip() or None
+
def _github_runtime_command(self, source_dir: Path, node: list[str]) -> list[str] | None:
cli_path = source_dir / "packages" / "runtime" / "dist" / "cli.js"
if not cli_path.exists():
diff --git a/scripts/incus_regression.py b/scripts/incus_regression.py
index 78eb0a2ea..359272631 100644
--- a/scripts/incus_regression.py
+++ b/scripts/incus_regression.py
@@ -26,7 +26,7 @@ from contextlib import contextmanager
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
-from typing import Sequence
+from typing import Container, Iterator, Sequence
try:
import fcntl
@@ -51,6 +51,10 @@ METADATA_DIR = "/var/lib/avibe-regression"
METADATA_PATH = f"{METADATA_DIR}/metadata.json"
FINGERPRINT_PATH = f"{METADATA_DIR}/fingerprints.json"
SERVICE_NAME = "avibe-regression.service"
+# Directories under ``ui/`` that a build produces or installs, as opposed to
+# reads. They are excluded from the UI source fingerprint and are the ones a
+# sync keeps in place so an unchanged front end never pays for ``npm ci``.
+UI_NON_SOURCE_DIRS = ("node_modules", "dist", ".vite")
INTERNAL_DISPATCH_SOCKET = "/tmp/vibe_remote/dispatch.sock"
DEFAULT_IMAGE = "avibe-regression-base-current"
DEFAULT_BASE_SOURCE_IMAGE = "images:ubuntu/24.04/cloud"
@@ -761,6 +765,13 @@ def root_exec(target: RegressionTarget, command: str, *, remote: str | None = No
def source_excludes(*, include_ui_dist: bool = False) -> tuple[str, ...]:
+ """Path patterns dropped from the deployed source tree.
+
+ A bare pattern matches that name at any depth. A pattern with a leading
+ ``/`` is anchored at the repository root, which is what keeps ``/dist``
+ (the Python build output) from also swallowing ``ui/dist``, whose fate
+ belongs to ``include_ui_dist``.
+ """
excludes = [
".git",
".runtime",
@@ -776,6 +787,7 @@ def source_excludes(*, include_ui_dist: bool = False) -> tuple[str, ...]:
"_tmp",
"tmp",
"logs",
+ "/dist",
]
if not include_ui_dist:
excludes.append("ui/dist")
@@ -791,6 +803,11 @@ def should_exclude(relative: str, *, include_ui_dist: bool = False) -> bool:
return True
parts = relative.split("/")
for pattern in source_excludes(include_ui_dist=include_ui_dist):
+ if pattern.startswith("/"):
+ anchored = pattern[1:]
+ if relative == anchored or relative.startswith(anchored + "/"):
+ return True
+ continue
pattern_parts = pattern.split("/")
if relative == pattern or relative.startswith(pattern + "/"):
return True
@@ -799,13 +816,43 @@ def should_exclude(relative: str, *, include_ui_dist: bool = False) -> bool:
return False
+def is_virtualenv_dir(path: Path) -> bool:
+ """Whether ``path`` is a Python virtualenv root, whatever it is named.
+
+ ``pyvenv.cfg`` is the marker the interpreter itself writes, so this covers
+ ``venv``, ``.venv``, ``env`` and anything else a contributor happens to
+ use. Naming them one by one is how a 600 MB tree of host-native binaries
+ ends up shipped into a Linux container.
+ """
+ return (path / "pyvenv.cfg").is_file()
+
+
+def iter_source_entries(repo_root: Path, *, include_ui_dist: bool = False) -> Iterator[tuple[Path, str]]:
+ """Yield ``(path, arcname)`` for everything that belongs in the source tar.
+
+ Excluded directories are pruned during the walk rather than filtered after
+ it: ``node_modules`` and a virtualenv together hold well over a hundred
+ thousand paths that would otherwise be stat'ed just to be discarded.
+ """
+ def walk(current: Path) -> Iterator[tuple[Path, str]]:
+ for entry in sorted(current.iterdir()):
+ relative = entry.relative_to(repo_root).as_posix()
+ if should_exclude(relative, include_ui_dist=include_ui_dist):
+ continue
+ is_dir = entry.is_dir() and not entry.is_symlink()
+ if is_dir and is_virtualenv_dir(entry):
+ continue
+ yield entry, relative
+ if is_dir:
+ yield from walk(entry)
+
+ yield from walk(repo_root)
+
+
def build_source_tar(repo_root: Path, *, include_ui_dist: bool = False) -> bytes:
with tempfile.TemporaryFile() as fh:
with tarfile.open(fileobj=fh, mode="w") as tar:
- for path in sorted(repo_root.rglob("*")):
- relative = path.relative_to(repo_root).as_posix()
- if should_exclude(relative, include_ui_dist=include_ui_dist):
- continue
+ for path, relative in iter_source_entries(repo_root, include_ui_dist=include_ui_dist):
tar.add(path, arcname=relative, recursive=False)
fh.seek(0)
return fh.read()
@@ -820,8 +867,36 @@ def sync_source(
clean: bool,
include_ui_dist: bool = False,
) -> None:
- runner.run(root_exec(target, f"mkdir -p {shlex.quote(SOURCE_DIR)} && find {shlex.quote(SOURCE_DIR)} -mindepth 1 -maxdepth 1 -exec rm -rf {{}} +", remote=remote))
- runner.run(root_exec(target, f"mkdir -p {shlex.quote(SOURCE_DIR)} && chown -R {SERVICE_USER}:{SERVICE_USER} /opt/avibe", remote=remote))
+ quoted_source = shlex.quote(SOURCE_DIR)
+ if clean:
+ wipe = f"find {quoted_source} -mindepth 1 -maxdepth 1 -exec rm -rf {{}} +"
+ else:
+ # Everything stale still goes, but the UI dependency tree and its build
+ # output stay: they are the ~470 MB that a full wipe forces ``npm ci``
+ # and ``npm run build`` to recreate on every update whether or not the
+ # front end changed. Whether they are still valid is a fingerprint
+ # question, answered in update_dependencies_and_build.
+ #
+ # Preservation covers only what the archive does not carry. ``tar``
+ # extracts over what is already there and never deletes, so keeping a
+ # directory the host also ships would leave the files the host deleted
+ # -- a stable-name public asset, a manifest -- served alongside the new
+ # bundle. Whatever the archive supplies has to end up equal to the
+ # host's copy, which means the old one goes first. Which of these the
+ # archive supplies is read off the exclusion table rather than restated
+ # here, so the two cannot drift.
+ quoted_ui = shlex.quote(f"{SOURCE_DIR}/ui")
+ keep = " ".join(
+ f"! -name {shlex.quote(name)}"
+ for name in UI_NON_SOURCE_DIRS
+ if should_exclude(f"ui/{name}", include_ui_dist=include_ui_dist)
+ )
+ wipe = (
+ f"find {quoted_source} -mindepth 1 -maxdepth 1 ! -name ui -exec rm -rf {{}} + && "
+ f"if [ -d {quoted_ui} ]; then find {quoted_ui} -mindepth 1 -maxdepth 1 {keep} -exec rm -rf {{}} +; fi"
+ )
+ runner.run(root_exec(target, f"mkdir -p {quoted_source} && {wipe}", remote=remote))
+ runner.run(root_exec(target, f"mkdir -p {quoted_source} && chown -R {SERVICE_USER}:{SERVICE_USER} /opt/avibe", remote=remote))
tar_bytes = b"" if runner.dry_run else build_source_tar(repo_root, include_ui_dist=include_ui_dist)
runner.run(
incus("exec", remote_ref(remote, target.instance), "--", "tar", "-C", SOURCE_DIR, "-xf", "-", project=target.project),
@@ -910,24 +985,15 @@ def file_hash(repo_root: Path, relative_paths: Sequence[str]) -> str:
def compute_fingerprints(repo_root: Path) -> dict:
- ui_source_parts = [
- tree_hash(repo_root / "ui" / "src"),
- tree_hash(repo_root / "ui" / "public"),
- file_hash(
- repo_root,
- [
- "ui/index.html",
- "ui/vite.config.ts",
- "ui/tsconfig.json",
- "ui/tsconfig.app.json",
- "ui/tsconfig.node.json",
- ],
- ),
- ]
+ # ``ui_source`` covers the files the UI build reads, rather than a list of
+ # the build inputs we happened to think of. The list form silently missed
+ # ``postcss.config.js``, ``eslint.config.js`` and ``ui/scripts/``; a build
+ # input added tomorrow is covered without anyone remembering to extend a
+ # literal, including the ones that live outside ``ui/``.
return {
"python": file_hash(repo_root, ["pyproject.toml", "uv.lock"]),
"ui_deps": file_hash(repo_root, ["ui/package.json", "ui/package-lock.json"]),
- "ui_source": "|".join(ui_source_parts),
+ "ui_source": ui_source_hash(repo_root),
"show_runtime": "|".join(
[
regression_env("SHOW_RUNTIME_SOURCE", "github-source"),
@@ -938,16 +1004,131 @@ def compute_fingerprints(repo_root: Path) -> dict:
}
-def tree_hash(root: Path) -> str:
+def tree_hash(root: Path, *, prune: Sequence[str] = ()) -> str:
+ """Content hash of every file under ``root``, skipping pruned directories.
+
+ ``prune`` names directories, at any depth, that hold build outputs or
+ installed dependencies rather than sources.
+ """
digest = hashlib.sha256()
if not root.exists():
return "<missing>"
- for path in sorted(p for p in root.rglob("*") if p.is_file()):
+ pruned = set(prune)
+ files: list[Path] = []
+ stack = [root]
+ while stack:
+ for entry in stack.pop().iterdir():
+ if entry.is_dir() and not entry.is_symlink():
+ if entry.name not in pruned:
+ stack.append(entry)
+ elif entry.is_file():
+ files.append(entry)
+ for path in sorted(files):
digest.update(path.relative_to(root).as_posix().encode("utf-8"))
digest.update(path.read_bytes())
return digest.hexdigest()
+def ui_external_build_inputs(repo_root: Path) -> list[str]:
+ """Repo-relative paths outside ``ui/`` that the UI bundle is built from.
+
+ ``ui_source`` licenses skipping ``npm run build``, so it has to cover the
+ files the build reads. ``ui/`` is where most of them live, not what they
+ are: ``ui/src/lib/messageTypes.ts`` imports the repo-root
+ ``vibe/message_types.json`` and Vite inlines it into the browser bundle, so
+ a commit touching only that catalog changes the artifact while leaving a
+ ``ui/``-only hash identical -- the backend would get the new message-type
+ policies and the front end would keep applying the old ones.
+
+ The repository already declares this set and already keeps the declaration
+ honest, so this reads it rather than deriving it a second way. The
+ ``ui-builder`` stage builds the UI from a context holding only ``ui/``, so
+ every escaping input needs its own ``COPY`` there, and
+ ``ui/scripts/validate-out-of-tree-imports.mjs`` -- part of ``npm run
+ build``, which CI runs on every pull request -- fails the build when those
+ ``COPY`` lines and the real imports disagree. An empty result is therefore a
+ real answer rather than a scan that broke: it means the stage declares
+ nothing outside ``ui/``.
+ """
+ stage = next(
+ (
+ block
+ for block in re.split(r"^FROM ", (repo_root / "Dockerfile").read_text(encoding="utf-8"), flags=re.MULTILINE)
+ if re.match(r"^\S+\s+AS\s+ui-builder\b", block, flags=re.IGNORECASE)
+ ),
+ None,
+ )
+ if stage is None:
+ # Failing here beats returning a smaller input set than the build has:
+ # a fingerprint missing an input reads back as "the UI is unchanged"
+ # and skips the rebuild for good.
+ raise RuntimeError("Dockerfile no longer declares a ui-builder stage, so the UI build inputs are unknown")
+ found = set()
+ for arguments in re.findall(r"^COPY\s+(.+)$", stage, flags=re.MULTILINE):
+ sources = [word for word in arguments.split()[:-1] if not word.startswith("--")]
+ found.update(source.rstrip("/") for source in sources if not source.startswith("ui/"))
+ return sorted(found)
+
+
+def ui_source_hash(repo_root: Path) -> str:
+ """The UI build's whole input set: the ``ui/`` tree plus what escapes it."""
+ digest = hashlib.sha256()
+ digest.update(tree_hash(repo_root / "ui", prune=UI_NON_SOURCE_DIRS).encode("utf-8"))
+ for relative in ui_external_build_inputs(repo_root):
+ path = repo_root / relative
+ digest.update(relative.encode("utf-8"))
+ digest.update((tree_hash(path) if path.is_dir() else file_hash(repo_root, [relative])).encode("utf-8"))
+ return digest.hexdigest()
+
+
+def reconciled_fingerprints(previous: dict, current: dict, reconciled: Container[str]) -> dict:
+ """The fingerprints to record: what the artifacts on disk were built from.
+
+ A recorded fingerprint is read back as "the artifact in the instance was
+ produced from this input", which is what licenses a later update to skip
+ rebuilding it. That is only the same thing as "this input was synced" when
+ the run actually rebuilt the artifact. ``--no-build-ui`` skips the UI
+ entirely, so recording the synced source there would claim a dependency
+ tree and a bundle the instance never installed or built.
+
+ A key the run did not reconcile therefore keeps whatever the last
+ reconciliation recorded, so the next update still sees the difference. A key
+ with no previous value stays absent, which also reads as "rebuild".
+ """
+ merged = {}
+ for key, value in current.items():
+ if key in reconciled:
+ merged[key] = value
+ elif key in previous:
+ merged[key] = previous[key]
+ return merged
+
+
+def invalidate_fingerprints(runner: Runner, target: RegressionTarget, *, remote: str | None) -> None:
+ """Drop the recorded fingerprints before anything starts rebuilding.
+
+ A recorded fingerprint claims "the artifact in the instance was produced
+ from this input". The moment a rebuild starts, that claim stops holding for
+ the artifact it names: ``npm ci`` empties ``ui/node_modules``, ``npm run
+ build`` writes into ``ui/dist``, ``pip install`` rewrites the venv. A run
+ that dies mid-build would otherwise leave the old claim on disk, and if the
+ next update syncs the same inputs again -- a rollback, or a rerun after
+ fixing the environment rather than the source -- that stale claim licenses
+ skipping the very rebuild that failed.
+
+ Recording nothing reads as "rebuild everything", which is the honest answer
+ while a build is in flight. ``write_metadata`` records the real
+ fingerprints once the artifacts exist.
+ """
+ runner.run(
+ root_exec(
+ target,
+ f"mkdir -p {METADATA_DIR} && cat > {FINGERPRINT_PATH} <<'EOF'\n{{}}\nEOF",
+ remote=remote,
+ )
+ )
+
+
def write_metadata(runner: Runner, target: RegressionTarget, repo_root: Path, fingerprints: dict, *, remote: str | None) -> None:
payload = {
"schema_version": 1,
@@ -1210,6 +1391,20 @@ def instance_ui_dist_exists(runner: Runner, target: RegressionTarget, *, remote:
return result.returncode == 0
+def instance_ui_node_modules_exists(runner: Runner, target: RegressionTarget, *, remote: str | None) -> bool:
+ """Whether the instance already has an npm-installed dependency tree.
+
+ ``.package-lock.json`` is the marker npm itself writes inside
+ ``node_modules`` once an install completes, so it distinguishes a finished
+ tree from a directory left behind by an interrupted one.
+ """
+ result = runner.run(
+ tenant_exec(target, "test -f ui/node_modules/.package-lock.json", remote=remote),
+ check=False,
+ )
+ return result.returncode == 0
+
+
def normalize_runtime_config(runner: Runner, target: RegressionTarget, *, remote: str | None) -> None:
config_path = f"{AVIBE_HOME}/config/config.json"
script = textwrap.dedent(f"""
@@ -1252,7 +1447,15 @@ def update_dependencies_and_build(
build_ui: bool,
force_ui: bool,
remote: str | None,
-) -> None:
+) -> set[str]:
+ """Bring the instance's artifacts up to date; report which ones it reconciled.
+
+ The return value feeds ``reconciled_fingerprints``. A key belongs in it when
+ the artifact on disk now corresponds to ``next_fingerprints[key]`` -- either
+ because this run rebuilt it, or because the run skipped the rebuild
+ precisely because the fingerprint already matched. A key is absent only when
+ the run never looked, which is what ``--no-build-ui`` does to the UI.
+ """
runner.run(root_exec(target, f"python3 -m venv {shlex.quote(VENV_DIR)} || true", remote=remote))
runner.run(root_exec(target, f"chown -R {SERVICE_USER}:{SERVICE_USER} {shlex.quote(VENV_DIR)}", remote=remote))
python_changed = (
@@ -1269,7 +1472,15 @@ def update_dependencies_and_build(
if needs_ui_dist and not build_ui:
print("UI dist missing in synced source; building UI before editable install.")
if should_build_ui:
- ui_deps_changed = force_ui or previous_fingerprints.get("ui_deps") != next_fingerprints.get("ui_deps") or not previous_fingerprints
+ # A sync keeps ui/node_modules, so "the fingerprint did not change" only
+ # licenses skipping npm ci when the tree it describes is actually there.
+ needs_node_modules = not instance_ui_node_modules_exists(runner, target, remote=remote)
+ ui_deps_changed = (
+ force_ui
+ or needs_node_modules
+ or previous_fingerprints.get("ui_deps") != next_fingerprints.get("ui_deps")
+ or not previous_fingerprints
+ )
if ui_deps_changed:
runner.run(tenant_exec(target, "cd ui && npm ci", remote=remote))
else:
@@ -1291,6 +1502,12 @@ def update_dependencies_and_build(
print("UI source fingerprint unchanged; skipping npm run build.")
if python_changed:
runner.run(tenant_exec(target, f"{VENV_DIR}/bin/pip install -e .", remote=remote))
+ # ``python`` is always reconciled: it either just installed, or it was
+ # skipped because the previous fingerprint already equalled this one.
+ reconciled = {"python"}
+ if should_build_ui:
+ reconciled |= {"ui_deps", "ui_source"}
+ return reconciled
def restart_and_verify(runner: Runner, target: RegressionTarget, *, remote: str | None) -> None:
@@ -1317,7 +1534,11 @@ def restart_and_verify(runner: Runner, target: RegressionTarget, *, remote: str
def prepare_show_runtime(runner: Runner, target: RegressionTarget, *, remote: str | None) -> None:
result = runner.run(tenant_exec(target, f"{VENV_DIR}/bin/vibe runtime prepare --strict", remote=remote), check=False)
if result.returncode != 0:
- runner.run(tenant_exec(target, "rm -rf ~/.avibe/runtime/show-runtime/source ~/.npm/_cacache", remote=remote))
+ # Retry from a fresh checkout. The npm cache is verified rather than
+ # deleted: it grows past a gigabyte, refilling it costs more than the
+ # rest of an update put together, and `npm cache verify` already
+ # discards exactly the corrupt entries that made deleting it tempting.
+ runner.run(tenant_exec(target, "rm -rf ~/.avibe/runtime/show-runtime/source && npm cache verify", remote=remote), check=False)
runner.run(tenant_exec(target, f"{VENV_DIR}/bin/vibe runtime prepare --strict", remote=remote))
runner.run(tenant_exec(target, f"{VENV_DIR}/bin/vibe runtime status --json", remote=remote))
@@ -1535,19 +1756,29 @@ def cmd_up(args: argparse.Namespace) -> int:
sync_source(runner, target, repo_root, remote=args.remote, clean=args.clean, include_ui_dist=args.no_build_ui)
fingerprints = compute_fingerprints(repo_root)
previous_fingerprints = read_existing_fingerprints(runner, target, remote=args.remote)
- update_dependencies_and_build(
+ invalidate_fingerprints(runner, target, remote=args.remote)
+ reconciled = update_dependencies_and_build(
runner,
target,
previous_fingerprints=previous_fingerprints,
next_fingerprints=fingerprints,
force_deps=args.force_deps,
build_ui=not args.no_build_ui,
- force_ui=True,
+ force_ui=args.force_ui,
remote=args.remote,
)
+ # ``prepare_show_runtime`` below is unconditional, so the run either
+ # reconciles the show runtime or fails outright.
+ reconciled = reconciled | {"show_runtime"}
run_prepare_state(runner, target, reset_mode=args.reset_mode, remote=args.remote)
normalize_runtime_config(runner, target, remote=args.remote)
- write_metadata(runner, target, repo_root, fingerprints, remote=args.remote)
+ write_metadata(
+ runner,
+ target,
+ repo_root,
+ reconciled_fingerprints(previous_fingerprints, fingerprints, reconciled),
+ remote=args.remote,
+ )
# Install updated runtime sources while the service is stopped so the
# restarted process cannot keep serving code loaded before preparation.
prepare_show_runtime(runner, target, remote=args.remote)
@@ -1721,9 +1952,10 @@ def build_parser() -> argparse.ArgumentParser:
action="store_true",
help="Allow reset-mode config/all to delete Avibe Cloud pairing state from the master regression environment.",
)
- up.add_argument("--clean", action="store_true", help="Remove stale files before source sync.")
+ up.add_argument("--clean", action="store_true", help="Wipe the synced source completely, including the UI dependency tree and build output a sync normally keeps.")
up.add_argument("--force-deps", action="store_true", help="Force Python dependency refresh.")
up.add_argument("--no-build-ui", action="store_true", help="Skip npm ci/build for UI assets.")
+ up.add_argument("--force-ui", action="store_true", help="Force npm ci and npm run build even when the UI fingerprint is unchanged.")
up.set_defaults(func=cmd_up)
for name, func in (
diff --git a/scripts/run_regression.sh b/scripts/run_regression.sh
index 7725e61de..e4b9b291c 100755
--- a/scripts/run_regression.sh
+++ b/scripts/run_regression.sh
@@ -77,7 +77,7 @@ while [ $# -gt 0 ]; do
incus_args+=(--remote "$2")
shift 2
;;
- --allow-reset-paired-master|--dry-run|--clean|--force-deps|--no-build-ui|--yes)
+ --allow-reset-paired-master|--dry-run|--clean|--force-deps|--no-build-ui|--force-ui|--yes)
incus_args+=("$1")
shift
;;
diff --git a/tests/test_incus_regression.py b/tests/test_incus_regression.py
index 9ea0239fe..050ef0799 100644
--- a/tests/test_incus_regression.py
+++ b/tests/test_incus_regression.py
@@ -8,6 +8,7 @@ import os
import subprocess
import sys
import tarfile
+from collections.abc import Sequence
from pathlib import Path
import pytest
@@ -556,6 +557,153 @@ def test_source_exclude_drops_runtime_and_dependency_dirs() -> None:
assert not incus_regression.should_exclude("vibe/ui_server.py")
+def test_root_build_output_is_excluded_without_capturing_ui_dist() -> None:
+ """``/dist`` is anchored so it cannot decide ``ui/dist``'s fate.
+
+ ``ui/dist`` is the front-end bundle that ``--no-build-ui`` ships on
+ purpose; the Python wheel output at the repository root never is.
+ """
+ assert incus_regression.should_exclude("dist/avibe-3.0.12.tar.gz")
+ assert incus_regression.should_exclude("dist")
+ assert not incus_regression.should_exclude("ui/dist/assets/app.js", include_ui_dist=True)
+ assert not incus_regression.should_exclude("vibe/dist_helpers.py")
+
+
+def test_source_tar_drops_a_virtualenv_whatever_it_is_named(tmp_path: Path) -> None:
+ """Virtualenvs are recognised by ``pyvenv.cfg``, not by a list of names.
+
+ They hold host-native binaries that are useless inside the container, and
+ the repository has carried both ``venv`` and ``.venv`` at the same time.
+ """
+ for name in ("venv", ".venv", "env", "tools/sandbox"):
+ root = tmp_path / name
+ (root / "lib").mkdir(parents=True)
+ (root / "pyvenv.cfg").write_text("home = /usr\n", encoding="utf-8")
+ (root / "lib" / "libpython.dylib").write_text("mach-o\n", encoding="utf-8")
+ (tmp_path / "vibe").mkdir()
+ (tmp_path / "vibe" / "cli.py").write_text("print('ok')\n", encoding="utf-8")
+
+ with tarfile.open(fileobj=io.BytesIO(incus_regression.build_source_tar(tmp_path))) as tar:
+ names = set(tar.getnames())
+
+ assert "vibe/cli.py" in names
+ assert not [name for name in names if "pyvenv.cfg" in name or "libpython" in name]
+
+
+def test_source_tar_keeps_a_plain_directory_that_merely_looks_like_a_virtualenv(tmp_path: Path) -> None:
+ (tmp_path / "env").mkdir()
+ (tmp_path / "env" / "settings.py").write_text("DEBUG = False\n", encoding="utf-8")
+
+ with tarfile.open(fileobj=io.BytesIO(incus_regression.build_source_tar(tmp_path))) as tar:
+ assert "env/settings.py" in tar.getnames()
+
+
+def write_ui_builder_stage(root: Path, *, external: Sequence[str] = ()) -> None:
+ """Give a fixture repo root the Dockerfile stage the UI fingerprint reads.
+
+ ``compute_fingerprints`` takes the build inputs living outside ``ui/`` from
+ the ``ui-builder`` stage's ``COPY`` lines, so a fixture without that stage is
+ not a checkout the runner could be pointed at.
+ """
+ copies = "".join(f"COPY {relative} /app/{relative}\n" for relative in external)
+ (root / "Dockerfile").write_text(
+ "FROM node:20-slim AS ui-builder\n"
+ "WORKDIR /app/ui\n"
+ "COPY ui/package.json ui/package-lock.json ./\n"
+ f"{copies}"
+ "COPY ui/ .\n"
+ "RUN npm run build\n"
+ "\nFROM python:3.12-slim AS base\n"
+ "COPY pyproject.toml /app/pyproject.toml\n",
+ encoding="utf-8",
+ )
+
+
+def test_ui_source_fingerprint_covers_every_ui_input_and_no_output(tmp_path: Path) -> None:
+ """State the property: sources count, outputs and dependencies do not.
+
+ Listing the config files that matter is how ``postcss.config.js`` and
+ ``ui/scripts/`` were left out, which lets an unchanged fingerprint ship a
+ stale bundle now that the UI is no longer rebuilt unconditionally.
+ """
+ write_ui_builder_stage(tmp_path)
+ ui = tmp_path / "ui"
+ (ui / "src").mkdir(parents=True)
+ (ui / "src" / "main.tsx").write_text("export {}\n", encoding="utf-8")
+ baseline = incus_regression.compute_fingerprints(tmp_path)["ui_source"]
+
+ for relative in ("postcss.config.js", "eslint.config.js", "agentation.d.ts", "scripts/build.mjs"):
+ path = ui / relative
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text("// one\n", encoding="utf-8")
+ added = incus_regression.compute_fingerprints(tmp_path)["ui_source"]
+ assert added != baseline, f"{relative} is a build input but is outside the fingerprint"
+ baseline = added
+
+ for produced in incus_regression.UI_NON_SOURCE_DIRS:
+ (ui / produced).mkdir(parents=True, exist_ok=True)
+ (ui / produced / "generated").write_text("noise\n", encoding="utf-8")
+ assert incus_regression.compute_fingerprints(tmp_path)["ui_source"] == baseline
+
+
+def test_ui_fingerprint_covers_the_build_inputs_that_live_outside_ui(tmp_path: Path) -> None:
+ """The UI build's input set is the files it reads, not the directory they sit in.
+
+ ``ui/src/lib/messageTypes.ts`` imports the repository-root message-type
+ catalog and Vite inlines it into the browser bundle, so a commit touching
+ only that catalog changes the artifact. A ``ui/``-only hash reads identical
+ and skips the rebuild, leaving the environment with a backend on the new
+ message-type policy and a front end still applying the old one.
+ """
+ (tmp_path / "ui" / "src").mkdir(parents=True)
+ (tmp_path / "ui" / "src" / "messageTypes.ts").write_text(
+ "import catalog from '../../vibe/message_types.json';\n",
+ encoding="utf-8",
+ )
+ catalog = tmp_path / "vibe" / "message_types.json"
+ catalog.parent.mkdir(parents=True)
+ catalog.write_text('{"version": 1}\n', encoding="utf-8")
+ write_ui_builder_stage(tmp_path, external=["vibe/message_types.json"])
+
+ before = incus_regression.compute_fingerprints(tmp_path)["ui_source"]
+ catalog.write_text('{"version": 2}\n', encoding="utf-8")
+
+ assert incus_regression.compute_fingerprints(tmp_path)["ui_source"] != before
+
+
+def test_this_checkout_declares_the_message_type_catalog_as_a_ui_build_input() -> None:
+ """The fixture above proves the mechanism; this proves the answer is real.
+
+ Read against this repository rather than a synthetic tree, so the one import
+ that actually escapes ``ui/`` today has to be in the set.
+ """
+ repo_root = Path(incus_regression.__file__).resolve().parent.parent
+
+ assert "vibe/message_types.json" in incus_regression.ui_external_build_inputs(repo_root)
+
+
+def test_declaring_nothing_outside_ui_is_an_answer_but_an_unreadable_stage_is_not(tmp_path: Path) -> None:
+ """An empty set is a real answer here, and a missing declaration must not be.
+
+ The escaping inputs are read from a declaration the repository maintains --
+ the ``ui-builder`` stage builds from a context holding only ``ui/``, and
+ ``npm run build`` fails when its ``COPY`` lines and the real imports
+ disagree -- so "the stage declares nothing outside ``ui/``" is a state that
+ can legitimately hold. A Dockerfile that no longer has the stage is
+ different in kind: answering "nothing" there would narrow the input set to a
+ hash that keeps matching, and the UI would never be rebuilt again.
+ """
+ write_ui_builder_stage(tmp_path)
+ assert incus_regression.ui_external_build_inputs(tmp_path) == []
+
+ (tmp_path / "Dockerfile").write_text(
+ "FROM python:3.12-slim AS base\nCOPY pyproject.toml /app/pyproject.toml\n",
+ encoding="utf-8",
+ )
+ with pytest.raises(RuntimeError):
+ incus_regression.ui_external_build_inputs(tmp_path)
+
+
def test_source_tar_excludes_regression_secret_file(tmp_path: Path) -> None:
(tmp_path / ".env.regression").write_text("OPENAI_API_KEY=secret\n", encoding="utf-8")
(tmp_path / "vibe").mkdir()
@@ -625,10 +773,122 @@ def test_sync_source_clears_stale_files_even_without_clean(tmp_path: Path) -> No
incus_regression.sync_source(RecordingRunner(), target, tmp_path, remote=None, clean=False)
joined = "\n".join(" ".join(command) for command in commands)
- assert f"find {incus_regression.SOURCE_DIR} -mindepth 1 -maxdepth 1 -exec rm -rf" in joined
+ assert f"find {incus_regression.SOURCE_DIR} -mindepth 1 -maxdepth 1 ! -name ui -exec rm -rf" in joined
+ assert f"find {incus_regression.SOURCE_DIR}/ui -mindepth 1 -maxdepth 1 " in joined
+ for kept in incus_regression.UI_NON_SOURCE_DIRS:
+ assert f"! -name {kept}" in joined
+
+
+def test_sync_source_without_clean_keeps_every_ui_non_source_dir(tmp_path: Path) -> None:
+ """A sync must leave ui/node_modules and ui/dist for the fingerprints to judge.
+
+ Deleting them makes ``npm ci`` and ``npm run build`` unconditional, which is
+ the single largest cost of an update whose front end did not change.
+ """
+ script = run_sync_wipe(tmp_path, clean=False)
+
+ assert sorted(p.name for p in (tmp_path / "ui").iterdir()) == sorted(incus_regression.UI_NON_SOURCE_DIRS)
+ assert not (tmp_path / "stale.py").exists()
+ assert not (tmp_path / "stale-dir").exists()
+ assert not (tmp_path / "ui" / "src").exists()
+ assert script # the wipe really ran rather than silently matching nothing
+
+
+def test_sync_source_with_clean_wipes_the_ui_dirs_too(tmp_path: Path) -> None:
+ run_sync_wipe(tmp_path, clean=True)
+
+ assert list(tmp_path.iterdir()) == []
+
+
[email protected]("include_ui_dist", [False, True])
+def test_a_sync_only_preserves_what_its_own_archive_does_not_ship(tmp_path: Path, include_ui_dist: bool) -> None:
+ """Preservation is for what the sync does not carry; equality is for what it does.
+
+ ``tar`` extracts over what is already there and never deletes, so preserving
+ a directory the archive also ships leaves whatever the host deleted -- a
+ renamed chunk, a dropped public asset -- served next to the new bundle. Both
+ sides are read out of the real code: the shipped set from the archive the
+ same call would send, the preserved set from the wipe command it emits. A
+ change to either one alone breaks this.
+ """
+ seed_source_tree(tmp_path)
+ with tarfile.open(
+ fileobj=io.BytesIO(incus_regression.build_source_tar(tmp_path, include_ui_dist=include_ui_dist))
+ ) as tar:
+ shipped = {name for name in incus_regression.UI_NON_SOURCE_DIRS if f"ui/{name}" in tar.getnames()}
+
+ script = run_sync_wipe(tmp_path, clean=False, include_ui_dist=include_ui_dist)
+ preserved = {name for name in incus_regression.UI_NON_SOURCE_DIRS if f"! -name {name}" in script}
+
+ assert preserved == set(incus_regression.UI_NON_SOURCE_DIRS) - shipped
+ assert shipped or not include_ui_dist # the archive really carries ui/dist in that mode
+ for name in shipped:
+ assert not (tmp_path / "ui" / name).exists(), f"ui/{name} survived a sync that overwrites it"
+ for name in preserved:
+ assert (tmp_path / "ui" / name / "marker").exists(), f"ui/{name} was wiped for the build to recreate"
+
+
+def seed_source_tree(source_root: Path) -> None:
+ """A deployed source tree holding stale files, sources, and the UI's non-source dirs."""
+ for relative in ("stale.py", "stale-dir/old.txt", "ui/src/App.tsx"):
+ path = source_root / relative
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text("x", encoding="utf-8")
+ for name in incus_regression.UI_NON_SOURCE_DIRS:
+ (source_root / "ui" / name).mkdir(parents=True, exist_ok=True)
+ (source_root / "ui" / name / "marker").write_text("x", encoding="utf-8")
+
+
+def run_sync_wipe(source_root: Path, *, clean: bool, include_ui_dist: bool = False) -> str:
+ """Run sync_source's wipe command against a real directory tree.
+
+ The wipe is a shell one-liner, so asserting on its text only proves we
+ wrote what we meant to write. Executing it against a populated tree is what
+ proves it deletes the stale files and keeps the expensive ones.
+ """
+ seed_source_tree(source_root)
+
+ commands: list[list[str]] = []
+
+ class RecordingRunner:
+ dry_run = True
+
+ def run(self, command, **kwargs):
+ commands.append(command)
+ return subprocess.CompletedProcess(command, 0)
+
+ target = incus_regression.RegressionTarget(
+ target="master",
+ slug="master",
+ project="avr-master",
+ instance="avibe-master",
+ host_port=15130,
+ ui_host="127.0.0.1",
+ ui_port=5123,
+ )
+ incus_regression.sync_source(
+ RecordingRunner(),
+ target,
+ source_root,
+ remote=None,
+ clean=clean,
+ include_ui_dist=include_ui_dist,
+ )
+
+ script = next(
+ command[-1]
+ for command in commands
+ if command[-1].startswith("mkdir -p") and "-exec rm -rf" in command[-1]
+ )
+ subprocess.run(
+ ["bash", "-lc", script.replace(incus_regression.SOURCE_DIR, str(source_root))],
+ check=True,
+ )
+ return script
def test_ui_public_assets_are_part_of_source_fingerprint(tmp_path: Path) -> None:
+ write_ui_builder_stage(tmp_path)
(tmp_path / "ui" / "src").mkdir(parents=True)
(tmp_path / "ui" / "public").mkdir(parents=True)
(tmp_path / "ui" / "public" / "push-sw.js").write_text("one\n", encoding="utf-8")
@@ -644,6 +904,7 @@ def test_legacy_voice_realtime_build_flag_does_not_change_ui_fingerprint(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
+ write_ui_builder_stage(tmp_path)
monkeypatch.setenv("REGRESSION_VOICE_REALTIME_ENABLED", "false")
before = incus_regression.compute_fingerprints(tmp_path)["ui_source"]
@@ -1244,6 +1505,7 @@ def test_delete_round_trips_generated_worktree_slug(tmp_path: Path, monkeypatch:
def test_up_skips_host_port_preflight_for_existing_instance(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ write_ui_builder_stage(tmp_path)
(tmp_path / "pyproject.toml").write_text("[project]\nname='x'\n", encoding="utf-8")
(tmp_path / "uv.lock").write_text("", encoding="utf-8")
(tmp_path / "ui").mkdir()
@@ -1270,7 +1532,7 @@ def test_up_skips_host_port_preflight_for_existing_instance(tmp_path: Path, monk
monkeypatch.setattr(incus_regression, "write_runtime_env", lambda *args, **kwargs: None)
monkeypatch.setattr(incus_regression, "sync_source", lambda *args, **kwargs: None)
monkeypatch.setattr(incus_regression, "read_existing_fingerprints", lambda *args, **kwargs: {})
- monkeypatch.setattr(incus_regression, "update_dependencies_and_build", lambda *args, **kwargs: None)
+ monkeypatch.setattr(incus_regression, "update_dependencies_and_build", lambda *args, **kwargs: set())
monkeypatch.setattr(incus_regression, "run_prepare_state", lambda *args, **kwargs: None)
monkeypatch.setattr(incus_regression, "write_metadata", lambda *args, **kwargs: None)
monkeypatch.setattr(incus_regression, "restart_and_verify", lambda *args, **kwargs: None)
@@ -1298,6 +1560,7 @@ def test_up_skips_host_port_preflight_for_existing_instance(tmp_path: Path, monk
clean=False,
force_deps=False,
no_build_ui=True,
+ force_ui=False,
reset_mode="none",
)
@@ -1307,6 +1570,8 @@ def test_up_skips_host_port_preflight_for_existing_instance(tmp_path: Path, monk
def test_up_defers_master_port_preflight_until_after_instance_exists(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
+ write_ui_builder_stage(tmp_path)
+
class ExistingRunner:
def __init__(self, *, dry_run=False):
self.dry_run = dry_run
@@ -1337,7 +1602,7 @@ def test_up_defers_master_port_preflight_until_after_instance_exists(
monkeypatch.setattr(incus_regression, "write_runtime_env", lambda *args, **kwargs: None)
monkeypatch.setattr(incus_regression, "sync_source", lambda *args, **kwargs: None)
monkeypatch.setattr(incus_regression, "read_existing_fingerprints", lambda *args, **kwargs: {})
- monkeypatch.setattr(incus_regression, "update_dependencies_and_build", lambda *args, **kwargs: None)
+ monkeypatch.setattr(incus_regression, "update_dependencies_and_build", lambda *args, **kwargs: set())
monkeypatch.setattr(incus_regression, "run_prepare_state", lambda *args, **kwargs: None)
monkeypatch.setattr(incus_regression, "write_metadata", lambda *args, **kwargs: None)
monkeypatch.setattr(incus_regression, "restart_and_verify", lambda *args, **kwargs: None)
@@ -1365,6 +1630,7 @@ def test_up_defers_master_port_preflight_until_after_instance_exists(
clean=False,
force_deps=False,
no_build_ui=True,
+ force_ui=False,
reset_mode="none",
)
@@ -1395,7 +1661,7 @@ def test_up_checks_host_port_preflight_for_new_local_instance(tmp_path: Path, mo
monkeypatch.setattr(incus_regression, "sync_source", lambda *args, **kwargs: None)
monkeypatch.setattr(incus_regression, "compute_fingerprints", lambda repo_root: {})
monkeypatch.setattr(incus_regression, "read_existing_fingerprints", lambda *args, **kwargs: {})
- monkeypatch.setattr(incus_regression, "update_dependencies_and_build", lambda *args, **kwargs: None)
+ monkeypatch.setattr(incus_regression, "update_dependencies_and_build", lambda *args, **kwargs: set())
monkeypatch.setattr(incus_regression, "run_prepare_state", lambda *args, **kwargs: None)
monkeypatch.setattr(incus_regression, "write_metadata", lambda *args, **kwargs: None)
monkeypatch.setattr(incus_regression, "restart_and_verify", lambda *args, **kwargs: None)
@@ -1423,6 +1689,7 @@ def test_up_checks_host_port_preflight_for_new_local_instance(tmp_path: Path, mo
clean=False,
force_deps=False,
no_build_ui=True,
+ force_ui=False,
reset_mode="none",
)
@@ -1483,6 +1750,7 @@ def test_up_stops_when_the_daemon_cannot_say_whether_the_target_exists(
clean=False,
force_deps=False,
no_build_ui=True,
+ force_ui=False,
reset_mode="none",
)
@@ -1507,6 +1775,8 @@ def test_up_checks_seed_env_before_target_mutation(tmp_path: Path, monkeypatch:
def record(name):
def wrapper(*args, **kwargs):
calls.append(name)
+ if name == "update_dependencies_and_build":
+ return set()
if name == "require_runtime_seed_env":
raise SystemExit("missing")
@@ -1544,6 +1814,7 @@ def test_up_checks_seed_env_before_target_mutation(tmp_path: Path, monkeypatch:
clean=False,
force_deps=False,
no_build_ui=True,
+ force_ui=False,
reset_mode="none",
)
@@ -1568,6 +1839,8 @@ def test_up_checks_platform_seed_env_before_existing_reset_mutation(tmp_path: Pa
def record(name):
def wrapper(*args, **kwargs):
calls.append(name)
+ if name == "update_dependencies_and_build":
+ return set()
if name == "require_runtime_seed_env":
raise SystemExit("missing platform")
@@ -1602,6 +1875,7 @@ def test_up_checks_platform_seed_env_before_existing_reset_mutation(tmp_path: Pa
clean=False,
force_deps=False,
no_build_ui=True,
+ force_ui=False,
reset_mode="config",
)
@@ -1626,6 +1900,8 @@ def test_up_rejects_paired_master_reset_before_instance_mutation(tmp_path: Path,
def record(name):
def wrapper(*args, **kwargs):
calls.append(name)
+ if name == "update_dependencies_and_build":
+ return set()
return wrapper
@@ -1658,6 +1934,7 @@ def test_up_rejects_paired_master_reset_before_instance_mutation(tmp_path: Path,
clean=False,
force_deps=False,
no_build_ui=True,
+ force_ui=False,
reset_mode="config",
allow_reset_paired_master=False,
)
@@ -1683,6 +1960,8 @@ def test_up_dry_run_does_not_require_seed_env(tmp_path: Path, monkeypatch: pytes
def record(name):
def wrapper(*args, **kwargs):
calls.append(name)
+ if name == "update_dependencies_and_build":
+ return set()
if name == "require_runtime_seed_env":
raise AssertionError("dry-run should not require seed secrets")
@@ -1727,6 +2006,7 @@ def test_up_dry_run_does_not_require_seed_env(tmp_path: Path, monkeypatch: pytes
clean=False,
force_deps=False,
no_build_ui=True,
+ force_ui=False,
reset_mode="none",
)
@@ -1752,6 +2032,8 @@ def test_up_stops_old_service_before_mutating_runtime(tmp_path: Path, monkeypatc
def record(name):
def wrapper(*args, **kwargs):
calls.append(name)
+ if name == "update_dependencies_and_build":
+ return set()
return wrapper
@@ -1795,6 +2077,7 @@ def test_up_stops_old_service_before_mutating_runtime(tmp_path: Path, monkeypatc
clean=False,
force_deps=False,
no_build_ui=True,
+ force_ui=False,
reset_mode="none",
)
@@ -1827,6 +2110,8 @@ def test_up_preserves_runtime_env_when_existing_target_has_no_env_file(tmp_path:
def record(name):
def wrapper(*args, **kwargs):
calls.append(name)
+ if name == "update_dependencies_and_build":
+ return set()
return wrapper
@@ -1870,6 +2155,7 @@ def test_up_preserves_runtime_env_when_existing_target_has_no_env_file(tmp_path:
clean=False,
force_deps=False,
no_build_ui=True,
+ force_ui=False,
reset_mode="none",
)
@@ -1895,6 +2181,8 @@ def test_up_rewrites_runtime_env_when_env_file_is_loaded(tmp_path: Path, monkeyp
def record(name):
def wrapper(*args, **kwargs):
calls.append(name)
+ if name == "update_dependencies_and_build":
+ return set()
return wrapper
@@ -1937,6 +2225,7 @@ def test_up_rewrites_runtime_env_when_env_file_is_loaded(tmp_path: Path, monkeyp
clean=False,
force_deps=False,
no_build_ui=True,
+ force_ui=False,
reset_mode="none",
)
@@ -1979,6 +2268,8 @@ def test_up_reserves_worktree_port_under_mapping_lock(tmp_path: Path, monkeypatc
def record(name):
def wrapper(*args, **kwargs):
calls.append(name)
+ if name == "update_dependencies_and_build":
+ return set()
return wrapper
@@ -2035,6 +2326,7 @@ def test_up_reserves_worktree_port_under_mapping_lock(tmp_path: Path, monkeypatc
clean=False,
force_deps=False,
no_build_ui=True,
+ force_ui=False,
reset_mode="none",
)
@@ -2205,6 +2497,75 @@ def test_force_ui_rebuilds_with_realtime_enabled_by_default() -> None:
assert "pip install -e ." not in joined
+def run_ui_update(
+ *,
+ present: set[str],
+ force_ui: bool = False,
+ previous_fingerprints: dict | None = None,
+ next_fingerprints: dict | None = None,
+) -> str:
+ """Drive update_dependencies_and_build with a chosen instance state.
+
+ ``present`` names the artifacts a sync left behind: ``node_modules`` and/or
+ ``dist``. Every other command succeeds. The fingerprints default to a pair
+ that matches, so a caller that cares only about instance state gets the
+ "nothing changed" case.
+ """
+ commands: list[str] = []
+
+ class RecordingRunner:
+ def run(self, command, **kwargs):
+ joined = " ".join(command)
+ commands.append(joined)
+ if "ui/node_modules/.package-lock.json" in joined:
+ return subprocess.CompletedProcess(command, 0 if "node_modules" in present else 1)
+ if "test -d ui/dist" in joined:
+ return subprocess.CompletedProcess(command, 0 if "dist" in present else 1)
+ return subprocess.CompletedProcess(command, 0)
+
+ target = incus_regression.RegressionTarget(
+ target="master",
+ slug="master",
+ project="avr-master",
+ instance="avibe-master",
+ host_port=15130,
+ ui_host="127.0.0.1",
+ ui_port=5123,
+ )
+ fingerprints = {"python": "p", "ui_deps": "d", "ui_source": "s"}
+ incus_regression.update_dependencies_and_build(
+ RecordingRunner(),
+ target,
+ previous_fingerprints=dict(previous_fingerprints if previous_fingerprints is not None else fingerprints),
+ next_fingerprints=dict(next_fingerprints if next_fingerprints is not None else fingerprints),
+ force_deps=False,
+ build_ui=True,
+ force_ui=force_ui,
+ remote=None,
+ )
+ return "\n".join(commands)
+
+
+def test_unchanged_ui_reuses_the_dependency_tree_and_bundle_a_sync_kept() -> None:
+ joined = run_ui_update(present={"node_modules", "dist"})
+
+ assert "cd ui && npm ci" not in joined
+ assert "cd ui && npm run build" not in joined
+
+
+def test_npm_ci_runs_when_the_dependency_tree_is_absent_however_the_fingerprint_reads() -> None:
+ """``npm run build`` must never be asked to run without its dependencies.
+
+ An unchanged ``ui_deps`` fingerprint describes a lockfile, not the tree
+ installed from it; ``--clean`` and a fresh instance both leave the second
+ missing while the first still matches.
+ """
+ joined = run_ui_update(present={"dist"})
+
+ assert "cd ui && npm ci" in joined
+ assert joined.index("cd ui && npm ci") < joined.index("cd ui && npm run build")
+
+
def test_missing_ui_dist_overrides_no_build_ui_before_editable_install() -> None:
commands = []
@@ -2244,6 +2605,241 @@ def test_missing_ui_dist_overrides_no_build_ui_before_editable_install() -> None
assert build_index < install_index
+def reconcile_update(*, build_ui: bool, present: set[str]) -> set[str]:
+ """The keys ``update_dependencies_and_build`` reports it reconciled."""
+
+ class RecordingRunner:
+ def run(self, command, **kwargs):
+ joined = " ".join(command)
+ if "ui/node_modules/.package-lock.json" in joined:
+ return subprocess.CompletedProcess(command, 0 if "node_modules" in present else 1)
+ if "test -d ui/dist" in joined:
+ return subprocess.CompletedProcess(command, 0 if "dist" in present else 1)
+ return subprocess.CompletedProcess(command, 0)
+
+ target = incus_regression.RegressionTarget(
+ target="master",
+ slug="master",
+ project="avr-master",
+ instance="avibe-master",
+ host_port=15130,
+ ui_host="127.0.0.1",
+ ui_port=5123,
+ )
+ return incus_regression.update_dependencies_and_build(
+ RecordingRunner(),
+ target,
+ previous_fingerprints={"python": "p", "ui_deps": "old", "ui_source": "old"},
+ next_fingerprints={"python": "p", "ui_deps": "new", "ui_source": "new"},
+ force_deps=False,
+ build_ui=build_ui,
+ force_ui=False,
+ remote=None,
+ )
+
+
+def test_a_normal_update_reconciles_every_fingerprint_it_records(tmp_path: Path) -> None:
+ """Seeded from the real key set, so a fingerprint added later is covered.
+
+ Listing the keys here instead would pass forever while the new one silently
+ went unreconciled.
+ """
+ write_ui_builder_stage(tmp_path)
+ (tmp_path / "ui").mkdir()
+ every_key = set(incus_regression.compute_fingerprints(tmp_path))
+
+ reconciled = reconcile_update(build_ui=True, present={"node_modules", "dist"})
+
+ # ``show_runtime`` belongs to prepare_show_runtime, which cmd_up runs
+ # unconditionally; everything else is this function's to reconcile.
+ assert reconciled | {"show_runtime"} == every_key
+
+
+def test_no_build_ui_does_not_claim_the_ui_artifacts_it_never_touched() -> None:
+ reconciled = reconcile_update(build_ui=False, present={"node_modules", "dist"})
+
+ assert reconciled == {"python"}
+
+
+def test_no_build_ui_still_claims_a_ui_it_had_to_build_anyway() -> None:
+ """A missing dist overrides --no-build-ui, and then the record is honest."""
+ reconciled = reconcile_update(build_ui=False, present={"node_modules"})
+
+ assert reconciled == {"python", "ui_deps", "ui_source"}
+
+
+def test_an_unreconciled_fingerprint_keeps_the_value_that_described_the_artifact() -> None:
+ """The recorded fingerprint describes the artifact, not the synced source.
+
+ Blessing the new source here is what would let the next update skip
+ ``npm ci`` against a dependency tree installed from a different lockfile.
+ """
+ recorded = incus_regression.reconciled_fingerprints(
+ {"python": "p1", "ui_deps": "d1", "ui_source": "s1"},
+ {"python": "p2", "ui_deps": "d2", "ui_source": "s2"},
+ {"python"},
+ )
+
+ assert recorded == {"python": "p2", "ui_deps": "d1", "ui_source": "s1"}
+
+
+def test_an_unreconciled_fingerprint_with_no_history_stays_absent() -> None:
+ """Absent reads as "rebuild", which is the safe answer for a first run."""
+ recorded = incus_regression.reconciled_fingerprints(
+ {},
+ {"python": "p", "ui_deps": "d", "ui_source": "s"},
+ {"python"},
+ )
+
+ assert recorded == {"python": "p"}
+
+
+def test_a_no_build_ui_update_leaves_the_next_update_rebuilding_the_ui() -> None:
+ """The whole point, end to end across two updates.
+
+ A sync now keeps ``ui/node_modules``, so a stale tree survives a
+ ``--no-build-ui`` update. Only the fingerprint the first update recorded
+ decides whether the second one notices.
+ """
+ changed_lockfile = {"python": "p", "ui_deps": "new", "ui_source": "new"}
+ first = reconcile_update(build_ui=False, present={"node_modules", "dist"})
+ carried = incus_regression.reconciled_fingerprints(
+ {"python": "p", "ui_deps": "old", "ui_source": "old"},
+ changed_lockfile,
+ first,
+ )
+
+ joined = run_ui_update(
+ present={"node_modules", "dist"},
+ previous_fingerprints=carried,
+ next_fingerprints=changed_lockfile,
+ )
+
+ assert "cd ui && npm ci" in joined
+ assert "cd ui && npm run build" in joined
+
+
+def test_invalidating_the_record_reads_back_as_rebuild_everything(tmp_path: Path) -> None:
+ """Executed rather than pattern-matched, so it proves the file really empties.
+
+ ``read_existing_fingerprints`` turns whatever is on disk into the previous
+ values every skip decision compares against, and "no keys" is the only
+ shape that reads as "rebuild everything".
+ """
+ metadata_dir = tmp_path / "metadata"
+ record = metadata_dir / "fingerprints.json"
+ metadata_dir.mkdir()
+ record.write_text(json.dumps({"python": "p", "ui_deps": "d", "ui_source": "s"}), encoding="utf-8")
+
+ commands: list[list[str]] = []
+
+ class RecordingRunner:
+ def run(self, command, **kwargs):
+ commands.append(command)
+ return subprocess.CompletedProcess(command, 0)
+
+ target = incus_regression.RegressionTarget(
+ target="master",
+ slug="master",
+ project="avr-master",
+ instance="avibe-master",
+ host_port=15130,
+ ui_host="127.0.0.1",
+ ui_port=5123,
+ )
+
+ incus_regression.invalidate_fingerprints(RecordingRunner(), target, remote=None)
+
+ script = (
+ commands[0][-1]
+ .replace(incus_regression.FINGERPRINT_PATH, str(record))
+ .replace(incus_regression.METADATA_DIR, str(metadata_dir))
+ )
+ subprocess.run(["bash", "-lc", script], check=True)
+
+ assert json.loads(record.read_text(encoding="utf-8")) == {}
+
+
+def test_a_run_that_dies_mid_build_leaves_nothing_licensing_a_skip(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The other half of what a recorded fingerprint means.
+
+ Recording only what was rebuilt is not enough on its own: a rebuild also
+ destroys the artifact the previous record described, so a run that dies
+ part way through leaves a claim about something that no longer exists. If
+ the next update syncs the same inputs -- a rollback, or a rerun after
+ fixing the environment rather than the source -- that claim licenses
+ skipping the rebuild that just failed.
+ """
+ calls = []
+
+ class ExistingRunner:
+ def __init__(self, *, dry_run=False):
+ self.dry_run = dry_run
+
+ names = daemon_listing(*MASTER_NAMES)
+
+ def run(self, command, **kwargs):
+ return subprocess.CompletedProcess(command, 0, stdout="{}")
+
+ def record(name):
+ def wrapper(*args, **kwargs):
+ calls.append(name)
+
+ return wrapper
+
+ def die_mid_build(*args, **kwargs):
+ calls.append("update_dependencies_and_build")
+ raise RuntimeError("npm run build failed")
+
+ monkeypatch.setattr(incus_regression, "current_repo_root", lambda: tmp_path)
+ monkeypatch.setattr(incus_regression, "require_incus", lambda: None)
+ monkeypatch.setattr(incus_regression, "Runner", ExistingRunner)
+ monkeypatch.setattr(incus_regression, "ensure_project_and_instance", record("ensure_project_and_instance"))
+ monkeypatch.setattr(incus_regression, "stop_service_for_update", record("stop_service_for_update"))
+ monkeypatch.setattr(incus_regression, "write_runtime_env", record("write_runtime_env"))
+ monkeypatch.setattr(incus_regression, "migrate_legacy_backend_runtimes", record("migrate_legacy_backend_runtimes"))
+ monkeypatch.setattr(incus_regression, "should_seed_state", lambda *args, **kwargs: False)
+ monkeypatch.setattr(incus_regression, "sync_source", record("sync_source"))
+ monkeypatch.setattr(incus_regression, "compute_fingerprints", lambda repo_root: {"python": "new"})
+ monkeypatch.setattr(incus_regression, "read_existing_fingerprints", lambda *args, **kwargs: {"python": "old"})
+ monkeypatch.setattr(incus_regression, "invalidate_fingerprints", record("invalidate_fingerprints"))
+ monkeypatch.setattr(incus_regression, "update_dependencies_and_build", die_mid_build)
+ monkeypatch.setattr(incus_regression, "write_metadata", record("write_metadata"))
+
+ args = argparse.Namespace(
+ target="master",
+ slug=None,
+ host_port=None,
+ ui_host="127.0.0.1",
+ ui_port=5123,
+ worktree_port_start=15200,
+ worktree_port_end=15399,
+ env_file=None,
+ dry_run=False,
+ image="avibe-regression-base-current",
+ storage_pool="default",
+ network="incusbr0",
+ cpus="2",
+ memory="4GiB",
+ disk="20GiB",
+ processes="4096",
+ remote=None,
+ clean=False,
+ force_deps=False,
+ no_build_ui=True,
+ force_ui=False,
+ reset_mode="none",
+ )
+
+ with pytest.raises(RuntimeError):
+ incus_regression.cmd_up(args)
+
+ assert calls.index("invalidate_fingerprints") < calls.index("update_dependencies_and_build")
+ assert "write_metadata" not in calls
+
+
def test_missing_ui_dist_rebuilds_even_when_python_is_unchanged() -> None:
commands = []
@@ -2310,10 +2906,47 @@ def test_prepare_show_runtime_cleans_partial_source_and_retries_once() -> None:
joined = "\n".join(commands)
assert joined.count("vibe runtime prepare --strict") == 2
- assert "rm -rf ~/.avibe/runtime/show-runtime/source ~/.npm/_cacache" in joined
+ assert "rm -rf ~/.avibe/runtime/show-runtime/source" in joined
assert "vibe runtime status --json" in joined
+def test_prepare_show_runtime_retry_verifies_the_npm_cache_instead_of_deleting_it() -> None:
+ """The npm cache is a gigabyte of downloads shared by every later build.
+
+ Deleting it turns one failed prepare into a cold rebuild of everything;
+ `npm cache verify` drops the corrupt entries and keeps the rest.
+ """
+ commands = []
+
+ class RecordingRunner:
+ def __init__(self) -> None:
+ self.prepare_attempts = 0
+
+ def run(self, command, **kwargs):
+ joined = " ".join(command)
+ commands.append(joined)
+ if "vibe runtime prepare --strict" in joined:
+ self.prepare_attempts += 1
+ return subprocess.CompletedProcess(command, 1 if self.prepare_attempts == 1 else 0)
+ return subprocess.CompletedProcess(command, 0)
+
+ target = incus_regression.RegressionTarget(
+ target="master",
+ slug="master",
+ project="avr-master",
+ instance="avibe-master",
+ host_port=15130,
+ ui_host="127.0.0.1",
+ ui_port=5123,
+ )
+
+ incus_regression.prepare_show_runtime(RecordingRunner(), target, remote=None)
+
+ joined = "\n".join(commands)
+ assert "npm cache verify" in joined
+ assert "_cacache" not in joined
+
+
def test_restart_waits_for_service_and_status_running() -> None:
commands = []
diff --git a/tests/test_show_runtime_github_source.py b/tests/test_show_runtime_github_source.py
new file mode 100644
index 000000000..6a6118608
--- /dev/null
+++ b/tests/test_show_runtime_github_source.py
@@ -0,0 +1,204 @@
+"""The github-source provider must not rebuild a commit it already built.
+
+Every ``vibe runtime prepare`` used to re-run ``npm ci`` and ``npm run build``
+against a checkout that ``git fetch`` had just confirmed was unchanged, which
+is around forty seconds on each regression update. A marker recording the
+commit that produced the artifacts on disk turns that into one shallow fetch.
+"""
+
+from __future__ import annotations
+
+import subprocess
+from pathlib import Path
+
+import pytest
+
+from core import show_runtime
+
+
+def git(*args: str, cwd: Path) -> str:
+ result = subprocess.run(
+ ["git", *args],
+ cwd=cwd,
+ capture_output=True,
+ text=True,
+ check=True,
+ env={
+ "PATH": "/usr/bin:/bin:/usr/local/bin",
+ "HOME": str(cwd),
+ "GIT_AUTHOR_NAME": "t",
+ "GIT_AUTHOR_EMAIL": "[email protected]",
+ "GIT_COMMITTER_NAME": "t",
+ "GIT_COMMITTER_EMAIL": "[email protected]",
+ "GIT_CONFIG_GLOBAL": "/dev/null",
+ "GIT_CONFIG_SYSTEM": "/dev/null",
+ },
+ )
+ return result.stdout.strip()
+
+
+def make_upstream(tmp_path: Path) -> Path:
+ upstream = tmp_path / "upstream"
+ upstream.mkdir()
+ git("init", "-b", "main", cwd=upstream)
+ (upstream / "package.json").write_text('{"name": "runtime"}\n', encoding="utf-8")
+ git("add", "-A", cwd=upstream)
+ git("commit", "-m", "one", cwd=upstream)
+ return upstream
+
+
+class Harness:
+ """A manager wired to a local upstream, with npm simulated and git real."""
+
+ def __init__(self, tmp_path: Path, upstream: Path, *, force_install: bool = False) -> None:
+ self.npm_commands: list[list[str]] = []
+ self.manager = show_runtime.ShowRuntimeManager(
+ runtime_dir=tmp_path / "runtime",
+ runtime_source="github-source",
+ github_repo=str(upstream),
+ github_ref="main",
+ force_install=force_install,
+ )
+ self.manager._run_install_command = self._run # type: ignore[method-assign]
+
+ def _run(self, command: list[str], *, cwd: Path | None = None) -> bool:
+ if Path(command[0]).name == "npm":
+ self.npm_commands.append(command)
+ if command[1:] == ["run", "build"]:
+ cli = Path(cwd or ".") / "packages" / "runtime" / "dist" / "cli.js"
+ cli.parent.mkdir(parents=True, exist_ok=True)
+ cli.write_text("#!/usr/bin/env node\n", encoding="utf-8")
+ return True
+ return subprocess.run(command, cwd=cwd, capture_output=True).returncode == 0
+
+
[email protected](autouse=True)
+def resolvable_toolchain(monkeypatch: pytest.MonkeyPatch) -> None:
+ real_resolve = show_runtime._resolve_command
+ monkeypatch.setattr(show_runtime, "_resolve_node_command", lambda: ["/usr/bin/node"])
+ monkeypatch.setattr(
+ show_runtime,
+ "_resolve_command",
+ lambda name: ["/usr/bin/npm"] if name == "npm" else real_resolve(name),
+ )
+
+
+def test_first_install_builds_and_records_the_commit_it_built(tmp_path: Path) -> None:
+ upstream = make_upstream(tmp_path)
+ harness = Harness(tmp_path, upstream)
+
+ assert harness.manager._install_github_runtime()
+
+ assert [command[1:] for command in harness.npm_commands] == [["ci"], ["run", "build"]]
+ source_dir = harness.manager._github_source_dir()
+ assert harness.manager._read_github_build_marker(source_dir) == git("rev-parse", "HEAD", cwd=upstream)
+
+
+def test_unchanged_upstream_reuses_the_build_instead_of_repeating_it(tmp_path: Path) -> None:
+ upstream = make_upstream(tmp_path)
+ harness = Harness(tmp_path, upstream)
+ assert harness.manager._install_github_runtime()
+ harness.npm_commands.clear()
+
+ command = harness.manager._install_github_runtime()
+
+ assert command # the runtime is still usable
+ assert harness.npm_commands == []
+ assert harness.manager._install_reason is None
+
+
+def test_a_new_upstream_commit_is_still_picked_up(tmp_path: Path) -> None:
+ upstream = make_upstream(tmp_path)
+ harness = Harness(tmp_path, upstream)
+ assert harness.manager._install_github_runtime()
+ harness.npm_commands.clear()
+
+ (upstream / "package.json").write_text('{"name": "runtime", "version": "2"}\n', encoding="utf-8")
+ git("commit", "-am", "two", cwd=upstream)
+
+ assert harness.manager._install_github_runtime()
+
+ assert [command[1:] for command in harness.npm_commands] == [["ci"], ["run", "build"]]
+ source_dir = harness.manager._github_source_dir()
+ assert harness.manager._read_github_build_marker(source_dir) == git("rev-parse", "HEAD", cwd=upstream)
+
+
+def test_force_install_rebuilds_even_when_the_commit_matches(tmp_path: Path) -> None:
+ upstream = make_upstream(tmp_path)
+ harness = Harness(tmp_path, upstream)
+ assert harness.manager._install_github_runtime()
+ harness.npm_commands.clear()
+ harness.manager.force_install = True
+
+ assert harness.manager._install_github_runtime()
+
+ assert [command[1:] for command in harness.npm_commands] == [["ci"], ["run", "build"]]
+
+
+def test_a_failed_build_leaves_no_marker_licensing_a_skip(tmp_path: Path) -> None:
+ """A marker may only ever describe artifacts that exist right now.
+
+ Otherwise a build that died halfway would make every later prepare skip the
+ repair it needs.
+ """
+ upstream = make_upstream(tmp_path)
+ harness = Harness(tmp_path, upstream)
+ real_run = harness._run
+
+ def fail_the_build(command: list[str], *, cwd: Path | None = None) -> bool:
+ if command[1:] == ["run", "build"]:
+ harness.npm_commands.append(command)
+ return False
+ return real_run(command, cwd=cwd)
+
+ harness.manager._run_install_command = fail_the_build # type: ignore[method-assign]
+ assert harness.manager._install_github_runtime() is None
+
+ source_dir = harness.manager._github_source_dir()
+ assert harness.manager._read_github_build_marker(source_dir) is None
+
+ harness.manager._run_install_command = real_run # type: ignore[method-assign]
+ harness.npm_commands.clear()
+ assert harness.manager._install_github_runtime()
+ assert [command[1:] for command in harness.npm_commands] == [["ci"], ["run", "build"]]
+
+
+# The complete rebuild sequence, asserted by
+# ``test_first_install_builds_and_records_the_commit_it_built``. Each step
+# replaces part of the artifact the marker describes, so each one failing must
+# leave the marker gone.
[email protected]("failing_step", [["ci"], ["run", "build"]])
+def test_a_failed_rebuild_retracts_the_marker_it_had_already_earned(tmp_path: Path, failing_step: list[str]) -> None:
+ """The marker describes the artifact on disk, and a rebuild replaces it.
+
+ A rebuild at the commit already recorded is the case that bites: the marker
+ still names that commit while ``npm ci`` has emptied node_modules, so the
+ next ordinary prepare would fetch the same commit, match the marker, find
+ the stale entry point still resolving, and skip the repair forever.
+ """
+ upstream = make_upstream(tmp_path)
+ harness = Harness(tmp_path, upstream)
+ assert harness.manager._install_github_runtime()
+ built = harness.manager._read_github_build_marker(harness.manager._github_source_dir())
+ assert built
+
+ real_run = harness._run
+
+ def fail_one_step(command: list[str], *, cwd: Path | None = None) -> bool:
+ if command[1:] == failing_step:
+ harness.npm_commands.append(command)
+ return False
+ return real_run(command, cwd=cwd)
+
+ harness.manager._run_install_command = fail_one_step # type: ignore[method-assign]
+ harness.manager.force_install = True
+ harness.npm_commands.clear()
+ harness.manager._install_github_runtime()
+
+ assert harness.manager._read_github_build_marker(harness.manager._github_source_dir()) is None
+
+ harness.manager._run_install_command = real_run # type: ignore[method-assign]
+ harness.manager.force_install = False
+ harness.npm_commands.clear()
+ assert harness.manager._install_github_runtime()
+ assert [command[1:] for command in harness.npm_commands] == [["ci"], ["run", "build"]]