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.

fix(memory): stage package repair outside the live environment (#1910)

Call Whitede14bfd19343
diff --git a/docs/plans/memory-repair-atomic-generation.md b/docs/plans/memory-repair-atomic-generation.md
new file mode 100644
index 000000000..bfc760f85
--- /dev/null
+++ b/docs/plans/memory-repair-atomic-generation.md
@@ -0,0 +1,52 @@
+# Atomic Memory Package Repair
+
+## Evidence and Scope Decision
+
+Post-merge CI run 34014938619 passed all 405 Python files and 21 distribution
+contracts, but MEMORY-INDEP-026 failed after the released 3.0.13 core upgrade.
+The retained repair state reports `memory_package_install_failed`. Concurrent
+runtime logs show missing `certifi/cacert.pem` and later missing `vibe.api`.
+The installer's stderr was not retained, so its exact original error is unknown.
+
+A private reproduction using that run's core/Memory wheels and uv 0.12.10 proves
+the live-environment hazard: concurrent cache writes during `uv tool install
+--force` cause environment removal to fail with `Directory not empty`, leaving
+the interpreter and application files missing. An ordinary uncontended repair
+succeeds. This is consistent with, but does not prove, the historical CI error.
+
+The orchestrator extends the CI repair scope to the existing upgrade planner,
+Memory dependency job, their consuming tests (including MEMORY-INDEP-026), and
+this plan. Exact-version uv
+repairs must reuse the existing staged generation and atomic activation owner.
+No new installer, lifecycle state, retry policy, dependency, or timeout is needed.
+Pip installations retain their existing installer policy; the proven recursive
+tool-environment replacement is a uv-specific failure mechanism.
+
+## Invariants
+
+- Every uv plan installs into a fresh generation, never the running tool root.
+- Exact core/Memory versions and recorded release origins remain unchanged.
+- Installation or candidate verification failure cannot replace the live launcher.
+- Failed candidates are discarded; activated candidates survive restart failure.
+- Both service and UI restart from the activated generation. A restart-only retry
+ follows the stable launcher without reinstalling or consuming a new source tree.
+- Automatic repair admission, bounded attempts, serialized activation, real
+ released-wheel upgrades, and all existing CI checks remain intact.
+
+## Validation
+
+- Upgrade planner/lifecycle: 155 passed. Local dependency admission/repair: 194
+ passed, including staged install failure, timeout, integrity failure, locked
+ launcher, activation success, and restart-only retry contracts.
+- A fresh private tool environment with the real same-run wheel pair and uv
+ 0.12.10 completed staged repair during 289,488 controlled cache writes. All
+ protected original files retained their SHA-256 values; the exact core/Memory
+ pair passed candidate integrity and launcher activation. No service was started.
+- The released-upgrade scenario additionally requires a different active
+ interpreter and an intact, still-core-only previous environment.
+- Restart/Memory package-shape consumers: 38 passed. Upgrade diagnostics: 6
+ passed. Workflow contracts: 60 passed. Ruff 0.4.9, dependency compatibility
+ (85 private test-tool packages), and diff whitespace checks passed.
+- Pending: all PR checks and exact merged-source
+ installer/Windows verification. Docker is unavailable locally; real Docker
+ coverage remains mandatory in CI, not replaced by the private uv probe.
diff --git a/tests/e2e/test_upgrade_command.py b/tests/e2e/test_upgrade_command.py
index b3cc02479..cff5796db 100644
--- a/tests/e2e/test_upgrade_command.py
+++ b/tests/e2e/test_upgrade_command.py
@@ -389,6 +389,10 @@ def test_memory_indep_026_upgrade_command_bridges_released_3_0_13_generation():
'"$current_python" -c "from config.v2_config import V2Config; '
f"from importlib.metadata import version; assert V2Config.load().memory.enabled; assert version('avibe-os') == '{TEST_RELEASE_VERSION}'; "
f"assert version('avibe-memory') == '{TEST_RELEASE_VERSION}'\"",
+ 'test "$current_python" != "$upgraded_python"',
+ '"$upgraded_python" -c "import certifi, importlib.util; from pathlib import Path; '
+ "assert Path(certifi.where()).is_file(); assert importlib.util.find_spec('vibe.api') is not None; "
+ "assert importlib.util.find_spec('avibe_memory') is None\"",
'wait_until 120 1 "vibe service to report running=true" vibe_service_running',
"printf '%s\\n' \"$status_output\"",
]
diff --git a/tests/test_local_deps.py b/tests/test_local_deps.py
index 147045ab4..9e88a9515 100644
--- a/tests/test_local_deps.py
+++ b/tests/test_local_deps.py
@@ -3349,7 +3349,7 @@ def test_memory_package_dependency_job_targets_the_running_version_wherever_it_c
"delay_seconds": 2.0,
"vibe_path": "/bin/vibe",
"trigger": "memory-package-repair",
- "scope": "service",
+ "scope": "all",
}
assert result["restarting"] is True
assert result["restart"] == {"job_id": "restart"}
@@ -3484,6 +3484,83 @@ def test_memory_package_dependency_job_fails_closed_when_restart_cannot_be_sched
assert api._memory_package_restart_retry_required("3.0.14") is False
[email protected]("outcome", ("success", "install", "timeout", "integrity", "activation", "restart"))
+def test_memory_repair_stages_activation_without_mutating_the_running_environment(
+ monkeypatch, tmp_path, outcome,
+) -> None:
+ from core.install_integrity import IntegrityResult
+ from vibe import upgrade
+
+ root = tmp_path / "generations"
+ live = tmp_path / "uv" / "tools" / "avibe-os"
+ live.mkdir(parents=True)
+ original = {"vibe": b"old launcher", "python": b"old interpreter", "api.py": b"old code"}
+ for name, content in original.items():
+ (live / name).write_bytes(content)
+ launcher = tmp_path / "bin" / "vibe"
+ launcher.parent.mkdir()
+ launcher.symlink_to(live / "vibe")
+ candidate = root / "new" / "bin" / "vibe"
+ candidate.parent.mkdir(parents=True)
+ candidate.write_bytes(b"new launcher")
+ candidate.chmod(0o755)
+ candidate_python = candidate.with_name("python")
+ candidate_python.write_bytes(b"new interpreter")
+ candidate_python.chmod(0o755)
+ activation = upgrade.AtomicActivation(launcher, candidate)
+ plan = upgrade.UpgradePlan(["repair"], {}, "uv", activation=activation)
+
+ monkeypatch.setattr(upgrade, "atomic_uv_install_root", lambda: root)
+ monkeypatch.setattr(api, "atomic_upgrade_lock", nullcontext)
+ monkeypatch.setattr(api, "_memory_package_repair_rejection", lambda **_: None)
+ monkeypatch.setattr(api, "_published_running_version", lambda: "3.0.14")
+ monkeypatch.setattr(api, "get_running_vibe_path", lambda: str(launcher))
+ monkeypatch.setattr(api, "get_safe_cwd", lambda: str(tmp_path))
+ monkeypatch.setattr(api, "restart_is_pending", lambda: False)
+ monkeypatch.setattr(api, "release_asset_specs", lambda _: None)
+ monkeypatch.setattr(api, "_memory_package_auto_repair_state_path", lambda: tmp_path / "repair.json")
+ build = Mock(return_value=plan)
+ monkeypatch.setattr(api, "build_upgrade_plan", build)
+ execute = Mock(return_value=subprocess.CompletedProcess(["repair"], outcome == "install", "installed", ""))
+ if outcome == "timeout":
+ execute.side_effect = subprocess.TimeoutExpired(["repair"], 1)
+ monkeypatch.setattr(api, "execute_upgrade_plan", execute)
+ verify = Mock(return_value=IntegrityResult(outcome != "integrity", failures=("incomplete",) if outcome == "integrity" else ()))
+ monkeypatch.setattr(upgrade, "verify_upgrade_candidate", verify)
+ monkeypatch.setattr(api, "verify_python_environment", Mock(side_effect=AssertionError("must verify candidate, not live interpreter")))
+ if outcome == "activation":
+ monkeypatch.setattr(upgrade, "_prepare_launcher_replacement", Mock(side_effect=PermissionError("launcher locked")))
+ restart = Mock(return_value={"job_id": "new-generation"})
+ if outcome == "restart":
+ restart.side_effect = RuntimeError("cannot spawn")
+ monkeypatch.setattr(api, "schedule_restart", restart)
+
+ result = api._prepare_memory_package_job()
+
+ assert {name: (live / name).read_bytes() for name in original} == original
+ assert result["ok"] is (outcome == "success")
+ activated = outcome in {"success", "restart"}
+ assert launcher.resolve() == (candidate if activated else live / "vibe")
+ assert candidate.exists() is activated
+ assert restart.call_count == int(activated)
+ if activated:
+ restart.assert_called_once_with(
+ delay_seconds=2.0, vibe_path=str(launcher), trigger="memory-package-repair",
+ scope="all", python_executable=str(candidate_python),
+ )
+ if outcome == "restart":
+ assert api._memory_package_restart_retry_required("3.0.14") is True
+ restart.side_effect = None
+ retried = api._prepare_memory_package_job()
+ assert retried["ok"] is True
+ assert build.call_count == execute.call_count == 1
+ assert restart.call_args.kwargs == {
+ "delay_seconds": 2.0, "vibe_path": str(launcher),
+ "trigger": "memory-package-repair", "scope": "all",
+ }
+ assert launcher.resolve() == candidate
+
+
def test_memory_indep_026_auto_repair_persists_a_per_version_attempt_budget(
monkeypatch,
tmp_path,
diff --git a/tests/test_upgrade_flow.py b/tests/test_upgrade_flow.py
index 8a9bcb7da..663e82554 100644
--- a/tests/test_upgrade_flow.py
+++ b/tests/test_upgrade_flow.py
@@ -931,7 +931,10 @@ def test_an_exact_plan_never_asks_for_an_upgrade_and_always_forces_the_install(m
"--force",
]
assert "--upgrade" not in uv_plan.command
- assert uv_plan.env["UV_TOOL_DIR"] == "/tmp/.local/share/uv/tools"
+ assert uv_plan.env["UV_TOOL_DIR"] != "/tmp/.local/share/uv/tools"
+ assert uv_plan.activation is not None
+ assert uv_plan.activation.launcher == Path("/custom/bin/vibe")
+ assert Path(uv_plan.env["UV_TOOL_DIR"]).is_relative_to(vibe_upgrade.atomic_uv_install_root())
pip_plan = build_upgrade_plan(
python_executable="/usr/bin/python3",
@@ -990,6 +993,9 @@ def test_an_exact_memory_plan_names_both_index_pins_when_no_source_is_given(monk
"avibe-os==3.0.10",
"avibe-memory==3.0.10",
]
+ assert uv_plan.activation is not None
+ assert uv_plan.env["UV_TOOL_DIR"] != "/tmp/.local/share/uv/tools"
+ assert uv_plan.env["UV_TOOL_BIN_DIR"] != "/custom/bin"
pip_plan = build_upgrade_plan(
python_executable="/usr/bin/python3",
@@ -2667,6 +2673,22 @@ def test_explicit_memory_install_keeps_exact_package_version(monkeypatch):
assert "avibe-memory==3.0.14" in plan.preflight_command
[email protected]("launcher", (None, "/tmp/uv/tools/avibe-os/bin/vibe"))
+def test_exact_uv_repair_without_a_stable_launcher_fails_before_mutation(monkeypatch, launcher):
+ monkeypatch.setattr(vibe_upgrade, "find_uv_binary", lambda **_: "/usr/bin/uv")
+ plan = build_upgrade_plan(
+ python_executable="/tmp/uv/tools/avibe-os/bin/python",
+ vibe_path=launcher, version="3.0.14", memory_package=True,
+ memory_version="3.0.14", base_env={"PATH": "/usr/bin"},
+ )
+ assert plan.activation is None
+ assert plan.preflight_error
+ run = Mock()
+ with pytest.raises(ValueError, match="stable vibe launcher"):
+ execute_upgrade_plan(plan, run=run)
+ run.assert_not_called()
+
+
def test_with_memory_extra_preserves_vcs_url_and_local_specs(tmp_path, monkeypatch):
from vibe.upgrade import _with_memory_extra
diff --git a/vibe/api.py b/vibe/api.py
index ea1425931..6fa26ef1d 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -9750,6 +9750,9 @@ def _prepare_memory_package_job(*, automatic: bool = False) -> dict:
reservation: dict | None = None
current_version: str | None = None
+ plan = None
+ activated = False
+ restart_python = None
try:
with atomic_upgrade_lock():
rejection = _memory_package_repair_rejection(
@@ -9835,11 +9838,12 @@ def _prepare_memory_package_job(*, automatic: bool = False) -> dict:
"output": output or None,
"reason": "memory_package_install_failed",
}
+ elif plan.activation is not None:
+ restart_python = _candidate_python(plan.activation.candidate_launcher)
+ activate_upgrade_candidate(plan.activation)
+ activated = True
+ result = {"ok": True}
else:
- # Keep the current UI process on its live tool environment
- # so a service-only restart can immediately observe the
- # companion. The shared upgrade lock serializes this exact
- # repair with staged forward upgrades.
integrity = verify_python_environment(sys.executable)
result = (
{"ok": True}
@@ -9857,7 +9861,10 @@ def _prepare_memory_package_job(*, automatic: bool = False) -> dict:
delay_seconds=2.0,
vibe_path=current_vibe_path,
trigger="memory-package-repair",
- scope="service",
+ # The old UI must release its Python environment too.
+ # Restart-only retries resolve the now-active launcher.
+ scope="all",
+ **({"python_executable": str(restart_python)} if restart_python else {}),
)
except Exception as exc: # noqa: BLE001
logger.warning("Memory package repair could not schedule activation restart", exc_info=True)
@@ -9877,7 +9884,7 @@ def _prepare_memory_package_job(*, automatic: bool = False) -> dict:
"restarting": True,
"restart": restart,
}
- except (OSError, subprocess.TimeoutExpired, ValueError, MigrationLockTimeout) as exc:
+ except (OSError, subprocess.TimeoutExpired, ValueError, RuntimeError, MigrationLockTimeout) as exc:
logger.warning("Memory package repair failed before completion: %s", exc)
result = {
"ok": False,
@@ -9885,6 +9892,9 @@ def _prepare_memory_package_job(*, automatic: bool = False) -> dict:
"output": str(exc),
"reason": "memory_package_install_failed",
}
+ finally:
+ if plan is not None and plan.activation is not None and not activated:
+ discard_atomic_uv_install_generation(plan.activation.candidate_launcher)
if reservation is not None and current_version is not None:
_finish_memory_package_auto_repair_attempt(
current_version,
diff --git a/vibe/upgrade.py b/vibe/upgrade.py
index 2b52d99e9..b90c8bf4f 100644
--- a/vibe/upgrade.py
+++ b/vibe/upgrade.py
@@ -150,6 +150,8 @@ def execute_upgrade_plan(
the existing restart supervisor owns any later activation.
"""
+ if plan.preflight_error:
+ raise ValueError(plan.preflight_error)
preflight = preflight_upgrade_plan(plan, run=run, **run_kwargs)
if preflight is not None:
if preflight.returncode != 0:
@@ -1451,24 +1453,15 @@ def build_upgrade_plan(
if is_uv_tool_install(executable) and uv_binary:
env = dict(base_env or os.environ)
- atomic = None
preflight_error = None
- if version is None:
- tool_dir, bin_dir, atomic = _staged_uv_environment(vibe_path)
- if atomic is None:
- preflight_error = "Cannot atomically upgrade uv installation: stable vibe launcher is unavailable"
- else:
- env["UV_TOOL_DIR"] = str(tool_dir)
- env["UV_TOOL_BIN_DIR"] = str(bin_dir)
+ # Exact repairs can recreate the whole uv environment too. Stage them
+ # just like forward upgrades while the service/UI still use the old one.
+ tool_dir, bin_dir, atomic = _staged_uv_environment(vibe_path)
+ if atomic is None:
+ preflight_error = "Cannot atomically upgrade uv installation: stable vibe launcher is unavailable"
else:
- current_tool_dir = get_current_uv_tool_dir(executable)
- vibe_bin_dir = get_current_vibe_bin_dir(vibe_path)
- if current_tool_dir is None:
- preflight_error = "Cannot safely repair uv installation: current tool root is unavailable"
- else:
- env["UV_TOOL_DIR"] = current_tool_dir
- if vibe_bin_dir:
- env["UV_TOOL_BIN_DIR"] = vibe_bin_dir
+ env["UV_TOOL_DIR"] = str(tool_dir)
+ env["UV_TOOL_BIN_DIR"] = str(bin_dir)
command = [uv_binary, "tool", "install", package_spec]
if pinned_memory_spec:
command.extend(["--with", pinned_memory_spec])