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(desktop): ship precompiled bytecode in the private Runtime (#2278)

Call White89bddaad0601
diff --git a/desktop/scripts/build-runtime-bundle.py b/desktop/scripts/build-runtime-bundle.py
index 7c3c2e9e1..dbf88e385 100755
--- a/desktop/scripts/build-runtime-bundle.py
+++ b/desktop/scripts/build-runtime-bundle.py
@@ -757,6 +757,76 @@ def prune_payload(payload: Path) -> None:
file.unlink()
+def python_library(private_python: Path, payload: Path) -> Path:
+ """Return the payload directory the Runtime imports its Python from.
+
+ Only this directory is compiled. Other `.py` files in the tree are not
+ imported, and some are not Python: the Windows interpreter ships Tix
+ preference files under `tcl/` that compileall rejects.
+ """
+ completed = subprocess.run(
+ [
+ str(private_python),
+ "-I",
+ "-B",
+ "-c",
+ "import sysconfig; print(sysconfig.get_path('stdlib')); print(sysconfig.get_path('purelib'))",
+ ],
+ check=True,
+ capture_output=True,
+ text=True,
+ )
+ stdlib, purelib = (Path(line).resolve() for line in completed.stdout.splitlines())
+ if not purelib.is_relative_to(stdlib):
+ raise SystemExit(f"Runtime site-packages is outside its standard library: {purelib}")
+ # Under the payload path compileall is given, so `-s` matches its paths.
+ return payload / stdlib.relative_to(payload.resolve())
+
+
+def compile_payload(private_python: Path, library: Path) -> None:
+ """Ship the Runtime's bytecode inside its verified tree.
+
+ The installed Runtime runs with `-B`: a `.pyc` written at run time would
+ fail `verify_installed_tree`. Without shipped bytecode, every Runtime
+ process therefore recompiles every module it imports. Unchecked-hash
+ bytecode stays valid wherever the tree is extracted, since it records no
+ source mtime, and the tree hash already binds each `.pyc` to its source.
+ """
+ run(
+ [
+ str(private_python),
+ "-I",
+ # compileall writes every file explicitly; `-B` only keeps its own
+ # imports from leaving timestamp bytecode that it then skips as current.
+ "-B",
+ "-m",
+ "compileall",
+ "-q",
+ "-j",
+ "0",
+ "--invalidation-mode",
+ "unchecked-hash",
+ # Record paths relative to the library, not this build's work dir.
+ # The import system rewrites them to the installed location on load.
+ "-s",
+ str(library),
+ str(library),
+ ]
+ )
+ # A Runtime that quietly compiles at run time again is the cost this step
+ # removes, and nothing downstream would notice it, so check what shipped.
+ sources = {source.parent / source.stem for source in library.rglob("*.py")}
+ compiled = set()
+ for bytecode in library.rglob("__pycache__/*.pyc"):
+ with bytecode.open("rb") as header:
+ # The flags word follows the magic number; 1 is unchecked-hash.
+ if int.from_bytes(header.read(8)[4:], "little") != 1:
+ raise SystemExit(f"Runtime bytecode is not unchecked-hash: {bytecode}")
+ compiled.add(bytecode.parent.parent / bytecode.name.rsplit(".", 2)[0])
+ if missing := sorted(sources - compiled):
+ raise SystemExit(f"{len(missing)} Runtime sources have no bytecode, including {missing[0]}.py")
+
+
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--target", required=True)
@@ -815,8 +885,11 @@ def main() -> int:
installed_payload = work_dir / "relocated runtime"
payload.rename(installed_payload)
payload = installed_payload
- verify_payload(target_config, payload, work_dir, sources["npm_version"])
prune_payload(payload)
+ private_python = payload / target_config["python_entrypoint"]
+ compile_payload(private_python, python_library(private_python, payload))
+ # Probe the tree as it ships, bytecode included.
+ verify_payload(target_config, payload, work_dir, sources["npm_version"])
output_parent = args.output.parent
output_parent.mkdir(parents=True, exist_ok=True)
diff --git a/tests/test_desktop_runtime_bundle_builder.py b/tests/test_desktop_runtime_bundle_builder.py
index 9b9455130..f52981282 100644
--- a/tests/test_desktop_runtime_bundle_builder.py
+++ b/tests/test_desktop_runtime_bundle_builder.py
@@ -2,11 +2,13 @@ from __future__ import annotations
import importlib.util
import json
+import marshal
import os
import shlex
import shutil
import stat
import subprocess
+import sys
import zipfile
from pathlib import Path
@@ -304,6 +306,37 @@ def test_runtime_zip_is_byte_for_byte_deterministic(tmp_path):
assert first.read_bytes() == second.read_bytes()
+def test_shipped_bytecode_is_valid_wherever_the_tree_is_extracted(tmp_path):
+ library = tmp_path / "payload" / "python" / "lib"
+ package = library / "package"
+ package.mkdir(parents=True)
+ (package / "__init__.py").write_text("")
+ (package / "module.py").write_text("VALUE = 1\n")
+
+ builder.compile_payload(Path(sys.executable), library)
+
+ bytecode = next((package / "__pycache__").glob("module.*.pyc")).read_bytes()
+ # Unchecked-hash: no source mtime, so extraction time cannot invalidate it.
+ assert int.from_bytes(bytecode[4:8], "little") == 1
+ # Recorded relative to the library, not to this build's directory.
+ assert Path(marshal.loads(bytecode[16:]).co_filename) == Path("package/module.py")
+
+
+def test_only_the_python_the_runtime_imports_is_compiled(tmp_path):
+ python_root = tmp_path / "payload" / "python"
+ (python_root / "Lib").mkdir(parents=True)
+ (python_root / "Lib" / "module.py").write_text("VALUE = 1\n")
+ # The Windows interpreter ships Tix preference files that are not Python.
+ preferences = python_root / "tcl" / "tix8.4.3" / "pref"
+ preferences.mkdir(parents=True)
+ (preferences / "WmDefault.py").write_text("proc tixPref {} {\n\tset x 1\n set y 2\n}\n")
+
+ builder.compile_payload(Path(sys.executable), python_root / "Lib")
+
+ assert list((python_root / "Lib" / "__pycache__").glob("module.*.pyc"))
+ assert not list(python_root.joinpath("tcl").rglob("*.pyc"))
+
+
def test_probe_diagnostics_report_every_log_including_the_ones_that_are_missing(tmp_path):
probe_home = tmp_path / "avibe-probe-xyz"
(probe_home / "runtime").mkdir(parents=True)