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(regression): derive environment existence from a completed Incus listing

cyh126bc4dd2c12
diff --git a/AGENTS.md b/AGENTS.md
index b3529d55d..d644bab9a 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -127,6 +127,32 @@ State and lookup notes:
- `.env.regression` is read from the current worktree first, then the primary checkout
- branch/master source checkouts default `REGRESSION_SHOW_RUNTIME_SOURCE=github-source`; packaged release installs should use the packaged manifest path
+#### Connecting to Incus on macOS
+
+There is no native Incus daemon on macOS; it runs inside the Lima VM
+`avibe-incus-regression`. A plain `incus` on the host reaches no server, so the
+runner must be driven through the VM:
+
+```
+INCUS_CMD="limactl shell avibe-incus-regression -- sudo incus" ./scripts/run_regression.sh
+```
+
+Two consequences worth knowing before reading a runner failure:
+
+- Lima's default port-forward rule mirrors every `127.0.0.1` listener inside the
+ VM onto the Mac. A live environment's UI port therefore *is* held on the host,
+ by its own Incus proxy device. The host-side port preflight is a valid check
+ precisely because of this mirroring — it just must only run once the daemon has
+ confirmed the environment is absent.
+- The runner derives existence from a listing the daemon completed, never from a
+ lookup's exit status, so an unreachable or stalled daemon now aborts with
+ `Could not list …` instead of reporting the environment as absent and trying to
+ create it. Seeing that error means `INCUS_CMD` is unset, or the daemon is up but
+ stalled — `context deadline exceeded` / `no available cowsql leader server
+ found` usually means the VM is starved. Check `/proc/pressure/memory` and
+ `/proc/pressure/io` inside the VM; if `full avg10` is high, raise `cpus` /
+ `memory` in `~/.lima/avibe-incus-regression/lima.yaml` and restart the VM.
+
## 4. Configuration and Routing Model
Persistent configuration is centered on `config/v2_config.py` and the Web UI.
diff --git a/scripts/incus_regression.py b/scripts/incus_regression.py
index 658759231..45c42d2ea 100644
--- a/scripts/incus_regression.py
+++ b/scripts/incus_regression.py
@@ -64,6 +64,13 @@ DEFAULT_WORKTREE_PORT_END = 15399
ENV_FILE_NAME = ".env.regression"
ENV_PREFIX = "REGRESSION_"
SLUG_RE = re.compile(r"^[a-z][a-z0-9-]{1,38}[a-z0-9]$")
+DAEMON_UNREACHABLE_HINT = (
+ "The daemon did not answer, so whether the environment already exists is unknown and the "
+ "runner will not guess. On macOS the daemon lives in the Lima VM, so plain `incus` cannot "
+ "reach it: set INCUS_CMD, e.g. INCUS_CMD='limactl shell avibe-incus-regression -- sudo incus'. "
+ "A daemon that is up but stalled (\"context deadline exceeded\", \"no available cowsql leader "
+ "server found\") usually means the VM is starved for IO or memory; let it recover, then retry."
+)
class RegressionError(RuntimeError):
@@ -108,11 +115,28 @@ class Runner:
kwargs["input"] = input_text
return subprocess.run(list(command), **kwargs)
- def exists(self, command: Sequence[str]) -> bool:
+ def names(self, command: Sequence[str], *, what: str) -> list[str]:
+ """Return the names the daemon enumerated, or raise if it could not answer.
+
+ Existence must come from a listing the daemon actually completed, never
+ from a lookup's exit status: `incus` exits non-zero both when an object
+ is genuinely absent and when the daemon is unreachable or its database
+ is stalled. Collapsing the second into the first turns "cannot tell"
+ into "not there", and callers then set out to create what already
+ exists.
+ """
if self.dry_run:
- return False
- result = subprocess.run(list(command), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
- return result.returncode == 0
+ return []
+ result = subprocess.run(list(command), capture_output=True, text=True)
+ if result.returncode != 0:
+ raise RegressionError(f"Could not list {what}: {daemon_failure_detail(result)}\n{DAEMON_UNREACHABLE_HINT}")
+ try:
+ payload = json.loads(result.stdout or "[]")
+ except json.JSONDecodeError as exc:
+ raise RegressionError(f"Could not parse the {what} listing returned by Incus: {exc}") from exc
+ if not isinstance(payload, list):
+ raise RegressionError(f"Unexpected {what} listing returned by Incus: {type(payload).__name__}")
+ return [item["name"] for item in payload if isinstance(item, dict) and isinstance(item.get("name"), str)]
def incus(*args: str, project: str | None = None) -> list[str]:
@@ -133,6 +157,25 @@ def optional_remote_ref(remote: str | None) -> list[str]:
return [remote_ref(remote)] if remote else []
+def daemon_failure_detail(result: subprocess.CompletedProcess[str]) -> str:
+ output = (result.stderr or result.stdout or "").strip().splitlines()
+ return output[0] if output else f"exit status {result.returncode}"
+
+
+def project_exists(runner: Runner, remote: str | None, project: str) -> bool:
+ command = incus("project", "list", *optional_remote_ref(remote), "--format", "json")
+ return project in runner.names(command, what="Incus projects")
+
+
+def instance_exists(runner: Runner, remote: str | None, project: str, instance: str) -> bool:
+ # An instance cannot outlive its project, so an absent project answers the
+ # question without asking Incus to list inside a project it does not have.
+ if not project_exists(runner, remote, project):
+ return False
+ command = incus("list", *optional_remote_ref(remote), "--format", "json", project=project)
+ return instance in runner.names(command, what=f"instances in project {project}")
+
+
def require_incus() -> None:
command = shlex.split(os.environ.get("INCUS_CMD", "incus"))
executable = command[0] if command else "incus"
@@ -619,7 +662,7 @@ def ensure_project_and_instance(
processes: str,
remote: str | None,
) -> None:
- if not runner.exists(incus("project", "show", remote_ref(remote, target.project))):
+ if not project_exists(runner, remote, target.project):
command = incus("project", "create", remote_ref(remote, target.project))
for item in project_create_config(target):
command.extend(["--config", item])
@@ -628,7 +671,7 @@ def ensure_project_and_instance(
incus("profile", "edit", remote_ref(remote, "default"), project=target.project),
input_text=profile_yaml(storage_pool, network, cpus, memory, disk, processes),
)
- if not runner.exists(incus("info", remote_ref(remote, target.instance), project=target.project)):
+ if not instance_exists(runner, remote, target.project, target.instance):
runner.run(
incus(
"init",
@@ -1430,24 +1473,12 @@ def cmd_up(args: argparse.Namespace) -> int:
reserve_worktree_mapping(repo_root, target)
with target_update_lock(repo_root, target, dry_run=args.dry_run):
runner = Runner(dry_run=args.dry_run)
- target_exists = runner.exists(incus("info", remote_ref(args.remote, target.instance), project=target.project))
+ target_exists = instance_exists(runner, args.remote, target.project, target.instance)
if not args.dry_run and not target_exists and args.remote is None:
- try:
- ensure_host_port_available(target.ui_host, target.host_port)
- except RegressionError as exc:
- # A reachable incus client would have reported the instance as existing
- # above and skipped this preflight. The usual macOS cause is that `incus`
- # can't reach the Lima VM daemon, so `incus info` failed and the instance
- # only *looks* absent — point the operator at the real fix.
- raise RegressionError(
- f"{exc}\n"
- "If this instance already exists, the incus client is probably not "
- "reaching the daemon (on macOS incus runs in the Lima VM), so the "
- "earlier `incus info` failed and the instance looks absent. Set "
- "INCUS_CMD to drive incus through the VM, e.g. "
- "INCUS_CMD='limactl shell avibe-incus-regression -- sudo incus', so the "
- "runner sees the existing instance and skips this preflight."
- ) from exc
+ # Reached only once the daemon has enumerated its instances and this one
+ # was absent, so an occupied port is a real conflict with something else
+ # rather than this environment's own proxy device.
+ ensure_host_port_available(target.ui_host, target.host_port)
seed_requires_env = not args.dry_run and (args.reset_mode != "none" or not target_exists)
if seed_requires_env:
require_runtime_seed_env()
diff --git a/tests/test_incus_regression.py b/tests/test_incus_regression.py
index e847dc7cb..d8b7ec6fc 100644
--- a/tests/test_incus_regression.py
+++ b/tests/test_incus_regression.py
@@ -20,6 +20,31 @@ assert SPEC.loader is not None
sys.modules[SPEC.name] = incus_regression
SPEC.loader.exec_module(incus_regression)
+MASTER_NAMES = ("avr-master", "avibe-master")
+
+
+def daemon_listing(*names: str):
+ """Build a ``Runner.names`` stand-in that answers from a fixed inventory.
+
+ Stubs describe what the daemon enumerated rather than a bare yes/no, because
+ the runner has to tell "absent" apart from "could not ask": a stub that can
+ only say True or False cannot express the difference the code now depends on.
+ """
+
+ def listing(self, command, *, what):
+ return list(names)
+
+ return listing
+
+
+def stub_incus_result(returncode: int, *, stdout: str = "", stderr: str = ""):
+ """Stand in for `subprocess.run` so the real `Runner` sees a given incus result."""
+
+ def run(command, **kwargs):
+ return subprocess.CompletedProcess(list(command), returncode, stdout=stdout, stderr=stderr)
+
+ return run
+
def test_master_target_uses_stable_project_instance_and_port(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.delenv("REGRESSION_PORT", raising=False)
@@ -331,6 +356,79 @@ def test_require_incus_reports_missing_override(monkeypatch: pytest.MonkeyPatch)
incus_regression.require_incus()
+def test_existence_comes_from_the_names_the_daemon_listed(monkeypatch: pytest.MonkeyPatch) -> None:
+ listing = json.dumps([{"name": "avr-master"}, {"name": "avr-wt-demo-branch"}, {"other": "ignored"}])
+ monkeypatch.setattr(incus_regression.subprocess, "run", stub_incus_result(0, stdout=listing))
+
+ names = incus_regression.Runner().names(incus_regression.incus("project", "list"), what="Incus projects")
+
+ assert names == ["avr-master", "avr-wt-demo-branch"]
+
+
+ "result",
+ [
+ pytest.param({"returncode": 1, "stderr": "Error: unix.socket: connect: connection refused\n"}, id="daemon-down"),
+ pytest.param({"returncode": 1, "stderr": "Error: Failed to begin transaction: context deadline exceeded\n"}, id="daemon-stalled"),
+ pytest.param({"returncode": 1, "stdout": "boom on stdout\n"}, id="detail-on-stdout"),
+ pytest.param({"returncode": 1}, id="silent-failure"),
+ pytest.param({"returncode": 0, "stdout": "not json"}, id="unparseable"),
+ pytest.param({"returncode": 0, "stdout": '{"name": "avr-master"}'}, id="not-a-listing"),
+ ],
+)
+ "ask",
+ [
+ pytest.param(lambda runner: incus_regression.project_exists(runner, None, "avr-master"), id="project"),
+ pytest.param(
+ lambda runner: incus_regression.instance_exists(runner, None, "avr-master", "avibe-master"), id="instance"
+ ),
+ ],
+)
+def test_unanswerable_existence_question_raises_instead_of_reporting_absence(
+ monkeypatch: pytest.MonkeyPatch, result: dict, ask
+) -> None:
+ """Whatever keeps the daemon from producing a listing, the answer is an error.
+
+ `incus` exits non-zero both when an object is genuinely absent and when the
+ daemon is unreachable or stalled, so a boolean answer derived from exit
+ status silently turns "cannot tell" into "not there" — and every caller then
+ sets out to create what already exists.
+ """
+ monkeypatch.setattr(incus_regression.subprocess, "run", stub_incus_result(**result))
+
+ with pytest.raises(incus_regression.RegressionError):
+ ask(incus_regression.Runner())
+
+
+def test_unanswerable_existence_question_reports_the_daemon_detail_and_the_fix(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(
+ incus_regression.subprocess,
+ "run",
+ stub_incus_result(1, stderr="Error: Failed to begin transaction: context deadline exceeded\n"),
+ )
+
+ with pytest.raises(incus_regression.RegressionError) as excinfo:
+ incus_regression.project_exists(incus_regression.Runner(), None, "avr-master")
+
+ message = str(excinfo.value)
+ assert "context deadline exceeded" in message
+ assert "INCUS_CMD" in message
+
+
+def test_absent_project_answers_without_listing_inside_it(monkeypatch: pytest.MonkeyPatch) -> None:
+ commands = []
+
+ def run(command, **kwargs):
+ commands.append(list(command))
+ return subprocess.CompletedProcess(list(command), 0, stdout=json.dumps([{"name": "avr-other"}]))
+
+ monkeypatch.setattr(incus_regression.subprocess, "run", run)
+
+ assert incus_regression.instance_exists(incus_regression.Runner(), None, "avr-master", "avibe-master") is False
+ assert commands == [incus_regression.incus("project", "list", "--format", "json")]
+
+
def test_default_base_image_alias_is_not_remote_syntax() -> None:
assert ":" not in incus_regression.DEFAULT_IMAGE
@@ -357,8 +455,7 @@ def test_existing_instance_proxy_device_is_refreshed() -> None:
commands = []
class RecordingRunner:
- def exists(self, command):
- return True
+ names = daemon_listing(*MASTER_NAMES)
def run(self, command, *, check=True, **kwargs):
commands.append((command, check))
@@ -1151,8 +1248,7 @@ def test_up_skips_host_port_preflight_for_existing_instance(tmp_path: Path, monk
def __init__(self, *, dry_run=False):
self.dry_run = dry_run
- def exists(self, command):
- return command[:4] == ["incus", "--project", "avr-master", "info"]
+ names = daemon_listing(*MASTER_NAMES)
def run(self, command, **kwargs):
return subprocess.CompletedProcess(command, 0, stdout="{}")
@@ -1208,8 +1304,7 @@ def test_up_defers_master_port_preflight_until_after_instance_exists(
def __init__(self, *, dry_run=False):
self.dry_run = dry_run
- def exists(self, command):
- return True
+ names = daemon_listing(*MASTER_NAMES)
def run(self, command, **kwargs):
return subprocess.CompletedProcess(command, 0, stdout="{}")
@@ -1274,8 +1369,7 @@ def test_up_checks_host_port_preflight_for_new_local_instance(tmp_path: Path, mo
def __init__(self, *, dry_run=False):
self.dry_run = dry_run
- def exists(self, command):
- return False
+ names = daemon_listing()
def run(self, command, **kwargs):
return subprocess.CompletedProcess(command, 0, stdout="{}")
@@ -1329,6 +1423,68 @@ def test_up_checks_host_port_preflight_for_new_local_instance(tmp_path: Path, mo
assert preflight_calls == [("127.0.0.1", 15130)]
+def test_up_stops_when_the_daemon_cannot_say_whether_the_target_exists(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """An unreachable or stalled daemon aborts `up` before it touches anything.
+
+ This is the shape that broke a real run: a starved daemon failed the instance
+ lookup, the runner read that as "instance absent", and the host-port preflight
+ then tripped over the port the still-live instance's own proxy device holds.
+ The port was never the problem — the unanswered question was.
+ """
+ touched = []
+
+ def refuse(name):
+ def wrapper(*args, **kwargs):
+ touched.append(name)
+ raise AssertionError(f"{name} ran while the daemon's answer was unknown")
+
+ return wrapper
+
+ monkeypatch.setattr(incus_regression, "current_repo_root", lambda: tmp_path)
+ monkeypatch.setattr(incus_regression, "load_env_file", lambda repo_root, env_file: None)
+ monkeypatch.setattr(incus_regression, "require_incus", lambda: None)
+ monkeypatch.setattr(
+ incus_regression.subprocess,
+ "run",
+ stub_incus_result(1, stderr="Error: Failed to begin transaction: context deadline exceeded\n"),
+ )
+ monkeypatch.setattr(incus_regression, "ensure_host_port_available", refuse("ensure_host_port_available"))
+ monkeypatch.setattr(incus_regression, "require_runtime_seed_env", refuse("require_runtime_seed_env"))
+ monkeypatch.setattr(incus_regression, "ensure_project_and_instance", refuse("ensure_project_and_instance"))
+ monkeypatch.setattr(incus_regression, "stop_service_for_update", refuse("stop_service_for_update"))
+
+ 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,
+ reset_mode="none",
+ )
+
+ with pytest.raises(incus_regression.RegressionError, match="context deadline exceeded"):
+ incus_regression.cmd_up(args)
+
+ assert touched == []
+
+
def test_up_checks_seed_env_before_target_mutation(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
calls = []
@@ -1336,8 +1492,7 @@ def test_up_checks_seed_env_before_target_mutation(tmp_path: Path, monkeypatch:
def __init__(self, *, dry_run=False):
self.dry_run = dry_run
- def exists(self, command):
- return False
+ names = daemon_listing()
def run(self, command, **kwargs):
return subprocess.CompletedProcess(command, 1, stdout="")
@@ -1398,8 +1553,7 @@ def test_up_checks_platform_seed_env_before_existing_reset_mutation(tmp_path: Pa
def __init__(self, *, dry_run=False):
self.dry_run = dry_run
- def exists(self, command):
- return True
+ names = daemon_listing(*MASTER_NAMES)
def run(self, command, **kwargs):
return subprocess.CompletedProcess(command, 0, stdout="")
@@ -1457,8 +1611,7 @@ def test_up_rejects_paired_master_reset_before_instance_mutation(tmp_path: Path,
def __init__(self, *, dry_run=False):
self.dry_run = dry_run
- def exists(self, command):
- return True
+ names = daemon_listing(*MASTER_NAMES)
def run(self, command, **kwargs):
return subprocess.CompletedProcess(command, 0, stdout='{"state": "paired"}')
@@ -1515,8 +1668,7 @@ def test_up_dry_run_does_not_require_seed_env(tmp_path: Path, monkeypatch: pytes
def __init__(self, *, dry_run=False):
self.dry_run = dry_run
- def exists(self, command):
- return False
+ names = daemon_listing()
def run(self, command, **kwargs):
return subprocess.CompletedProcess(command, 0, stdout="{}")
@@ -1585,8 +1737,7 @@ def test_up_stops_old_service_before_mutating_runtime(tmp_path: Path, monkeypatc
def __init__(self, *, dry_run=False):
self.dry_run = dry_run
- def exists(self, command):
- return True
+ names = daemon_listing(*MASTER_NAMES)
def run(self, command, **kwargs):
return subprocess.CompletedProcess(command, 0, stdout="{}")
@@ -1661,8 +1812,7 @@ def test_up_preserves_runtime_env_when_existing_target_has_no_env_file(tmp_path:
def __init__(self, *, dry_run=False):
self.dry_run = dry_run
- def exists(self, command):
- return True
+ names = daemon_listing(*MASTER_NAMES)
def run(self, command, **kwargs):
return subprocess.CompletedProcess(command, 0, stdout="{}")
@@ -1730,8 +1880,7 @@ def test_up_rewrites_runtime_env_when_env_file_is_loaded(tmp_path: Path, monkeyp
def __init__(self, *, dry_run=False):
self.dry_run = dry_run
- def exists(self, command):
- return True
+ names = daemon_listing(*MASTER_NAMES)
def run(self, command, **kwargs):
return subprocess.CompletedProcess(command, 0, stdout="{}")
@@ -1795,8 +1944,7 @@ def test_up_reserves_worktree_port_under_mapping_lock(tmp_path: Path, monkeypatc
def __init__(self, *, dry_run=False):
self.dry_run = dry_run
- def exists(self, command):
- return True
+ names = daemon_listing("avr-wt-demo-branch", "avibe-wt-demo-branch")
def run(self, command, **kwargs):
return subprocess.CompletedProcess(command, 0, stdout="{}")
@@ -1832,6 +1980,10 @@ def test_up_reserves_worktree_port_under_mapping_lock(tmp_path: Path, monkeypatc
monkeypatch.setattr(incus_regression, "load_env_file", lambda repo_root, env_file: None)
monkeypatch.setattr(incus_regression, "require_incus", lambda: None)
monkeypatch.setattr(incus_regression, "Runner", ExistingRunner)
+ # Port allocation probes real host ports, so pin the preflight: this test is
+ # about reserving the mapping under the lock, not about which ports happen to
+ # be free on the machine running it.
+ monkeypatch.setattr(incus_regression, "ensure_host_port_available", lambda host, port: None)
monkeypatch.setattr(incus_regression, "worktree_mapping_lock", mapping_lock)
original_reserve_worktree_mapping = incus_regression.reserve_worktree_mapping