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(cli): report a failed restart with no service as a doctor failure (#1570)

Call White5afe52231b64
diff --git a/tests/test_restart_supervisor.py b/tests/test_restart_supervisor.py
index bc822468c..0d2bbef45 100644
--- a/tests/test_restart_supervisor.py
+++ b/tests/test_restart_supervisor.py
@@ -159,6 +159,48 @@ def test_schedule_restart_marks_status_failed_when_spawn_fails(monkeypatch, tmp_
assert "failed to spawn" in status["error"]
+ "outcome",
+ [
+ {"ok": False, "state": "failed", "error": "boom"},
+ {"ok": None, "state": "scheduled", "error": None},
+ {"ok": True, "state": "succeeded", "error": None},
+ ],
+ ids=["failed", "in-flight", "succeeded"],
+)
+def test_a_recorded_outcome_reports_the_job_and_nothing_about_liveness(monkeypatch, tmp_path, outcome):
+ """The record says what the job did. It makes no claim about the machine.
+
+ A fence, not a repair. An earlier revision of this fix had the writer stamp
+ what was alive at write time, and every later reader of that stamp was a way
+ to get a present-tense question wrong from a past-tense answer; doctor now
+ measures liveness when it reports, so the record must stay a statement about
+ the job alone. The liveness probes are stubbed to raise rather than to answer,
+ so a writer that starts consulting them fails here instead of in review --
+ and it names the second cost of consulting them, since a probe can fail on
+ its own (an unopenable lock file is enough) and a diagnostic detail is never
+ worth losing the restart result over, least of all on the spawn-error path
+ where losing it also strands the `ok: null` marker that makes status report a
+ restart still in flight.
+ """
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ paths.ensure_data_dirs()
+
+ def fail_probe(*_args, **_kwargs):
+ raise OSError("service.lock cannot be opened")
+
+ monkeypatch.setattr(runtime, "resolve_service_owner_pid", fail_probe)
+ monkeypatch.setattr(runtime, "extra_service_process_pids", fail_probe)
+
+ restart_supervisor._write_status({"job_id": "job-1", **outcome})
+
+ status = runtime.read_json(runtime.get_restart_status_path())
+ assert status["ok"] is outcome["ok"]
+ assert status["state"] == outcome["state"]
+ assert "service_alive" not in status
+
+
def test_restart_job_stops_and_starts_service(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
paths.ensure_data_dirs()
diff --git a/tests/test_runtime_service_lock.py b/tests/test_runtime_service_lock.py
index 8482d41ab..e4df97414 100644
--- a/tests/test_runtime_service_lock.py
+++ b/tests/test_runtime_service_lock.py
@@ -703,5 +703,42 @@ class RuntimeServiceLockTests(unittest.TestCase):
self.assertFalse(runtime.current_process_owns_service_instance())
+ def test_verified_service_running_follows_the_lock_not_the_lock_record(self):
+ """The held lock is the fact; a readable holder pid is not required.
+
+ ``start_service`` refuses on ``lock_available`` alone and does not care
+ whether a holder pid can be read, so the doctor predicate that decides
+ whether an instance has a working service has to agree with it. Corrupting
+ the record while the lock stays held is the state where those two can
+ disagree: it is what a service looks like in the window between taking the
+ lock and writing its record, and answering "no service is running" there
+ would report downtime for a running instance and prescribe a start that
+ cannot succeed.
+ """
+
+ with tempfile.TemporaryDirectory() as tmpdir:
+ runtime_dir = Path(tmpdir) / "runtime"
+ runtime_dir.mkdir(parents=True)
+ lock_path = runtime_dir / "service.lock"
+ pid_path = runtime_dir / "vibe.pid"
+
+ with patch("vibe.runtime.paths.get_runtime_service_lock_path", return_value=lock_path):
+ with patch("vibe.runtime.paths.get_runtime_pid_path", return_value=pid_path):
+ with patch("vibe.runtime.paths.ensure_data_dirs", return_value=None):
+ self.assertFalse(runtime.verified_service_running())
+
+ runtime.acquire_service_instance_lock()
+ try:
+ self.assertTrue(runtime.verified_service_running())
+
+ lock_path.write_text("", encoding="utf-8")
+ self.assertIsNone(runtime.service_instance_lock_available()[1])
+ self.assertTrue(runtime.verified_service_running())
+ finally:
+ runtime.release_service_instance_lock()
+
+ self.assertFalse(runtime.verified_service_running())
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/tests/test_vibe_cli.py b/tests/test_vibe_cli.py
index 769e6ed07..f8bcd9ef2 100644
--- a/tests/test_vibe_cli.py
+++ b/tests/test_vibe_cli.py
@@ -1,6 +1,7 @@
import json
import os
import pytest
+import re
import signal
import shlex
import sqlite3
@@ -185,6 +186,29 @@ def test_status_written(tmp_path, monkeypatch):
assert payload["detail"] == "pid=123"
[email protected]("state", ["running", "starting", "stopped", "error", "degraded"])
[email protected]("ok", [False, None, True], ids=["failed", "in-flight", "succeeded"])
+def test_a_restart_record_survives_every_status_write(tmp_path, monkeypatch, state, ok):
+ """Nothing about writing runtime status touches the restart record.
+
+ The record is the restart subsystem's own account of its last job, and doctor
+ reads it against live facts rather than against anything a status write
+ remembered. Seeded across every outcome and every state a caller can write, so
+ a status path added later inherits the assertion instead of needing its own.
+ """
+
+ monkeypatch.setattr(paths, "get_vibe_remote_dir", lambda: tmp_path / ".vibe_remote")
+ runtime.ensure_dirs()
+ restart_path = runtime.get_restart_status_path()
+ payload = {"ok": ok, "state": "failed" if ok is False else "succeeded", "job_id": "job-1"}
+ runtime.write_json(restart_path, payload)
+
+ runtime.write_status(state, detail="pid=123")
+
+ assert runtime.read_status()["state"] == state
+ assert runtime.read_json(restart_path) == payload
+
+
def test_render_status_includes_restart_status(tmp_path, monkeypatch):
monkeypatch.setattr(paths, "get_vibe_remote_dir", lambda: tmp_path / ".vibe_remote")
runtime.ensure_dirs()
@@ -1346,6 +1370,228 @@ def test_repair_stale_restart_state_removes_old_marker_without_start_time(monkey
assert refreshed == [True]
+def _restart_status_payload(**overrides) -> dict:
+ """Return the status the restart supervisor writes, defaulted to a failure."""
+
+ payload = {
+ "ok": False,
+ "job_id": "0d1f2e3a4b5c",
+ "supervisor_pid": 4242,
+ "supervisor_started_at": 1.0,
+ "state": "failed",
+ "trigger": "auto-update",
+ "delay_seconds": 0.0,
+ "scope": "all",
+ "old_pid": 111,
+ "new_pid": None,
+ "log_path": "/tmp/vibe-restart-0d1f2e3a4b5c.log",
+ "error": "start runtime failed: Config 'model_hub'\n contains unknown fields",
+ "created_at": "2026-08-11T04:50:31Z",
+ "stage_durations": {"restart_total_seconds": 1.5},
+ }
+ payload.update(overrides)
+ return payload
+
+
+def _seed_restart_status(payload: dict, *, age_seconds: float = 0.0) -> Path:
+ paths.ensure_data_dirs()
+ restart_path = runtime.get_restart_status_path()
+ runtime.write_json(restart_path, payload)
+ if age_seconds:
+ stamp = time.time() - age_seconds
+ os.utime(restart_path, (stamp, stamp))
+ return restart_path
+
+
+def _stub_service_liveness(monkeypatch, *, owner_pid=None, starting_pid=None, extra_pids=(), lock_held=None):
+ """Describe a machine state, and let the real predicates read it.
+
+ Stubbing ``verified_service_running`` itself would only assert which helper
+ doctor calls. These are the sources underneath it and underneath the broader
+ ``service_process_running``, so a test can name a machine state -- a lock
+ owner, a pid that only reserved itself, a stray process -- and assert the
+ verdict the real predicates produce for it.
+
+ ``lock_held`` defaults to whether a lock owner was named, which is the usual
+ case. Pass it True with no ``owner_pid`` for the one state where the two come
+ apart: the lock is held but its record answers no pid, either because the
+ service has not written it yet or because it was corrupted. The lock is what
+ ``start_service`` refuses on, so that state is a running service.
+ """
+
+ reserved = owner_pid if starting_pid is None else starting_pid
+ holds_lock = owner_pid is not None if lock_held is None else lock_held
+
+ def resolve_owner(*, include_starting=False, **_kwargs):
+ return reserved if include_starting else owner_pid
+
+ monkeypatch.setattr(cli.runtime, "resolve_service_owner_pid", resolve_owner)
+ monkeypatch.setattr(cli.runtime, "extra_service_process_pids", lambda *_a, **_kw: list(extra_pids))
+ monkeypatch.setattr(cli.runtime, "service_instance_lock_available", lambda: (not holds_lock, owner_pid))
+
+
+ "age_seconds",
+ [0.0, cli.DOCTOR_RESTART_RESULT_RETENTION_SECONDS + 60],
+ ids=["fresh", "past-retention"],
+)
+def test_recorded_restart_failure_with_no_service_is_a_doctor_failure(monkeypatch, age_seconds):
+ """A restart that failed and left nothing running is a failure at any age.
+
+ Age is what used to decide the verdict, so both sides of the retention
+ boundary are exercised against the same recorded failure: while the instance
+ is down, neither side may call it healthy nor offer to delete the one record
+ of why it is down.
+ """
+
+ _seed_restart_status(_restart_status_payload(), age_seconds=age_seconds)
+ _stub_service_liveness(monkeypatch)
+
+ items = cli._restart_state_items()
+
+ assert [item["status"] for item in items] == ["fail"]
+ item = items[0]
+ assert item["code"] == "runtime.restart_failed"
+ assert "model_hub" in item["message"]
+ assert "\n" not in item["message"]
+ assert "vibe-restart-0d1f2e3a4b5c.log" in item["message"]
+ assert not item.get("repairable")
+ assert "stale-restart-state" not in item.get("action", "")
+
+
+def test_the_failure_action_only_tells_the_reader_to_run_real_commands(monkeypatch):
+ """Every command the action names is one the reader can actually run.
+
+ An action is actionable on its own or not at all. An earlier revision of this
+ told the reader to "apply the extra-service-process repair listed in this
+ report", which is a dependency on what else got rendered: that item is behind
+ `--deep`, and the default run is exactly where a reader of this item lands, so
+ the instruction resolved to nothing. Naming the command instead is the fix, and
+ parsing it here is what keeps the name honest -- a renamed or misspelled repair
+ target fails against the real parser rather than against a user who is already
+ down. Extracted rather than asserted literally, so a command added to this text
+ later is checked too.
+ """
+
+ _seed_restart_status(_restart_status_payload())
+ _stub_service_liveness(monkeypatch)
+
+ action = cli._restart_state_items()[0]["action"]
+ commands = [text for text in re.findall(r"`([^`]+)`", action) if text.startswith("vibe ")]
+ assert commands, f"the action names no runnable command: {action}"
+
+ parser = cli.build_parser()
+ for command in commands:
+ parser.parse_args(shlex.split(command)[1:])
+
+ assert "vibe doctor repair duplicate-service-processes" in commands
+
+ # No command twice. `duplicate-service-processes` starts a clean service on
+ # the no-owner path it is prescribed for, so a trailing "then start again"
+ # earns `ServiceAlreadyRunningError` and reads as a recovery that failed --
+ # which is why this asserts the shape rather than that one wording: any
+ # repair that already does what a later step repeats fails here.
+ assert len(commands) == len(set(commands)), f"the action asks for a command twice: {commands}"
+
+
+ ("liveness", "expected"),
+ [
+ ({}, "fail"),
+ ({"starting_pid": 5555}, "fail"),
+ ({"extra_pids": (7777,)}, "fail"),
+ ({"starting_pid": 5555, "extra_pids": (5555,)}, "fail"),
+ ({"owner_pid": 4321}, "warn"),
+ ({"owner_pid": 4321, "extra_pids": (7777,)}, "warn"),
+ ({"lock_held": True}, "warn"),
+ ],
+ ids=[
+ "nothing-running",
+ "pid-reserved-but-never-locked",
+ "stray-process-holding-no-lock",
+ "half-started-child-both-reserved-and-scanned",
+ "lock-owner",
+ "lock-owner-beside-a-stray-process",
+ "lock-held-but-its-record-answers-no-pid",
+ ],
+)
+def test_a_restart_failure_is_downtime_until_a_lock_verified_service_exists(monkeypatch, liveness, expected):
+ """One record against every liveness shape: only the service lock ends downtime.
+
+ The shapes that are not a lock owner are the wreckage a failed restart leaves:
+ a pid that reserved itself and never acquired the lock, a stray process the
+ scan can see, or one child that is both. Reading any of them as a running
+ service would suppress the very failure that produced it, so each stays a
+ failure until something actually holds the lock.
+
+ The last shape is the one that discriminates the lock from its record. A held
+ lock with no readable holder pid is a service -- caught between acquiring the
+ lock and writing the record, or holding a corrupted one -- and it is exactly
+ what ``start_service`` refuses to start past. Calling it downtime would report
+ a running instance as down and then prescribe a start that cannot succeed.
+ """
+
+ _seed_restart_status(
+ _restart_status_payload(),
+ age_seconds=cli.DOCTOR_RESTART_RESULT_RETENTION_SECONDS + 60,
+ )
+ _stub_service_liveness(monkeypatch, **liveness)
+
+ items = cli._restart_state_items()
+
+ assert [item["status"] for item in items] == [expected]
+ if expected == "warn":
+ assert items[0]["repair"]["target"] == "stale-restart-state"
+
+
+ "extra",
+ [{}, {"service_alive": True}, {"service_alive": False}, {"whatever_a_future_writer_adds": True}],
+ ids=["bare", "claims-a-service-survived", "claims-nothing-survived", "an-unknown-field"],
+)
+def test_only_live_facts_decide_downtime_not_what_the_record_claims(monkeypatch, extra):
+ """No field in the record can talk doctor out of a verdict about right now.
+
+ A record is written at failure time and read arbitrarily later, so anything it
+ says about what was alive is a snapshot that may since have been falsified --
+ by a child that took the lock after the supervisor gave up, or by any later
+ start. The rule reads the record for the outcome and the machine for liveness,
+ and nothing else. Seeded with the field a previous revision of this PR wrote,
+ both ways round, so a record produced by any version reaches the same verdict.
+ """
+
+ _seed_restart_status(
+ {**_restart_status_payload(), **extra},
+ age_seconds=cli.DOCTOR_RESTART_RESULT_RETENTION_SECONDS + 60,
+ )
+ _stub_service_liveness(monkeypatch)
+
+ assert [item["status"] for item in cli._restart_state_items()] == ["fail"]
+
+
+def test_restart_state_items_classify_non_failures_without_probing_the_service(monkeypatch):
+ """A record the supervisor did not fail keeps the classification it always had.
+
+ The probes raise instead of returning a pid so this also pins the
+ short-circuit: only a recorded failure may cost doctor a process probe.
+ """
+
+ def fail_probe(*args, **kwargs):
+ raise AssertionError("classifying a non-failure must not probe the service")
+
+ monkeypatch.setattr(cli.runtime, "resolve_service_owner_pid", fail_probe)
+ monkeypatch.setattr(cli.runtime, "extra_service_process_pids", fail_probe)
+ succeeded = _restart_status_payload(ok=True, state="succeeded", error=None, new_pid=222)
+
+ _seed_restart_status(succeeded)
+ assert [item["status"] for item in cli._restart_state_items()] == ["pass"]
+
+ _seed_restart_status(succeeded, age_seconds=cli.DOCTOR_RESTART_RESULT_RETENTION_SECONDS + 60)
+ stale = cli._restart_state_items()
+ assert [item["status"] for item in stale] == ["warn"]
+ assert stale[0]["repair"]["target"] == "stale-restart-state"
+
+
def test_doctor_repair_dry_run_does_not_probe_runtime(monkeypatch):
def fail_runtime_probe(*args, **kwargs):
raise AssertionError("dry-run must not touch runtime probes")
diff --git a/vibe/cli.py b/vibe/cli.py
index 1a745150b..72e506710 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -1184,6 +1184,24 @@ def _restart_status_is_stale(payload: dict, path: Path) -> bool:
return False
+def _restart_failure_summary(payload: dict) -> str:
+ """Describe a recorded restart failure on the single line doctor prints.
+
+ Why it failed is the entire value of the item, so the recorded error is
+ carried through rather than summarized away, with its whitespace collapsed
+ because the report prints one line per item.
+ """
+
+ pairs = (
+ ("state", payload.get("state") or "unknown"),
+ ("error", " ".join(str(payload.get("error") or "").split())),
+ ("trigger", payload.get("trigger")),
+ ("job_id", payload.get("job_id")),
+ ("log", payload.get("log_path")),
+ )
+ return " ".join(f"{name}={value}" for name, value in pairs if value)
+
+
def _restart_state_items() -> list[dict]:
items: list[dict] = []
restart_path = runtime.get_restart_status_path()
@@ -1192,6 +1210,65 @@ def _restart_state_items() -> list[dict]:
_add_doctor_item(items, "pass", "No restart metadata is present", code="runtime.restart_state_absent")
return items
+ # Both clauses are read now, from what is on disk and what is running now.
+ # Nothing here asks what was true at some earlier moment, which is the whole
+ # design: an earlier version of this decided downtime from a liveness snapshot
+ # the supervisor had stamped into the record, and every interleaving between
+ # taking that snapshot and acting on it was a way to get the answer wrong. A
+ # rule with no remembered observation in it has no such window.
+ #
+ # The cost is bounded and in the safe direction. A restart that failed without
+ # stopping the old service -- the spawn path never stops anything -- leaves a
+ # record that outlives its relevance, so after that service is later stopped on
+ # purpose this reports a failure that is history. Both halves of the sentence
+ # are still true, and `vibe start` ends it. Suppressing it instead would mean
+ # trusting a remembered snapshot to stay true, and for a diagnostic the
+ # asymmetry decides it: a stale `fail` is a true statement with a self-clearing
+ # next step, while a wrong `pass` is the eight-day silent outage in #1567
+ # sitting behind a green health check.
+ #
+ # Note what the action must not say, which is the original defect: never offer
+ # the marker-deleting repair here. The reader may be genuinely down, and that
+ # command both destroys the only record of why and makes doctor pass again --
+ # an operator following it would silence their own health check.
+ #
+ # This has to be read before the staleness branch below, because terminal
+ # metadata goes stale after DOCTOR_RESTART_RESULT_RETENTION_SECONDS, and that
+ # branch offers a repair that deletes the marker -- on a still-down instance,
+ # the reason it is down.
+ #
+ # Liveness asks `verified_service_running`, never the broader
+ # `service_process_running`. The broad one reports whatever occupies this data
+ # dir, which is the right question for refusing a second start and the wrong
+ # one here: a pid reserved by a process that never acquired the lock is the
+ # wreckage of a failed start, not a recovery, and reading it as one would
+ # suppress the very failure it came from. What that leaves is a stray process
+ # `start_service` refuses to start past, because it asks the broad question --
+ # so the action has to cover it, and `_service_lifecycle_items` cannot be the
+ # one to do that here: its extra-process item is behind `--deep` and the
+ # default run is exactly where a reader of this lands.
+ #
+ # Which is the whole discipline for the text below. Every sentence of procedure
+ # is a claim about control flow this item does not own, and each one is
+ # separately falsifiable: earlier revisions deferred to an item that is not
+ # rendered by default, and then told the reader to start again after a repair
+ # that starts the service itself. So it names the two commands, in order, and
+ # says the one thing the reader cannot see -- that the repair brings the
+ # service up -- because that is what stops them from running start twice and
+ # reading `ServiceAlreadyRunningError` as a failed recovery. Anything beyond
+ # that is a prediction, and the commands report their own outcomes.
+ if payload.get("ok") is False and not runtime.verified_service_running():
+ _add_doctor_item(
+ items,
+ "fail",
+ f"Last restart failed and no service is running: {_restart_failure_summary(payload)}",
+ "Read the restart log named above for the cause, then run `vibe start`. If that reports a "
+ "service already running, the failed restart left a process holding no lock: run "
+ "`vibe doctor repair duplicate-service-processes`, which stops it and brings the service up.",
+ code="runtime.restart_failed",
+ )
+ return items
+
if _restart_status_is_stale(payload, restart_path):
state = payload.get("state") or "unknown"
_add_doctor_item(
diff --git a/vibe/runtime.py b/vibe/runtime.py
index 40d6e75db..f6bcae7af 100644
--- a/vibe/runtime.py
+++ b/vibe/runtime.py
@@ -762,6 +762,35 @@ def service_process_running() -> bool:
return resolve_service_owner_pid(include_starting=False) is not None or bool(extra_service_process_pids())
+def verified_service_running() -> bool:
+ """Report whether a service holding the service lock is running.
+
+ ``service_process_running`` answers a different question -- whether anything at
+ all occupies this data dir -- and ``start_service`` is right to ask that one,
+ because a half-started child must still block a second start. Deciding whether
+ the instance has a working service needs the narrower fact: a process that
+ reserved the pid and never acquired the lock is not a service, it is a failed
+ start, and a restart record describing that failure must not be demoted to
+ history because the wreckage is still running.
+
+ The held lock *is* that fact, so this asks for nothing else. Reading the holder
+ pid out of the lock record and requiring it to parse would be strictly weaker
+ than the signal already in hand: the record is written just after the lock is
+ taken, so a service caught in that window -- or one whose record was corrupted
+ -- holds the lock while answering no pid, and calling that "no service" both
+ contradicts the lock and disagrees with ``start_service``, which refuses on
+ ``lock_available`` alone and does not care whether a holder pid could be read.
+ A dead holder cannot keep the lock either, since the kernel drops it when the
+ process goes, so liveness needs no separate check.
+
+ Cheap by construction: one open and one non-blocking lock attempt, and unlike
+ the broader probe it never scans the process table.
+ """
+
+ lock_available, _holder_pid = service_instance_lock_available()
+ return not lock_available
+
+
def _pid_reservation_is_fresh(pid_path: Path, pid: int, *, max_age: float = SERVICE_SLOW_START_TIMEOUT_SECONDS) -> bool:
try:
pidfile_mtime = pid_path.stat().st_mtime