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(upgrade): roll back a failed upgrade restart instead of leaving no service (#1586)

Call Whiteb2eab4d91983
diff --git a/core/controller.py b/core/controller.py
index e36ddb0c8..a7c815555 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -62,6 +62,7 @@ from core.memory.blocking import run_blocking
from core.memory.operation_lock import MemoryOperationBusy, MemoryOperationLease
from core.memory_telemetry import log_attachment_capture
from vibe.i18n import get_supported_languages, t as i18n_t
+from vibe.runtime import mark_service_instance_started
logger = logging.getLogger(__name__)
@@ -1435,6 +1436,40 @@ class Controller:
except Exception:
logger.error("Background IM message callback failed", exc_info=True)
+ def _publish_readiness_unless_im_runtime_failed(self) -> None:
+ """Announce a started service instance, unless the IM runtime already died.
+
+ Readiness is what the upgrade supervisor waits for before it decides an
+ upgrade worked, so publishing it is the one irreversible statement this
+ startup makes: after it, nothing rolls back. The IM runtime is the piece
+ most likely to fail on a bad release and the only piece that fails on
+ another thread, which is why this asks it rather than assuming.
+
+ It asks for the recorded exception and not `Thread.is_alive()`. A Web-only
+ install with no IM platform configured has `im_client.run()` return
+ immediately and legitimately, so a liveness check would refuse readiness
+ forever on a service that is working perfectly.
+
+ Reaching this at all is now most of the answer. `MultiIMClient.run()`
+ emits the ready callback unconditionally once the platform threads are
+ started -- with zero platforms configured too, which is why a Web-only
+ install still gets here -- so an aggregate runtime that dies before that
+ point never calls this at all. Readiness is withheld by absence, rather
+ than by winning a race with the event loop's first pass the way it had
+ to when `run()` announced.
+
+ Which leaves the recorded exception as the weaker of the two checks
+ rather than the load-bearing one: the emitting thread blocks on this
+ callback, so it cannot record a failure while the callback runs. It is
+ kept because it belongs to the primitive and not to one caller -- move
+ the emission point and it is the check that survives the move.
+ """
+
+ if self._im_run_exception is not None:
+ logger.error("Not publishing service readiness: the IM runtime failed during startup")
+ return
+ mark_service_instance_started()
+
def _run_im_runtime(self) -> None:
try:
self.im_client.run()
@@ -1443,8 +1478,21 @@ class Controller:
logger.error("IM runtime thread exited with error: %s", exc, exc_info=True)
finally:
loop = self._loop
- if loop and loop.is_running():
- loop.call_soon_threadsafe(loop.stop)
+ if loop is not None:
+ try:
+ # Scheduled whether or not the loop has started yet. The
+ # `is_running()` guard that used to stand here dropped the
+ # stop in exactly the case that matters: this thread is
+ # started just before `run_forever()`, so an adapter that
+ # fails immediately -- the shape a bad release takes -- lands
+ # here while the loop is merely created, and the stop was
+ # discarded. `run_forever()` then ran forever with no IM
+ # runtime and nothing left to ask it to stop. A callback
+ # queued before the loop starts runs as soon as it does.
+ loop.call_soon_threadsafe(loop.stop)
+ except RuntimeError:
+ # A closed loop has already stopped; nothing left to ask.
+ logger.debug("IM runtime could not signal the event loop to stop", exc_info=True)
async def _restore_active_polls(self, platforms: set[str]) -> None:
opencode_agent = self.agent_service.agents.get("opencode")
@@ -1491,7 +1539,24 @@ class Controller:
return self.im_client.is_transport_ready(platform)
async def _on_runtime_ready(self) -> None:
- """Start aggregate services without waiting for external connectivity."""
+ """Start aggregate services, and announce readiness once they are started.
+
+ The steps below the readiness line are best-effort by construction: each
+ catches its own failure and continues, so none of them can mean the
+ service is not up. The steps above it are the opposite -- a failure
+ there aborts this function, so the steps below never run, and a service
+ with no durable delivery owners, no scheduled tasks and no watch service
+ is not a started service however alive its process looks.
+
+ Readiness is what the upgrade supervisor waits for before it decides an
+ upgrade worked, so which side of that line a step falls on decides
+ whether a release dying in its own startup gets rolled back or gets
+ recorded as a success. It used to be announced from `run()`, before this
+ callback had run at all: recovery could fail, request shutdown, and
+ re-raise, and the supervisor had already been told the service was up.
+ Put the line here and a startup step added later is inside the claim or
+ outside it because someone chose, not because of where it was written.
+ """
logger.info("IM runtime ready, starting core services")
workbench_platforms = {"avibe"}
if self.primary_platform == "avibe":
@@ -1502,6 +1567,12 @@ class Controller:
except Exception:
self.request_shutdown("runtime owner recovery failed")
raise
+
+ # --- everything above must have succeeded for the service to be up ---
+ # A no-op in any process that does not hold the service lock, so the
+ # embedded and test paths that run a controller are unaffected.
+ self._publish_readiness_unless_im_runtime_failed()
+
try:
await self.update_checker.check_and_send_post_update_notification(ready_platform="avibe")
except Exception as e:
@@ -1524,11 +1595,14 @@ class Controller:
except Exception as e:
logger.error("Failed to start runtime command watcher: %s", e, exc_info=True)
- claude_timeout, codex_timeout = self._get_idle_cleanup_timeouts()
- if (claude_timeout > 0 or codex_timeout > 0) and (
- self.cleanup_task is None or self.cleanup_task.done()
- ):
- self.cleanup_task = asyncio.create_task(self.periodic_cleanup())
+ try:
+ claude_timeout, codex_timeout = self._get_idle_cleanup_timeouts()
+ if (claude_timeout > 0 or codex_timeout > 0) and (
+ self.cleanup_task is None or self.cleanup_task.done()
+ ):
+ self.cleanup_task = asyncio.create_task(self.periodic_cleanup())
+ except Exception as e:
+ logger.error("Failed to start idle session cleanup: %s", e, exc_info=True)
async def _recover_runtime_owners(self) -> None:
"""Restore durable execution owners before any producer can admit work."""
@@ -3101,6 +3175,16 @@ class Controller:
self._im_thread.start()
if self._shutdown_requested:
self._ensure_shutdown_task("pre-loop request")
+ # Readiness is NOT published here, and where it is published is the
+ # whole point rather than a placement detail. This function starts
+ # startup; it does not finish it. Announcing from a line in the
+ # middle means every step written after that line is outside the
+ # claim by accident, which is the mistake this loop has now made
+ # four times at four different steps -- the caller, the IM thread,
+ # the UI probe, and the durable-owner recovery. The announcement
+ # belongs at a stated boundary inside the function that runs the
+ # startup steps, so a step added later is inside or outside it by
+ # decision. See `_on_runtime_ready`.
self._loop.run_forever()
if self._im_run_exception and not isinstance(self._im_run_exception, (KeyboardInterrupt, SystemExit)):
raise self._im_run_exception
diff --git a/main.py b/main.py
index b64c6886c..c1254bcf9 100644
--- a/main.py
+++ b/main.py
@@ -208,6 +208,14 @@ def main():
signal.signal(signal.SIGTERM, _handle_shutdown)
signal.signal(signal.SIGINT, _handle_shutdown)
+ # Readiness is published from inside `controller.run()`, by the code that
+ # reaches it. Announcing it from here was announcing something this
+ # function has not observed: `run()` still has to build the event loop,
+ # start the checkpoint service, schedule the internal server and get the
+ # IM runtime onto its thread, and it catches its own failures and returns,
+ # so the process exits through the ordinary path. A watcher that saw
+ # `running` in that window read a release dying in its own startup as an
+ # upgrade that worked.
try:
controller.run()
finally:
diff --git a/scripts/incus_regression_supervisor.py b/scripts/incus_regression_supervisor.py
index 08bdf18f5..c4cbc5bdd 100644
--- a/scripts/incus_regression_supervisor.py
+++ b/scripts/incus_regression_supervisor.py
@@ -34,6 +34,31 @@ def _reap_child(pid: int | None) -> None:
return
+def _adoptable_service_pid(pid: int | None) -> bool:
+ """Whether a replacement pid may be tracked as this supervisor's service.
+
+ Two questions, and both have to be answered yes. `service_pid_recorded` asks
+ whether this is the process the system considers the service: alive, named by
+ the pid file, holding the instance lock. `service_instance_started` asks the
+ one the lock cannot answer -- whether it finished starting. A restart that
+ takes the lock and then hangs in migration satisfies the first for as long as
+ it stays alive, so adopting on that alone is exactly how a hung generation
+ gets tracked as healthy: the supervisor keeps looping, never exits nonzero,
+ and the unit's `Restart=on-failure` never gets its chance.
+
+ Deferring adoption is not refusing it. A healthy replacement is still
+ starting for a moment, fails this on that iteration, and is adopted on a
+ later one; the only case that never converges is the one that never starts,
+ which is the case that must reach the recovery exit.
+ """
+
+ return bool(
+ pid
+ and runtime.service_pid_recorded(pid)
+ and runtime.service_instance_started(pid)
+ )
+
+
def _restart_in_progress() -> bool:
status = runtime.read_json(runtime.get_restart_status_path()) or {}
# Only the active stop/start phase ("running") should suppress the supervisor's
@@ -88,17 +113,18 @@ def main() -> int:
memory_ui_secret=memory_ui_secret,
)
- if not runtime.service_pid_recorded(service_pid):
- ready_service_pid = runtime.wait_for_service_ready(
- service_pid,
- timeout=runtime.SERVICE_SLOW_START_TIMEOUT_SECONDS,
- )
- if ready_service_pid is None:
- runtime.write_status("error", "service did not become ready", service_pid, ui_pid)
- runtime.stop_ui()
- runtime.stop_service()
- return 1
- service_pid = ready_service_pid
+ # Asked unconditionally: the predicate that used to guard this is the lock,
+ # which is held by a process that has not finished migrating and may never.
+ ready_service_pid = runtime.wait_for_service_ready(
+ service_pid,
+ timeout=runtime.SERVICE_SLOW_START_TIMEOUT_SECONDS,
+ )
+ if ready_service_pid is None:
+ runtime.write_status("error", "service did not become ready", service_pid, ui_pid)
+ runtime.stop_ui()
+ runtime.stop_service()
+ return 1
+ service_pid = ready_service_pid
runtime.write_status("running", "incus regression started", service_pid, ui_pid)
while not stopping:
@@ -106,13 +132,14 @@ def main() -> int:
# snapshotted here: a managed restart can begin mid-iteration, and a stale
# snapshot would let the supervisor kill a healthy restart.
current_service_pid = _read_pid_file(paths.get_runtime_pid_path())
- # Only track a *ready* service pid (recorded and holding the service lock).
- # Adopting a pid just because the file changed would let a hung restart
- # that never becomes ready masquerade as healthy and block recovery.
+ # Only track a service pid that has reported it finished starting --
+ # see `_adoptable_service_pid`. Adopting a pid just because the file
+ # changed, or just because it holds the lock, would let a hung restart
+ # masquerade as healthy and block recovery.
if (
current_service_pid
and current_service_pid != service_pid
- and runtime.service_pid_recorded(current_service_pid)
+ and _adoptable_service_pid(current_service_pid)
):
_reap_child(service_pid)
service_pid = current_service_pid
@@ -137,7 +164,7 @@ def main() -> int:
if (
current_service_pid
and current_service_pid != service_pid
- and runtime.service_pid_recorded(current_service_pid)
+ and _adoptable_service_pid(current_service_pid)
):
service_pid = current_service_pid
time.sleep(1)
diff --git a/storage/backups.py b/storage/backups.py
index 0fb58791f..b1d7ad016 100644
--- a/storage/backups.py
+++ b/storage/backups.py
@@ -22,6 +22,13 @@ JSON_STATE_BACKUP_RETENTION = 3
SQLITE_BACKUP_RETENTION = 2
BACKUP_MANIFEST_VERSION = 1
+#: The name a restore gives the database it takes out of service, inside the
+#: backup directory it restored from. That directory is the record of "we rolled
+#: back to this point", so the database rolled back FROM belongs beside it -- and
+#: living inside the window means the existing bound already covers it, instead
+#: of a second growth path needing rules of its own.
+REPLACED_DATABASE_NAME = "vibe.sqlite.replaced"
+
_JSON_BACKUP_RE = re.compile(
r"^sqlite-state-migration-(?P<timestamp>\d{8}T\d{6}Z)(?:-(?P<suffix>\d+))?$"
)
@@ -286,6 +293,50 @@ def next_backup_sequence(backups_dir: Path) -> int:
return max(recorded, default=-1) + 1
+def find_restorable_backup(backups_dir: Path, *, written_at_or_after: int) -> Path | None:
+ """The rollback point taken after a caller's own earlier observation, if any.
+
+ The other half of `next_backup_sequence`: a caller reads that number before
+ handing the database to code it does not trust, and reads it back through
+ here afterwards. Any backup numbered at or above it was written after the
+ observation, so this answers "did a migration episode begin while I was
+ watching, and where is its rollback point" without consulting a clock, a
+ revision stamp, or anything the watched code reported about itself. Those
+ were all tried and are all labels: two attempts can leave a stamp and a
+ schema identical while the rows differ, and a clock corrected backwards
+ between two attempts dates the later copy first.
+
+ The answer is the NEWEST such copy, which is the one closest to the data the
+ machine actually had: every attempt copies the database as it stood before
+ its own migration, so an older copy discards whatever was committed between
+ the attempts. It is not certified undamaged -- an attempt that commits rows
+ and then fails leaves them in the next attempt's copy -- and nothing here can
+ certify one, for the reason `_kept_within_position` gives: which copy at a
+ position is the good one cannot be decided from the position. So the
+ automatic answer loses no data, and the first copy at that position stays in
+ the window for an operator who has diagnosed the damage and wants to go
+ further back by hand.
+
+ Backups with no recorded number are never eligible. One was written by a
+ release that did not have the field, which places it before any observation
+ this release could have made.
+ """
+
+ # Filtering on a recorded sequence also guarantees a directory backup with a
+ # readable `vibe.sqlite`: only `_directory_candidate` reads the field, and it
+ # only returns a sqlite candidate when that file is present.
+ candidates = [
+ candidate
+ for candidate in _managed_candidates(backups_dir)
+ if candidate.kind == "sqlite"
+ and candidate.sequence is not None
+ and candidate.sequence >= written_at_or_after
+ ]
+ if not candidates:
+ return None
+ return max(candidates, key=lambda candidate: candidate.written_order).root
+
+
def _remove_candidate(candidate: _BackupCandidate) -> bool:
if candidate.root.is_symlink():
return False
@@ -579,3 +630,250 @@ def create_sqlite_migration_backup(
# would not count itself against the bound.
prune_state_backups(target_root, json_retention=None, protect=backup_dir)
return backup_dir
+
+
+def _duplicate_file(source: Path, destination: Path) -> None:
+ """Copy `source` to `destination` without a window where only one copy exists.
+
+ By link where the filesystem allows it, by copy where it does not.
+ """
+
+ try:
+ os.link(source, destination)
+ except OSError:
+ logger.debug("Hard link unavailable for %s; copying it to %s instead", source, destination, exc_info=True)
+ shutil.copy2(str(source), str(destination))
+
+
+def _swap_live_database(db_path: Path, replacement: Path, *, into: Path) -> Path | None:
+ """Put `replacement` at the live path, keeping all of what was there.
+
+ Displacing the old generation and installing the new one are one operation
+ because the invariant is one: at every instant a failure can be observed, the
+ live path holds a database together with the sidecars that belong to it.
+ Split across two functions, neither owns that -- the displacement ends with
+ the live log already cleared and the caller has not yet renamed anything into
+ place, so an interrupted install leaves a database missing its own committed
+ tail, and no amount of care in either half closes a gap that exists between
+ them.
+
+ The write-ahead log and shared-memory sidecars move with the displaced
+ database, and that is not tidiness: a `-wal` left behind belongs to the
+ generation being displaced, and SQLite would replay it into the restored
+ database and call the result recovered. Moving them under the displaced
+ database's own name keeps them where SQLite will find them for it instead.
+
+ That rule is about the name, not about the database, so it holds equally
+ when there is no database to displace. Sidecars are therefore collected
+ before the two paths divide, and every path out of here clears the live name
+ of sidecars it did not bring with it.
+
+ A previous displacement into this same rollback point is replaced, but only
+ once the new one is whole on disk -- staged under its own name, then renamed
+ over. The bound has to come from somewhere: a full copy of the database per
+ rollback attempt is the growth `prune_state_backups` exists to prevent. But
+ the copy being dropped is a working database an operator may still need, and
+ deleting it to make room for one not yet written trades a bounded directory
+ for a window in which neither generation is anywhere.
+
+ Nothing leaves the live path until the displaced generation is whole under
+ its own name, and that ordering is the whole design rather than a detail of
+ it. This runs to free the live pathname for a restore that is itself the
+ recovery from a failure, so its own failure has to leave the machine no worse
+ than it found it: on any error the live database is still there, still with
+ its own write-ahead log, and still the database it was. Every step before the
+ commit therefore duplicates rather than moves -- by link where the filesystem
+ allows it, by copy where it does not, which costs a transient second copy on
+ a cross-filesystem layout and is the price of not having a window where the
+ only copy is in flight.
+ """
+
+ sidecar_suffixes = ("-wal", "-shm")
+
+ def sidecars_of(base: Path) -> tuple[Path, ...]:
+ return tuple(base.with_name(base.name + suffix) for suffix in sidecar_suffixes)
+
+ live_sidecars = [
+ sidecar for sidecar in sidecars_of(db_path) if sidecar.is_file() and not sidecar.is_symlink()
+ ]
+
+ if not db_path.exists():
+ # Nothing to displace, but the sidecars are not therefore nothing. A
+ # migration that removed the database and left its log behind leaves a
+ # log belonging to a generation that no longer exists anywhere, and
+ # SQLite pairs a log with a database by name -- it validates the log's
+ # own checksum chain, not the database it came from. Renaming the
+ # rollback point in over that name hands the failed generation's tail to
+ # the older database and SQLite replays it, which puts back precisely
+ # what the rollback exists to remove.
+ #
+ # So the same rule the displacing branch enforces below applies here,
+ # for the same reason and by the same call: whatever arrives under this
+ # name must not inherit sidecars that are not its own. They are unlinked
+ # rather than archived because a log without its database is not
+ # recoverable evidence -- its pages need that database's header to mean
+ # anything -- while a log kept beside a name is a log something can
+ # still be paired with later.
+ for orphan in live_sidecars:
+ orphan.unlink(missing_ok=True)
+ os.replace(replacement, db_path)
+ return None
+
+ replaced = into / REPLACED_DATABASE_NAME
+ staging = into / f"{REPLACED_DATABASE_NAME}.incoming"
+
+ for stale in (staging, *sidecars_of(staging)):
+ stale.unlink(missing_ok=True)
+
+ duplications: list[tuple[Path, Path]] = [(db_path, staging)]
+ for suffix in sidecar_suffixes:
+ sidecar = db_path.with_name(db_path.name + suffix)
+ if sidecar in live_sidecars:
+ duplications.append((sidecar, staging.with_name(staging.name + suffix)))
+
+ for source, destination in duplications:
+ _duplicate_file(source, destination)
+
+ # The previous displacement's sidecars go first and its database last. A
+ # database briefly without its write-ahead log is still that database; a
+ # write-ahead log briefly without its database is a log SQLite would replay
+ # into whatever arrives under that name next.
+ for stale_sidecar in sidecars_of(replaced):
+ stale_sidecar.unlink(missing_ok=True)
+ os.replace(staging, replaced)
+ try:
+ for suffix in sidecar_suffixes:
+ staged_sidecar = staging.with_name(staging.name + suffix)
+ if staged_sidecar.exists():
+ os.replace(staged_sidecar, replaced.with_name(replaced.name + suffix))
+ except OSError:
+ # Three files cannot be renamed atomically, so one instant is unavoidable:
+ # the displaced database is committed and its write-ahead log is not. What
+ # that instant holds is a complete database as of its last checkpoint --
+ # readable, self-consistent, and missing only what the failed release
+ # committed after it. Not torn, but quieter than it should be, so it is
+ # said out loud and the log is left where it can still be recovered by
+ # hand.
+ #
+ # Neither other ordering is available. Renaming the log in first pairs
+ # generation N+1's log with generation N's database, which is the one
+ # pairing SQLite will silently replay into corruption. Unlinking the
+ # displaced database to keep the set whole-or-absent destroys BOTH
+ # generations, because the rename above has already consumed the previous
+ # displacement -- `test_no_rename_a_swap_performs_can_cost_the_live_generation`
+ # fails on exactly that, which is how this comment came to be written.
+ logger.warning(
+ "Displaced database %s committed without its %s sidecars; it is complete only to its "
+ "last checkpoint. The staged sidecars are left beside it for manual recovery.",
+ replaced.name,
+ ", ".join(sidecar_suffixes),
+ exc_info=True,
+ )
+ raise
+
+ # The displacement is made durable BEFORE the live path commits, and that
+ # ordering is the same invariant as the one above, stated against power loss
+ # instead of against an exception. A rename is visible to this process the
+ # moment it returns and durable only once its directory is synced, so leaving
+ # both syncs until after the live commit admits a crash that persists the new
+ # live pathname while the directory entry naming the displaced generation is
+ # still only in cache. That generation holds everything the failed release
+ # committed and exists nowhere else -- the rollback point is a copy of an
+ # older database, not of this one -- so losing it is the one loss this whole
+ # function is built to prevent.
+ for displaced in (replaced, *sidecars_of(replaced)):
+ if displaced.is_file():
+ _fsync_file(displaced)
+ _fsync_directory(into)
+
+ # Only now does anything leave the live path, and only the sidecars: the
+ # displaced generation already holds its own copy of them, and the database
+ # arriving under this name must not inherit them. The database itself stays
+ # until the rename below replaces it.
+ #
+ # The unlinks happen inside the guard, not ahead of it. Removing the log and
+ # removing the shared-memory file are two calls, so a failure of the second
+ # would leave the live database at its own path with its log already gone --
+ # complete only to its last checkpoint, and silently so, because the restore
+ # raises and an operator reasonably reads a failed restore as "nothing moved".
+ # The recovery below is the same answer for a failed unlink as for a failed
+ # rename, so it covers both rather than only the one that was thought of
+ # first.
+ try:
+ for sidecar in live_sidecars:
+ sidecar.unlink(missing_ok=True)
+ os.replace(replacement, db_path)
+ except Exception:
+ # The live generation goes back exactly as it was. Its database never
+ # left this path; its log did, and the displaced copy is where it is, so
+ # it is put back before the failure surfaces -- otherwise a restore that
+ # failed would still have cost the machine everything that database
+ # committed since its last checkpoint.
+ for sidecar in live_sidecars:
+ displaced_sidecar = replaced.with_name(replaced.name + sidecar.name[len(db_path.name) :])
+ if not displaced_sidecar.is_file():
+ continue
+ try:
+ _duplicate_file(displaced_sidecar, sidecar)
+ except OSError:
+ logger.warning("Failed to restore %s after an interrupted database swap", sidecar, exc_info=True)
+ raise
+ return replaced
+
+
+def restore_sqlite_backup(backup_dir: Path, db_path: Path) -> Path | None:
+ """Put a rollback point back into service, destroying nothing.
+
+ A restore is a swap, never an overwrite. The database it takes out of service
+ holds whatever the version being rolled back from committed before it failed,
+ and that is the only copy of that data anywhere; a restore that dropped it
+ would make the recovery step the unrecoverable one. It is moved into the
+ rollback point's own directory and its path is returned, for the caller to
+ record where an operator will look for it.
+
+ The rollback point itself is also left intact. Its copy is read, not moved:
+ the restore's own outcome can be the bad one, and the same point has to still
+ be there to reach for again.
+
+ The replacement is copied and verified BEFORE anything about the live
+ database changes. Every cheaper order ends the same way -- a rollback point
+ that turns out to be unreadable, discovered after the working database is
+ already gone, leaving the machine with no database rather than a failed
+ rollback.
+
+ Restoring does not grow the backup window, so it does not prune: it adds one
+ file inside a directory the window already counts, and that directory's
+ eviction takes the file with it.
+ """
+
+ source_db = backup_dir.expanduser().resolve() / "vibe.sqlite"
+ target = db_path.expanduser().resolve()
+ target.parent.mkdir(parents=True, exist_ok=True)
+ staged = target.with_name(target.name + ".restoring")
+ staged_paths = (staged, *(staged.with_name(staged.name + suffix) for suffix in ("-wal", "-shm")))
+
+ for stale in staged_paths:
+ stale.unlink(missing_ok=True)
+ try:
+ with sqlite3.connect(f"{source_db.as_uri()}?mode=ro", uri=True) as source:
+ with sqlite3.connect(staged) as destination:
+ source.backup(destination)
+ destination.execute("PRAGMA journal_mode = DELETE")
+ check = destination.execute("PRAGMA quick_check").fetchone()
+ if check != ("ok",):
+ raise sqlite3.DatabaseError(f"SQLite rollback point quick_check failed: {check!r}")
+ os.chmod(staged, 0o600)
+ _fsync_file(staged)
+ except Exception:
+ for stale in staged_paths:
+ stale.unlink(missing_ok=True)
+ raise
+
+ replaced = _swap_live_database(target, staged, into=source_db.parent)
+ # Only the live directory, because the swap already synced the rollback point
+ # it displaced into -- it has to, in the middle of its own sequence rather
+ # than after it, and a second sync out here would suggest the ordering is
+ # decided in two places when the whole reason that function exists is that it
+ # is decided in one.
+ _fsync_directory(target.parent)
+ return replaced
diff --git a/tests/test_cli_setup_status.py b/tests/test_cli_setup_status.py
index 353c8c3d3..9c01685aa 100644
--- a/tests/test_cli_setup_status.py
+++ b/tests/test_cli_setup_status.py
@@ -24,7 +24,7 @@ def test_cmd_vibe_marks_setup_when_no_enabled_platform_has_credentials(capsys) -
patch("vibe.cli.runtime.stop_ui") as stop_ui,
patch("vibe.cli.runtime.start_service", return_value=101),
patch("vibe.cli.runtime.start_ui", return_value=202),
- patch("vibe.cli.runtime.service_pid_recorded", return_value=True),
+ patch("vibe.cli.runtime.wait_for_service_ready", return_value=101),
patch("vibe.cli.runtime.write_status"),
patch("vibe.cli._write_status") as write_status,
):
@@ -48,7 +48,7 @@ def test_cmd_vibe_marks_starting_when_non_slack_platform_is_configured() -> None
patch("vibe.cli.runtime.stop_ui") as stop_ui,
patch("vibe.cli.runtime.start_service", return_value=101),
patch("vibe.cli.runtime.start_ui", return_value=202),
- patch("vibe.cli.runtime.service_pid_recorded", return_value=True),
+ patch("vibe.cli.runtime.wait_for_service_ready", return_value=101),
patch("vibe.cli.runtime.write_status"),
patch("vibe.cli._write_status") as write_status,
):
diff --git a/tests/test_controller_im_ready.py b/tests/test_controller_im_ready.py
index 1444be266..443531089 100644
--- a/tests/test_controller_im_ready.py
+++ b/tests/test_controller_im_ready.py
@@ -36,6 +36,11 @@ def test_runtime_services_start_when_post_update_notification_fails() -> None:
controller._get_idle_cleanup_timeouts = Mock(return_value=(0, 0))
controller.cleanup_task = None
controller._delivery_recovery_complete = asyncio.Event()
+ # This is the only test here that gets past the readiness boundary inside
+ # `_on_runtime_ready()`, and the announcement asks the IM runtime whether it
+ # died first. Publishing itself is a no-op in a process that does not hold
+ # the service lock, which no test process does.
+ controller._im_run_exception = None
asyncio.run(controller._on_runtime_ready())
diff --git a/tests/test_incus_regression_supervisor.py b/tests/test_incus_regression_supervisor.py
index b63fd4864..ff8f42d82 100644
--- a/tests/test_incus_regression_supervisor.py
+++ b/tests/test_incus_regression_supervisor.py
@@ -148,6 +148,7 @@ def test_main_backs_off_during_active_restart(monkeypatch, tmp_path):
monkeypatch.setattr(runtime, "start_service", lambda wait_for_ready=True, **kwargs: 100)
monkeypatch.setattr(runtime, "effective_ui_bind_host", lambda config: "127.0.0.1")
monkeypatch.setattr(runtime, "start_ui", lambda host, port, **kwargs: 333)
+ monkeypatch.setattr(runtime, "wait_for_service_ready", lambda pid, timeout: 100)
monkeypatch.setattr(runtime, "service_pid_recorded", lambda pid: pid == 100)
monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == 333) # service 100 dead, ui alive
@@ -208,3 +209,79 @@ def test_main_adopts_scoped_service_lock_holder(monkeypatch, tmp_path):
assert waited == [(100, runtime.SERVICE_SLOW_START_TIMEOUT_SECONDS)]
assert statuses[0] == ("running", 200, 333)
+
+
+def test_main_does_not_adopt_a_lock_holder_that_never_finished_starting(monkeypatch, tmp_path):
+ # Round 8, finding 1. The failure this exists for: a restart spawns a new
+ # service, that process takes the instance lock and then hangs inside its own
+ # migration, and the restart job dies. Holding the lock makes
+ # `service_pid_recorded` true, so adopting on that alone tracks the hung
+ # generation as this supervisor's healthy service -- it loops forever, never
+ # exits nonzero, and the unit's `Restart=on-failure` never fires. Readiness is
+ # the question, and `service_instance_started` is the only thing that answers
+ # it.
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ paths.ensure_data_dirs()
+ paths.get_runtime_pid_path().write_text("200", encoding="utf-8")
+ paths.get_runtime_ui_pid_path().write_text("333", encoding="utf-8")
+
+ monkeypatch.setattr(supervisor, "_config", lambda: SimpleNamespace(ui=SimpleNamespace(setup_port=8080)))
+ monkeypatch.setattr(supervisor, "_reap_child", lambda pid: None)
+ monkeypatch.setattr(supervisor, "_restart_in_progress", lambda: False)
+ monkeypatch.setattr(runtime, "start_service", lambda wait_for_ready=True, **kwargs: 100)
+ monkeypatch.setattr(runtime, "effective_ui_bind_host", lambda config: "127.0.0.1")
+ monkeypatch.setattr(runtime, "start_ui", lambda host, port, **kwargs: 333)
+ monkeypatch.setattr(runtime, "wait_for_service_ready", lambda pid, timeout: 100)
+ # 200 is alive and holds the lock -- and has not finished starting. 100, the
+ # pid this supervisor started and had ready, is gone.
+ monkeypatch.setattr(runtime, "service_pid_recorded", lambda pid: pid == 200)
+ monkeypatch.setattr(runtime, "service_instance_started", lambda pid: False)
+ monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid in {200, 333})
+ monkeypatch.setattr(runtime, "stop_ui", lambda *args, **kwargs: None)
+ monkeypatch.setattr(runtime, "stop_service", lambda *args, **kwargs: None)
+ monkeypatch.setattr(supervisor.time, "sleep", lambda _seconds: None)
+
+ assert supervisor._adoptable_service_pid(200) is False
+ rc = supervisor.main()
+
+ assert rc == 1
+ assert runtime.read_status()["state"] == "error"
+
+
+def test_main_adopts_the_replacement_once_it_finishes_starting(monkeypatch, tmp_path):
+ # The other half of the same property, and the reason it is a deferral rather
+ # than a refusal: the same pid, same lock, one iteration later, now reporting
+ # that it finished starting -- and the supervisor tracks it instead of exiting
+ # for systemd. A test that only asserted the refusal above would pass just as
+ # well against a supervisor that never adopts anything.
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ paths.ensure_data_dirs()
+ paths.get_runtime_pid_path().write_text("200", encoding="utf-8")
+ paths.get_runtime_ui_pid_path().write_text("333", encoding="utf-8")
+
+ monkeypatch.setattr(supervisor, "_config", lambda: SimpleNamespace(ui=SimpleNamespace(setup_port=8080)))
+ monkeypatch.setattr(supervisor, "_reap_child", lambda pid: None)
+ monkeypatch.setattr(supervisor, "_restart_in_progress", lambda: False)
+ monkeypatch.setattr(runtime, "start_service", lambda wait_for_ready=True, **kwargs: 100)
+ monkeypatch.setattr(runtime, "effective_ui_bind_host", lambda config: "127.0.0.1")
+ monkeypatch.setattr(runtime, "start_ui", lambda host, port, **kwargs: 333)
+ monkeypatch.setattr(runtime, "wait_for_service_ready", lambda pid, timeout: 100)
+ monkeypatch.setattr(runtime, "service_pid_recorded", lambda pid: pid == 200)
+ monkeypatch.setattr(runtime, "service_instance_started", lambda pid: pid == 200)
+ monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid in {200, 333})
+ monkeypatch.setattr(runtime, "stop_ui", lambda *args, **kwargs: None)
+ monkeypatch.setattr(runtime, "stop_service", lambda *args, **kwargs: None)
+
+ statuses: list[str] = []
+ monkeypatch.setattr(runtime, "write_status", lambda state, *a, **k: statuses.append(state))
+
+ class _Stop(Exception):
+ pass
+
+ monkeypatch.setattr(supervisor.time, "sleep", lambda _seconds: (_ for _ in ()).throw(_Stop()))
+
+ assert supervisor._adoptable_service_pid(200) is True
+ with pytest.raises(_Stop):
+ supervisor.main()
+
+ assert "error" not in statuses
diff --git a/tests/test_restart_supervisor.py b/tests/test_restart_supervisor.py
index 0d2bbef45..c4ba995c9 100644
--- a/tests/test_restart_supervisor.py
+++ b/tests/test_restart_supervisor.py
@@ -1,21 +1,45 @@
from __future__ import annotations
+import ast
+import inspect
import io
import os
+import sqlite3
+import sys
+import textwrap
import threading
from types import SimpleNamespace
import pytest
from config import paths
+from storage.backups import create_sqlite_migration_backup
from vibe import restart_supervisor
from vibe import runtime
+from vibe.upgrade import RollbackTarget
+
+
+#: The install the machine was on before the upgrade replaced it. Deliberately
+#: not this process's own interpreter: the case the launcher exists for is the
+#: `vibe-remote` -> `avibe-os` rename, where the two generations live in
+#: different directories, and a fixture reusing `sys.executable` would pass
+#: whether or not the target's install is carried anywhere at all.
+_REPLACED_INSTALL = runtime.ServiceLauncher(
+ python="/uv/tools/vibe-remote/bin/python",
+ main="/uv/tools/vibe-remote/lib/python3.13/site-packages/vibe/service_main.py",
+)
+
+
+def _rollback_target(version: str = "3.0.10") -> RollbackTarget:
+ """The install to go back to, as the upgrade captured it before installing."""
+
+ return RollbackTarget(version=version, package="vibe-remote", launcher=_REPLACED_INSTALL)
def _fake_start_runtime(calls, service_pid: int = 222, ui_pid: int = 333):
calls.append("start_runtime")
runtime.write_status("running", f"pid={service_pid}", service_pid, ui_pid)
- return service_pid, ui_pid
+ return restart_supervisor.StartedRuntime(service_pid, ui_pid, ("127.0.0.1", 5123))
def _fake_stop_runtime(calls, *, ui_stopped=True, ui_pid=None, service_stopped=True):
@@ -133,6 +157,72 @@ def test_schedule_restart_passes_memory_ui_secret_only_through_stdin(monkeypatch
assert secret not in calls["kwargs"]["env"].values()
+def test_the_argv_the_job_builds_is_the_argv_the_entry_point_accepts(monkeypatch, tmp_path):
+ """One command, one parser, proved by running the built argv through the CLI.
+
+ `schedule_restart` builds a command line and a detached `vibe` process parses
+ it back. For a while both ends were owned by different parsers -- this module
+ built the `--rollback-*` flags, `vibe/cli.py` declared the ones it knew about,
+ and the top-level parser ran first. So the flags were not merely unsupported,
+ they were rejected: the child exited on `unrecognized arguments`, the seeded
+ "scheduled" record was never overwritten by anyone, and the machine stayed on
+ the release that could not start. Every test in this file called
+ `restart_supervisor.main([...])` directly, so nothing crossed that seam.
+
+ Asserted as a round trip rather than as a list of flags: the spawned argv is
+ taken exactly as `Popen` received it and handed to the real entry point, so a
+ flag added to the builder later is covered without touching this test.
+ """
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ paths.ensure_data_dirs()
+ spawned = {}
+
+ monkeypatch.setattr(restart_supervisor, "get_restart_invocation_command", lambda vibe_path=None: ["/bin/vibe", "restart"])
+ monkeypatch.setattr(restart_supervisor, "get_restart_environment", lambda vibe_path=None: None)
+ monkeypatch.setattr(restart_supervisor, "get_safe_cwd", lambda: str(tmp_path))
+ monkeypatch.setattr(restart_supervisor, "_prune_restart_logs", lambda: None)
+
+ def fake_popen(command, **kwargs):
+ spawned["command"] = command
+ return SimpleNamespace(pid=45678)
+
+ monkeypatch.setattr(restart_supervisor.subprocess, "Popen", fake_popen)
+
+ rollback_to = _rollback_target("3.0.10")
+ restart_supervisor.schedule_restart(
+ delay_seconds=0,
+ vibe_path="/bin/vibe",
+ trigger="upgrade",
+ scope="service",
+ prepare_show_runtime=True,
+ rollback_to=rollback_to,
+ )
+
+ from vibe import cli
+
+ ran = {}
+
+ def fake_run_restart_job(**kwargs):
+ ran.update(kwargs)
+ return 0
+
+ monkeypatch.setattr(cli, "cache_running_vibe_path", lambda: None)
+ monkeypatch.setattr(restart_supervisor, "_run_restart_job", fake_run_restart_job)
+ monkeypatch.setattr(sys, "argv", list(spawned["command"]))
+
+ with pytest.raises(SystemExit) as exit_info:
+ cli.main()
+
+ assert exit_info.value.code == 0
+ # Not just "it parsed": the rollback target has to arrive whole, because a
+ # partially-carried one is the failure this whole path exists to prevent.
+ assert ran["rollback_to"] == rollback_to
+ assert ran["trigger"] == "upgrade"
+ assert ran["scope"] == "service"
+ assert ran["prepare_show_runtime"] is True
+
+
def test_schedule_restart_marks_status_failed_when_spawn_fails(monkeypatch, tmp_path):
# The "scheduled" status is seeded before spawning; if the spawn fails, no
# child will overwrite it, so schedule_restart must mark it failed (otherwise
@@ -212,6 +302,7 @@ def test_restart_job_stops_and_starts_service(monkeypatch, tmp_path):
monkeypatch.setattr(restart_supervisor, "_wait_for_service_lock_release", lambda: True)
monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == 222)
monkeypatch.setattr(runtime, "service_pid_recorded", lambda pid: pid == 222)
+ monkeypatch.setattr(runtime, "service_instance_started", lambda pid: pid == 222)
rc = restart_supervisor._run_restart_job(job_id="jobabc", delay_seconds=0, vibe_path="/bin/vibe", trigger="test")
@@ -247,6 +338,7 @@ def test_restart_job_uses_lock_holder_when_pidfile_is_missing(monkeypatch, tmp_p
monkeypatch.setattr(restart_supervisor, "_wait_for_service_lock_release", lambda: True)
monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == 222)
monkeypatch.setattr(runtime, "service_pid_recorded", lambda pid: pid == 222)
+ monkeypatch.setattr(runtime, "service_instance_started", lambda pid: pid == 222)
rc = restart_supervisor._run_restart_job(job_id="joblockowner", delay_seconds=0, vibe_path="/bin/vibe", trigger="test")
@@ -276,6 +368,7 @@ def test_restart_job_prepares_show_runtime_after_service_start(monkeypatch, tmp_
monkeypatch.setattr(restart_supervisor.subprocess, "run", fake_run)
monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == 222)
monkeypatch.setattr(runtime, "service_pid_recorded", lambda pid: pid == 222)
+ monkeypatch.setattr(runtime, "service_instance_started", lambda pid: pid == 222)
rc = restart_supervisor._run_restart_job(
job_id="jobruntime",
@@ -306,6 +399,7 @@ def test_restart_job_schedules_pending_followup_after_success(monkeypatch, tmp_p
monkeypatch.setattr(restart_supervisor, "_wait_for_service_lock_release", lambda: True)
monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == 222)
monkeypatch.setattr(runtime, "service_pid_recorded", lambda pid: pid == 222)
+ monkeypatch.setattr(runtime, "service_instance_started", lambda pid: pid == 222)
original_schedule_restart = restart_supervisor.schedule_restart
@@ -386,6 +480,7 @@ def test_restart_job_continues_when_old_pid_already_exited(monkeypatch, tmp_path
monkeypatch.setattr(restart_supervisor, "_remaining_service_pids_after_stop", lambda: [])
monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == 222)
monkeypatch.setattr(runtime, "service_pid_recorded", lambda pid: pid == 222)
+ monkeypatch.setattr(runtime, "service_instance_started", lambda pid: pid == 222)
rc = restart_supervisor._run_restart_job(job_id="joboldgone", delay_seconds=0, vibe_path="/bin/vibe", trigger="test")
@@ -439,10 +534,13 @@ def test_restart_job_adopts_slow_starting_service_pid(monkeypatch, tmp_path):
paths.get_runtime_pid_path().unlink()
except FileNotFoundError:
pass
- return 222, 333
+ return restart_supervisor.StartedRuntime(222, 333, ("127.0.0.1", 5123))
monkeypatch.setattr(restart_supervisor, "_start_runtime_processes", slow_start_runtime)
- monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == 222)
+ # Both halves of the generation this start launched are alive: the status
+ # carries a UI pid only for a UI that is still there, so a stub that answered
+ # for the service alone would be describing a different machine.
+ monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid in {222, 333})
monkeypatch.setattr(runtime, "service_pid_recorded", lambda pid: False)
monkeypatch.setattr(runtime, "wait_for_service_ready", lambda pid, timeout: 222 if pid == 222 else None)
@@ -500,6 +598,7 @@ def test_restart_job_waits_for_service_lock_release_before_start(monkeypatch, tm
monkeypatch.setattr(runtime, "service_instance_lock_available", service_instance_lock_available)
monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == 222)
monkeypatch.setattr(runtime, "service_pid_recorded", lambda pid: pid == 222)
+ monkeypatch.setattr(runtime, "service_instance_started", lambda pid: pid == 222)
monkeypatch.setattr(restart_supervisor.time, "sleep", lambda _seconds: None)
rc = restart_supervisor._run_restart_job(job_id="joblock", delay_seconds=0, vibe_path="/bin/vibe", trigger="test")
@@ -569,17 +668,41 @@ def test_start_runtime_processes_starts_service_and_ui(monkeypatch, tmp_path):
monkeypatch.setattr(runtime, "service_pid_recorded", lambda pid: pid == 222)
monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == 222)
- service_pid, ui_pid = restart_supervisor._start_runtime_processes()
+ started = restart_supervisor._start_runtime_processes()
- assert service_pid == 222
- assert ui_pid == 333
+ assert started.service_pid == 222
+ assert started.ui_pid == 333
+ # The health target is resolved here or nowhere: this is the only place that
+ # loads the config to decide the bind host and port, so it is the only answer
+ # to "where is the UI" that cannot disagree with where the UI was started.
+ assert started.ui_health_target == ("0.0.0.0", 5123)
assert calls[:2] == ["ensure_data_dirs", "load_config"]
assert calls[2][:3] == ("start_service", False, 0)
assert calls[3] == ("bind_host", config)
assert calls[4][:4] == ("start_ui", "0.0.0.0", 5123, False)
assert calls[2][3]["memory_ui_secret"] == calls[4][4]["memory_ui_secret"]
+
+ # Every process this helper starts comes from the one install it was given,
+ # asserted over whatever it started rather than over two named spawns: the
+ # service and the UI are two halves of one generation, and a rollback that
+ # started one from the restored install and the other from the replaced one
+ # is a state neither release was ever run in. `None` is "this process",
+ # which is the right answer for every restart except a rollback.
+ def started_from() -> list:
+ return [call[-1].get("launcher") for call in calls if call[0] in ("start_service", "start_ui")]
+
+ assert started_from() == [None, None]
+
+ calls.clear()
+ restart_supervisor._start_runtime_processes(launcher=_REPLACED_INSTALL)
+ assert started_from() == [_REPLACED_INSTALL, _REPLACED_INSTALL]
+
status = runtime.read_status()
- assert status["state"] == "running"
+ # "starting", not "running", and the stubbed lock says the pid is recorded.
+ # This helper spawns; it does not observe. Its callers wait for the service's
+ # own report and promote the status themselves, so a claim of "running" from
+ # here is a claim about a process that has not migrated the database yet.
+ assert status["state"] == "starting"
assert status["service_pid"] == 222
assert status["ui_pid"] == 333
@@ -670,6 +793,7 @@ def test_restart_job_service_scope_keeps_ui(monkeypatch, tmp_path):
monkeypatch.setattr(restart_supervisor, "_wait_for_service_lock_release", lambda: True)
monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == 222)
monkeypatch.setattr(runtime, "service_pid_recorded", lambda pid: pid == 222)
+ monkeypatch.setattr(runtime, "service_instance_started", lambda pid: pid == 222)
rc = restart_supervisor._run_restart_job(
job_id="jobsvc", delay_seconds=0, vibe_path="/bin/vibe", trigger="web-ui", scope="service"
@@ -681,3 +805,464 @@ def test_restart_job_service_scope_keeps_ui(monkeypatch, tmp_path):
status = runtime.read_json(runtime.get_restart_status_path())
assert status["ok"] is True
assert status["scope"] == "service"
+
+
+def _seed_state_database(db_path):
+ """The database as the machine had it before the upgrade touched anything."""
+
+ db_path.parent.mkdir(parents=True, exist_ok=True)
+ with sqlite3.connect(db_path) as conn:
+ conn.execute("create table if not exists alembic_version (version_num varchar(32) not null)")
+ conn.execute("delete from alembic_version")
+ conn.execute("insert into alembic_version (version_num) values ('20260806_0047')")
+ conn.execute("create table payload (value text)")
+ conn.execute("insert into payload (value) values ('before the upgrade')")
+
+
+def _payload_rows(db_path) -> list[str]:
+ with sqlite3.connect(db_path) as conn:
+ return [row[0] for row in conn.execute("select value from payload order by rowid")]
+
+
+def _upgrade_restart_that_dies_after_migrating(
+ monkeypatch,
+ tmp_path,
+ *,
+ service_running: bool,
+ ui_serving: bool = True,
+):
+ """Arm the incident this whole path exists for, and hand back what it did.
+
+ The new version stops the old one, starts, takes its pre-migration backup,
+ commits a row, and then dies without ever holding the service lock. Only the
+ two processes and the package index are stubbed: the database, the backup
+ window, and the watermark the job reads out of it are the real ones, because
+ they are the things the rollback has to get right.
+ """
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ paths.ensure_data_dirs()
+ paths.get_runtime_pid_path().write_text("111", encoding="utf-8")
+ db_path = paths.get_sqlite_state_path()
+ _seed_state_database(db_path)
+
+ calls: list[str] = []
+ installs: list[list[str]] = []
+ launchers: list = []
+ observed_by_the_rolled_back_version: list[list[str]] = []
+
+ def start(start_ui=True, launcher=None):
+ calls.append("start_runtime")
+ launchers.append(launcher)
+ if calls.count("start_runtime") == 1:
+ # The new version gets far enough to take its rollback point and
+ # commit, then dies without ever holding the lock.
+ create_sqlite_migration_backup(db_path, backups_dir=paths.get_state_backups_dir())
+ with sqlite3.connect(db_path) as conn:
+ conn.execute("insert into payload (value) values ('committed by the new version')")
+ raise RuntimeError("service refused to start")
+ observed_by_the_rolled_back_version.append(_payload_rows(db_path))
+ return _fake_start_runtime([], service_pid=222, ui_pid=333)
+
+ def run(command, **_kwargs):
+ calls.append("install")
+ installs.append(list(command))
+ return SimpleNamespace(returncode=0, stdout="", stderr="")
+
+ monkeypatch.setattr(restart_supervisor, "_stop_runtime_for_restart", lambda stop_ui=True: _fake_stop_runtime(calls))
+ monkeypatch.setattr(restart_supervisor, "_start_runtime_processes", start)
+ monkeypatch.setattr(restart_supervisor, "_wait_for_service_lock_release", lambda: True)
+ monkeypatch.setattr(restart_supervisor, "get_safe_cwd", lambda: str(tmp_path))
+ monkeypatch.setattr(restart_supervisor.subprocess, "run", run)
+ monkeypatch.setattr(runtime, "verified_service_running", lambda: service_running)
+ monkeypatch.setattr(runtime, "wait_for_service_ready", lambda pid, timeout=None: pid)
+ # The machine as this failure actually leaves it: the version that died in
+ # its migration is gone, and so nothing of it is still holding the database
+ # open. Stated here rather than left to the host's real process table, which
+ # a test may not read and must never depend on.
+ monkeypatch.setattr(restart_supervisor, "_remaining_service_pids_after_stop", list)
+ monkeypatch.setattr(runtime, "ui_pid_file_points_to_running_ui", lambda *args, **kwargs: False)
+ # The UI the rollback restarts, and whether it answers. Both are stubbed
+ # rather than left to the host: `_ui_is_serving` opens a real socket, and a
+ # test that let it would wait out the timeout against whatever happens to be
+ # listening on the developer's machine.
+ ui_probes: list[tuple[str, int]] = []
+ monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == 333)
+ monkeypatch.setattr(
+ runtime,
+ "wait_for_ui_server",
+ lambda host, port, timeout=None: ui_probes.append((host, port)) or ui_serving,
+ )
+
+ return SimpleNamespace(
+ db_path=db_path,
+ calls=calls,
+ installs=installs,
+ launchers=launchers,
+ ui_probes=ui_probes,
+ observed_by_the_rolled_back_version=observed_by_the_rolled_back_version,
+ )
+
+
+def test_a_rollback_whose_ui_never_serves_is_not_reported_as_recovered(monkeypatch, tmp_path):
+ """A live pid is not a serving UI, and this job is the one that cannot guess.
+
+ The service came back and holds the lock; the UI process was started and is
+ alive, and never answers. Everything a pid-based check can see says the
+ machine is up, which is exactly the evidence this record must not accept:
+ nobody is watching an unattended rollback, so the half that is dark has to be
+ the half that is reported. The service pid is still recorded either way --
+ the run failed, it did not vanish.
+ """
+
+ armed = _upgrade_restart_that_dies_after_migrating(
+ monkeypatch, tmp_path, service_running=False, ui_serving=False
+ )
+
+ restart_supervisor._run_restart_job(
+ job_id="jobdark", delay_seconds=0, vibe_path="/bin/vibe", trigger="upgrade", rollback_to=_rollback_target()
+ )
+
+ rollback = runtime.read_json(runtime.get_restart_status_path())["rollback"]
+ assert rollback["state"] == "failed"
+ assert rollback["ui"] == {"pid": 333, "serving": False}
+ assert rollback["service_pid"] == 222
+ assert "Web UI" in rollback["error"]
+ # It reached the UI at all, rather than failing for want of a probe.
+ assert armed.ui_probes
+
+
+def test_a_restart_that_leaves_nothing_running_puts_the_old_version_back(monkeypatch, tmp_path):
+ """The property the change exists for: an upgrade cannot end with a dark instance.
+
+ Install, then restore, then start -- and the started version has to find the
+ database the version it is reads. That last part is why the order is asserted
+ through what the started process sees rather than through a call log: a
+ restore that lands after the start is a restore that lands after the service
+ has already opened a schema it cannot read.
+ """
+
+ armed = _upgrade_restart_that_dies_after_migrating(monkeypatch, tmp_path, service_running=False)
+
+ rc = restart_supervisor._run_restart_job(
+ job_id="jobroll", delay_seconds=0, vibe_path="/bin/vibe", trigger="upgrade", rollback_to=_rollback_target()
+ )
+
+ # The restart still failed, and still says so: a rollback recovers the
+ # machine, it does not turn a failed upgrade into a successful one.
+ assert rc == 1
+ status = runtime.read_json(runtime.get_restart_status_path())
+ assert status["ok"] is False
+ assert "start runtime failed: service refused to start" in status["error"]
+
+ # Nothing of the failed generation is left alive across the install and the
+ # restore: the second stop is the rollback's own, and without it a process
+ # that never reached the lock is still holding the database file open when
+ # the restore rewrites it -- and is what the final start would adopt.
+ assert armed.calls == ["stop_runtime", "start_runtime", "stop_runtime", "install", "start_runtime"]
+ # The distribution the OLD release was published as, not the one this build
+ # is: a machine that predates the `vibe-remote` -> `avibe-os` rename has no
+ # `avibe-os==3.0.10` to go back to, and pinning one is an index round-trip
+ # that fails and leaves the instance dark.
+ assert "vibe-remote==3.0.10" in armed.installs[0]
+ assert armed.observed_by_the_rolled_back_version == [["before the upgrade"]]
+ assert _payload_rows(armed.db_path) == ["before the upgrade"]
+
+ # The rollback starts the install it just reinstalled, not the one this job
+ # is running out of. An upgrade spawns the job through the `vibe` on PATH,
+ # which the install has already replaced, so by now `sys.executable` names
+ # the failed generation -- and across the `vibe-remote` -> `avibe-os` rename
+ # the two are different directories, both present, both startable. `None`
+ # for the first start is the upgrade's own: it is what should run next.
+ assert armed.launchers == [None, _REPLACED_INSTALL]
+
+ rollback = status["rollback"]
+ assert rollback["target_version"] == "3.0.10"
+ assert rollback["state"] == "succeeded"
+ assert rollback["install"]["ok"] is True
+ assert rollback["database"]["restored"] is True
+ assert runtime.read_status()["service_pid"] == 222
+
+
+def test_a_service_still_holding_the_lock_is_never_rolled_back_underneath(monkeypatch, tmp_path):
+ """The same failure, the opposite answer, decided by one fact: the lock.
+
+ A restart that failed while a service is still serving has not produced the
+ state this recovery exists for, and reinstalling and restoring underneath
+ that live process is the damage rather than the repair. Nothing about the
+ failure itself distinguishes the two cases -- only what is holding the lock
+ when it is over does.
+ """
+
+ armed = _upgrade_restart_that_dies_after_migrating(monkeypatch, tmp_path, service_running=True)
+
+ rc = restart_supervisor._run_restart_job(
+ job_id="jobheld", delay_seconds=0, vibe_path="/bin/vibe", trigger="upgrade", rollback_to=_rollback_target()
+ )
+
+ assert rc == 1
+ assert armed.calls == ["stop_runtime", "start_runtime"]
+ assert armed.installs == []
+ assert _payload_rows(armed.db_path) == ["before the upgrade", "committed by the new version"]
+ status = runtime.read_json(runtime.get_restart_status_path())
+ assert status["rollback"] == {"target_version": "3.0.10", "state": "skipped", "reason": "service_running"}
+
+
+def test_a_service_that_took_the_lock_and_then_died_is_rolled_back(monkeypatch, tmp_path):
+ """The incident this path exists for, in the shape it actually has.
+
+ The lock is taken BEFORE the database is migrated -- it has to be, since the
+ migration is what it excludes. So a release that fails on its migration does
+ hold the lock, for the seconds it takes to get there and die, and a job that
+ stopped at "the pid is recorded" spends those seconds writing
+ `state: succeeded` about an instance that ends them with nothing running.
+
+ Which makes the recorded pid unusable as the finish line, in the one case
+ that matters. What ends the wait is the service saying it is up, which it
+ says after the migration.
+ """
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ paths.ensure_data_dirs()
+ paths.get_runtime_pid_path().write_text("111", encoding="utf-8")
+ db_path = paths.get_sqlite_state_path()
+ _seed_state_database(db_path)
+ calls: list[str] = []
+ installs: list[list[str]] = []
+ launchers: list = []
+ observed_by_the_rolled_back_version: list[list[str]] = []
+ alive = {222: True, 333: True, 444: True}
+
+ def start(start_ui=True, launcher=None):
+ calls.append("start_runtime")
+ launchers.append(launcher)
+ if calls.count("start_runtime") == 1:
+ # The new version takes its rollback point, commits, and is now in
+ # the migration that will kill it -- all of it under the lock.
+ create_sqlite_migration_backup(db_path, backups_dir=paths.get_state_backups_dir())
+ with sqlite3.connect(db_path) as conn:
+ conn.execute("insert into payload (value) values ('committed by the new version')")
+ runtime.write_status("running", "pid=222", 222, 333)
+ return restart_supervisor.StartedRuntime(222, 333, ("127.0.0.1", 5123))
+ observed_by_the_rolled_back_version.append(_payload_rows(db_path))
+ return _fake_start_runtime([], service_pid=444, ui_pid=333)
+
+ def started(pid: int) -> bool:
+ # Asking is what finds out: the migration failed, so by the time anyone
+ # looks a second time the holder is gone and the lock with it.
+ alive[pid] = False
+ return pid == 444
+
+ def run(command, **_kwargs):
+ calls.append("install")
+ installs.append(list(command))
+ return SimpleNamespace(returncode=0, stdout="", stderr="")
+
+ monkeypatch.setattr(restart_supervisor, "_stop_runtime_for_restart", lambda stop_ui=True: _fake_stop_runtime(calls))
+ monkeypatch.setattr(restart_supervisor, "_start_runtime_processes", start)
+ monkeypatch.setattr(restart_supervisor, "_wait_for_service_lock_release", lambda: True)
+ monkeypatch.setattr(restart_supervisor, "get_safe_cwd", lambda: str(tmp_path))
+ monkeypatch.setattr(restart_supervisor.subprocess, "run", run)
+ monkeypatch.setattr(runtime, "pid_alive", lambda pid: alive.get(pid, False))
+ monkeypatch.setattr(runtime, "service_pid_recorded", lambda pid: True)
+ monkeypatch.setattr(runtime, "service_instance_started", started)
+ monkeypatch.setattr(runtime, "verified_service_running", lambda: False)
+ monkeypatch.setattr(runtime, "wait_for_ui_server", lambda host, port, timeout=None: True)
+
+ rc = restart_supervisor._run_restart_job(
+ job_id="jobdark", delay_seconds=0, vibe_path="/bin/vibe", trigger="upgrade", rollback_to=_rollback_target()
+ )
+
+ assert rc == 3
+ status = runtime.read_json(runtime.get_restart_status_path())
+ assert status["ok"] is False
+ assert "did not finish starting" in status["error"]
+ assert status["rollback"]["state"] == "succeeded"
+ assert "vibe-remote==3.0.10" in installs[0]
+ assert observed_by_the_rolled_back_version == [["before the upgrade"]]
+ assert _payload_rows(db_path) == ["before the upgrade"]
+
+
+def test_a_generation_that_was_already_gone_is_quiesced(monkeypatch, tmp_path):
+ """The ordinary case, and the one a stop report gets exactly backwards.
+
+ A version that died in its migration has nothing left to kill, so
+ `stop_service` reports that it stopped nothing -- the same answer it gives
+ for a process that refused to die, because the two states are
+ indistinguishable from the report and distinguishable only from the machine.
+ A rollback gated on the report therefore refuses to run on the failure it was
+ built for, which is the one where the instance is already dark.
+ """
+
+ armed = _upgrade_restart_that_dies_after_migrating(monkeypatch, tmp_path, service_running=False)
+ monkeypatch.setattr(
+ restart_supervisor,
+ "_stop_runtime_for_restart",
+ lambda stop_ui=True: _fake_stop_runtime(armed.calls, service_stopped=False, ui_stopped=False),
+ )
+
+ rc = restart_supervisor._run_restart_job(
+ job_id="jobgone", delay_seconds=0, vibe_path="/bin/vibe", trigger="upgrade", rollback_to=_rollback_target()
+ )
+
+ assert rc == 1
+ status = runtime.read_json(runtime.get_restart_status_path())
+ assert status["rollback"]["quiesced"] is True
+ assert status["rollback"]["state"] == "succeeded"
+ assert _payload_rows(armed.db_path) == ["before the upgrade"]
+
+
+ "survivor",
+ [
+ {"service_pids": [999]},
+ {"ui_alive": True},
+ ],
+ ids=["a-service-process-of-the-failed-generation", "a-ui-process-that-would-not-die"],
+)
+def test_a_failed_generation_that_will_not_stop_stops_the_rollback_instead(monkeypatch, tmp_path, survivor):
+ """Quiescing is a step with an outcome, not a step with a side effect.
+
+ A process that resists termination is the entire reason the stop is there, so
+ a rollback that ran it and then carried on regardless would be at its most
+ confident in the only case it is about. What follows makes that concrete: the
+ restore rewrites a database file that process holds open, and the final start
+ adopts its live recorded pid instead of launching what was just reinstalled --
+ so the rollback would report success for the version it was rolling back from,
+ over a database it had corrupted underneath it.
+
+ So the database is what this asserts on. Untouched is the whole claim; the
+ status record only has to be readable enough to send someone to look.
+ """
+
+ armed = _upgrade_restart_that_dies_after_migrating(monkeypatch, tmp_path, service_running=False)
+ # Whichever process survived, and whatever the stop said about it: what
+ # decides is the machine afterwards, so the stop is left reporting success.
+ monkeypatch.setattr(
+ restart_supervisor, "_remaining_service_pids_after_stop", lambda: list(survivor.get("service_pids", []))
+ )
+ monkeypatch.setattr(
+ runtime, "ui_pid_file_points_to_running_ui", lambda *args, **kwargs: bool(survivor.get("ui_alive"))
+ )
+
+ rc = restart_supervisor._run_restart_job(
+ job_id="jobstuck", delay_seconds=0, vibe_path="/bin/vibe", trigger="upgrade", rollback_to=_rollback_target()
+ )
+
+ assert rc == 1
+ status = runtime.read_json(runtime.get_restart_status_path())
+ assert status["rollback"]["state"] == "failed"
+ assert status["rollback"]["quiesced"] is False
+ assert "still running" in status["rollback"]["error"]
+ # Nothing was installed and nothing was restored: the machine is left exactly
+ # as the failed upgrade left it, which is recoverable by hand.
+ assert [command for command in armed.installs if any("3.0.10" in argument for argument in command)] == []
+ assert _payload_rows(armed.db_path) == ["before the upgrade", "committed by the new version"]
+
+
+def test_a_restart_with_no_version_to_go_back_to_changes_nothing(monkeypatch, tmp_path):
+ """A plain restart is already running what it would reinstall.
+
+ It has no rollback target, so the failure is left exactly as it happened for
+ whoever looks at it -- including the database, which nothing here is entitled
+ to move backwards. The absent record is the readable part: a failed restart
+ with a `rollback_to` and no `rollback` was armed and killed before it could
+ recover, which is a different incident from one that was never recoverable.
+ """
+
+ armed = _upgrade_restart_that_dies_after_migrating(monkeypatch, tmp_path, service_running=False)
+
+ rc = restart_supervisor._run_restart_job(job_id="jobplain", delay_seconds=0, vibe_path="/bin/vibe", trigger="cli")
+
+ assert rc == 1
+ assert armed.calls == ["stop_runtime", "start_runtime"]
+ assert armed.installs == []
+ assert _payload_rows(armed.db_path) == ["before the upgrade", "committed by the new version"]
+ status = runtime.read_json(runtime.get_restart_status_path())
+ assert status["rollback_to"] is None
+ assert "rollback" not in status
+
+
+def test_no_failure_branch_can_end_the_job_without_the_rollback_decision():
+ """Whether to roll back is asked once, not per failure branch.
+
+ A list of the branches that deserve a rollback is complete only until the
+ next branch is added, and the one nobody remembered is exactly the one that
+ leaves an instance dark. So the job has a single failure exit, and this
+ asserts that structurally: any new branch reaching the raw `_fail` directly
+ fails here, at the moment it is written, rather than in the incident.
+ """
+
+ tree = ast.parse(textwrap.dedent(inspect.getsource(restart_supervisor._run_restart_job)))
+ wrapper = next(
+ node for node in ast.walk(tree) if isinstance(node, ast.FunctionDef) and node.name == "fail"
+ )
+ inside_the_wrapper = {id(node) for node in ast.walk(wrapper)}
+ calls = [
+ node
+ for node in ast.walk(tree)
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id == "_fail"
+ ]
+
+ assert [node for node in calls if id(node) in inside_the_wrapper], "the wrapper is what ends a failed job"
+ assert [node for node in calls if id(node) not in inside_the_wrapper] == []
+
+
+def test_a_recoverable_restart_carries_its_rollback_target_into_the_job(monkeypatch, tmp_path):
+ """The target survives the process boundary the restart is built on.
+
+ `schedule_restart` spawns a detached job, so the install to go back to has to
+ travel as argv and be read back by the job's own parser. Asserted as a round
+ trip rather than as two independent expectations: the two sides are what can
+ drift, and a flag renamed on one of them would leave every rollback silently
+ disarmed while both halves still look right.
+
+ Asserted as equality against the whole target rather than field by field.
+ Argv is the one place the fields are apart, so it is the one place they can
+ be separated by accident -- a version arriving without its distribution pins
+ a name the old release never had, and one arriving without its install
+ reinstalls the right release and then starts the wrong one -- and a field
+ added later is carried by this test without it being edited, or fails it.
+ """
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ paths.ensure_data_dirs()
+ commands: list[list[str]] = []
+
+ monkeypatch.setattr(restart_supervisor, "get_restart_invocation_command", lambda vibe_path=None: ["/bin/vibe", "restart"])
+ monkeypatch.setattr(restart_supervisor, "get_restart_environment", lambda vibe_path=None: {"PATH": "/bin"})
+ monkeypatch.setattr(restart_supervisor, "get_safe_cwd", lambda: str(tmp_path))
+ monkeypatch.setattr(restart_supervisor, "_prune_restart_logs", lambda: None)
+
+ def fake_popen(command, **kwargs):
+ commands.append(command)
+ return SimpleNamespace(pid=4242)
+
+ monkeypatch.setattr(restart_supervisor.subprocess, "Popen", fake_popen)
+
+ target = _rollback_target()
+ restart_supervisor.schedule_restart(
+ delay_seconds=0,
+ vibe_path="/bin/vibe",
+ trigger="upgrade",
+ rollback_to=target,
+ )
+ upgrade_argv = commands[-1]
+ restart_supervisor.schedule_restart(delay_seconds=0, vibe_path="/bin/vibe", trigger="cli")
+ plain_argv = commands[-1]
+ assert [argument for argument in plain_argv if argument.startswith("--rollback")] == []
+
+ parsed: dict = {}
+ monkeypatch.setattr(restart_supervisor, "_run_restart_job", lambda **kwargs: parsed.update(kwargs) or 0)
+ assert restart_supervisor.main(upgrade_argv[2:]) == 0
+ assert parsed["rollback_to"] == target
+
+ parsed.clear()
+ assert restart_supervisor.main(plain_argv[2:]) == 0
+ assert parsed["rollback_to"] is None
+
+ # A partial set is refused rather than completed from this process. The job
+ # runs the release the rollback is undoing, so "fill in the missing install
+ # from here" is the exact wrong answer, and a silent one.
+ with pytest.raises(SystemExit):
+ restart_supervisor.main(["--job-id", "jobpartial", "--rollback-to", "3.0.10"])
diff --git a/tests/test_runtime_scope_bootstrap.py b/tests/test_runtime_scope_bootstrap.py
index eec3141e0..546d10444 100644
--- a/tests/test_runtime_scope_bootstrap.py
+++ b/tests/test_runtime_scope_bootstrap.py
@@ -263,16 +263,39 @@ class StartScopedServiceResultTests(unittest.TestCase):
class WaitForServiceReadyTests(unittest.TestCase):
- """Public wait that resolves the authoritative owner for any caller."""
+ """Public wait: resolve the authoritative owner, then wait for it to be up."""
def test_returns_resolved_owner_when_spawn_pid_is_a_wrapper(self):
# spawn pid never records itself; the lock holder is a different pid.
with ExitStack() as stack:
stack.enter_context(patch("vibe.runtime.service_pid_recorded", side_effect=[False, True]))
stack.enter_context(patch("vibe.runtime._adopt_scoped_service_owner", return_value=999))
+ stack.enter_context(patch("vibe.runtime.service_instance_started", return_value=True))
stack.enter_context(patch("vibe.runtime.time.sleep"))
self.assertEqual(runtime.wait_for_service_ready(111, 5.0), 999)
+ def test_an_owner_that_holds_the_lock_and_dies_is_never_reported_ready(self):
+ # The lock is taken before the database is migrated, so this is what a
+ # release with a bad migration looks like from out here: a real owner,
+ # briefly, and then nothing. Reporting it ready is what leaves an
+ # upgraded instance dark with a restart recorded as succeeded.
+ with ExitStack() as stack:
+ stack.enter_context(patch("vibe.runtime.service_pid_recorded", return_value=True))
+ stack.enter_context(patch("vibe.runtime.service_instance_started", return_value=False))
+ stack.enter_context(patch("vibe.runtime.pid_alive", return_value=False))
+ stack.enter_context(patch("vibe.runtime.time.sleep"))
+ self.assertIsNone(runtime.wait_for_service_ready(111, 5.0))
+
+ def test_an_owner_still_starting_is_waited_out_rather_than_declared_ready(self):
+ times = iter([0.0, 0.0, 10.0])
+ with ExitStack() as stack:
+ stack.enter_context(patch("vibe.runtime.service_pid_recorded", return_value=True))
+ stack.enter_context(patch("vibe.runtime.service_instance_started", return_value=False))
+ stack.enter_context(patch("vibe.runtime.pid_alive", return_value=True))
+ stack.enter_context(patch("vibe.runtime.time.sleep"))
+ stack.enter_context(patch("vibe.runtime.time.monotonic", side_effect=lambda: next(times)))
+ self.assertIsNone(runtime.wait_for_service_ready(111, 5.0))
+
def test_returns_none_when_no_owner_appears(self):
times = iter([0.0, 0.0, 10.0])
with ExitStack() as stack:
diff --git a/tests/test_runtime_service_lock.py b/tests/test_runtime_service_lock.py
index e4df97414..3a168880e 100644
--- a/tests/test_runtime_service_lock.py
+++ b/tests/test_runtime_service_lock.py
@@ -1,3 +1,4 @@
+import json
import os
import sys
import tempfile
@@ -22,8 +23,20 @@ class RuntimeServiceLockTests(unittest.TestCase):
# pin it off here. The scoped path has its own dedicated tests.
self._no_scope = patch("vibe.runtime.maybe_systemd_scope_prefix", return_value=[])
self._no_scope.start()
+ # Every test in this class asks WHICH process is the service -- reuse a
+ # recorded pid, ignore an unrelated one, refuse a second instance. None of
+ # them asks whether that process finished starting, and they mock the pid
+ # into existence without a lock record for it to report through, so the
+ # readiness gate `start_service()` now applies would wait out its full
+ # timeout on a process that does not exist. Stubbing it to the pid it was
+ # handed keeps these tests on the public entry point while confining them
+ # to their own question; the gate itself is covered by
+ # `ServiceReadinessGateTests` below, which deliberately does not stub it.
+ self._ready = patch("vibe.runtime.wait_for_service_ready", side_effect=lambda pid, timeout=None: pid)
+ self._ready.start()
def tearDown(self):
+ self._ready.stop()
self._no_scope.stop()
self._extra_service_pids.stop()
@@ -299,9 +312,16 @@ class RuntimeServiceLockTests(unittest.TestCase):
pid = runtime.start_service()
self.assertEqual(pid, 78901)
- wait_for_ready.assert_called_once_with(
- 67890,
- timeout=runtime.SERVICE_SLOW_START_TIMEOUT_SECONDS,
+ # Which pid the adopted scope is waited on is this test's subject.
+ # How long it may be waited on is not a constant any more but what
+ # the one start budget has left once the lock phase is done, so the
+ # bound is asserted as a bound; `ServiceReadinessGateTests` pins how
+ # it is spent.
+ wait_for_ready.assert_called_once()
+ self.assertEqual(wait_for_ready.call_args.args, (67890,))
+ self.assertLessEqual(
+ wait_for_ready.call_args.kwargs["timeout"],
+ runtime.SERVICE_SLOW_START_TIMEOUT_SECONDS,
)
spawn_background.assert_not_called()
@@ -703,17 +723,25 @@ 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.
+ def test_a_working_service_is_a_held_lock_plus_the_holders_own_report(self):
+ """"Something is holding the lock" is not "this instance has a service".
+
+ The lock is taken before the database is migrated, so every failed
+ migration passes through a state where it is held by a process that will
+ never serve anything. That state is what the incident looked like, and a
+ predicate that answers "running" there is the reason a dark instance was
+ reported healthy -- so the holder's own claim to have finished starting is
+ part of the fact, not a detail of it.
+
+ An unreadable record while the lock is held reads as not running for the
+ same reason: nothing has claimed to have started. It is indistinguishable
+ from the mid-startup window, and calling that window "running" is exactly
+ the mistake. The bounded wait, not this predicate, is what tells a slow
+ start from a stuck one.
+
+ ``service_instance_lock_available`` still answers the different question
+ ``start_service`` asks -- whether anything at all would block a second
+ start -- and stays true to the lock alone.
"""
with tempfile.TemporaryDirectory() as tmpdir:
@@ -729,16 +757,368 @@ class RuntimeServiceLockTests(unittest.TestCase):
runtime.acquire_service_instance_lock()
try:
+ self.assertFalse(runtime.verified_service_running())
+ self.assertFalse(runtime.service_instance_lock_available()[0])
+
+ runtime.mark_service_instance_started()
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())
+ self.assertFalse(runtime.service_instance_lock_available()[0])
+ self.assertFalse(runtime.verified_service_running())
finally:
runtime.release_service_instance_lock()
self.assertFalse(runtime.verified_service_running())
+ def test_holding_the_lock_is_not_yet_having_started(self):
+ """Two different facts, and the gap between them is where upgrades fail.
+
+ The lock is taken before the database is migrated, so a holder can be
+ mid-startup or already dead from a migration it never finished. Only the
+ holder can say which, and it says so by rewriting its own record through
+ the handle that holds the lock -- so the claim cannot outlive the process,
+ and cannot be read off a record the PREVIOUS holder left behind.
+ """
+
+ 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):
+ runtime.acquire_service_instance_lock()
+ try:
+ self.assertFalse(runtime.service_instance_started(os.getpid()))
+
+ runtime.mark_service_instance_started()
+ self.assertTrue(runtime.service_instance_started(os.getpid()))
+ # Someone else's startup, reported by a record this
+ # process happens to be able to read.
+ self.assertFalse(runtime.service_instance_started(os.getpid() + 1))
+ finally:
+ runtime.release_service_instance_lock()
+
+ def test_a_release_that_never_reported_startup_reads_as_started(self):
+ """What a rollback target on an older version can offer, kept working.
+
+ Releases predating this distinction wrote ``running`` when they took the
+ lock and never wrote again. Demanding the second write of them would make
+ every rollback report a failed start for a service that is up.
+ """
+
+ with tempfile.TemporaryDirectory() as tmpdir:
+ lock_path = Path(tmpdir) / "service.lock"
+ lock_path.write_text(json.dumps({"pid": os.getpid(), "phase": "running"}), encoding="utf-8")
+ with patch("vibe.runtime.paths.get_runtime_service_lock_path", return_value=lock_path):
+ self.assertTrue(runtime.service_instance_started(os.getpid()))
+
+ def test_every_reporter_says_starting_while_the_lock_holder_is_still_starting(self):
+ """One machine, one word, whichever reporter is asked for it.
+
+ The lock is taken before the database is migrated, so between the two a
+ holder occupies this instance without serving anybody. Everything that
+ reports that machine has to say so -- `vibe status`, the dashboard reading
+ the same payload, and the repair that PERSISTS the word for later readers
+ alike. Each of them deriving it separately is one fact with three answers,
+ and an instance stuck in its migration reading `running` for eight days is
+ what the wrong answer cost.
+
+ Asserted over the reporters together rather than one test each, because
+ the property is that they agree: a fourth reporter written to derive its
+ own word is the bug returning, and it belongs here where the reason is
+ written down.
+ """
+
+ from vibe import cli
+
+ 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"
+ status_path = runtime_dir / "status.json"
+
+ 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.get_runtime_status_path", return_value=status_path):
+ with patch("vibe.runtime.paths.ensure_data_dirs", return_value=None):
+ runtime.acquire_service_instance_lock()
+ try:
+ self.assertEqual(runtime.resolve_service_state().state, "starting")
+ self.assertFalse(runtime.resolve_service_state().running)
+
+ payload = json.loads(runtime.render_status())
+ self.assertEqual(payload["state"], "starting")
+ self.assertFalse(payload["running"])
+ self.assertEqual(payload["service_pid"], os.getpid())
+
+ cli._write_refreshed_runtime_status()
+ self.assertEqual(runtime.read_status()["state"], "starting")
+
+ # And all three again once the holder reports it
+ # got through startup: the word follows the
+ # machine rather than latching to either answer.
+ runtime.mark_service_instance_started()
+ self.assertEqual(runtime.resolve_service_state().state, "running")
+ self.assertTrue(json.loads(runtime.render_status())["running"])
+ cli._write_refreshed_runtime_status()
+ self.assertEqual(runtime.read_status()["state"], "running")
+ finally:
+ runtime.release_service_instance_lock()
+
+ def test_only_a_record_saying_so_moves_the_word_off_running(self):
+ """`starting` is claimed by evidence, never inferred from its absence.
+
+ The distinction matters because the record is not the only thing that can
+ be missing -- it can be lost, truncated, or left behind by a holder that
+ is gone. Reading any of those as `starting` would tell the owner of a
+ working machine that it is coming up, forever, since nothing will ever
+ write the record that answer waits for. That trades a stuck instance
+ reading healthy for a healthy instance reading stuck, which is the same
+ bug pointed the other way.
+
+ `service_instance_started` takes the opposite default on purpose: it asks
+ whether a new generation PROVED it works, and there an absent record is
+ an absent proof.
+ """
+
+ with tempfile.TemporaryDirectory() as tmpdir:
+ lock_path = Path(tmpdir) / "service.lock"
+ with patch("vibe.runtime.paths.get_runtime_service_lock_path", return_value=lock_path):
+ with patch("vibe.runtime.resolve_service_owner_pid", return_value=4242):
+ self.assertEqual(runtime.resolve_service_state().state, "running")
+
+ lock_path.write_text(json.dumps({"pid": 4242, "phase": "starting"}), encoding="utf-8")
+ self.assertEqual(runtime.resolve_service_state().state, "starting")
+
+ # Someone else's startup, in a record this instance happens
+ # to be able to read.
+ lock_path.write_text(json.dumps({"pid": 4243, "phase": "starting"}), encoding="utf-8")
+ self.assertEqual(runtime.resolve_service_state().state, "running")
+
+
+class ReadinessWaitIsNeverOptionalTests(unittest.TestCase):
+ """The class of bug this closes, stated once instead of caught once per site.
+
+ Three separate starters had each decided for themselves that a recorded pid
+ meant the wait could be skipped, and each was wrong in the same way, and each
+ cost its own review round. The mistake is available to every future starter
+ for as long as the two predicates sit next to each other, so it is worth a
+ test rather than three fixes: a fourth one written the same way fails here,
+ where the reason is written down, instead of in an incident.
+
+ Stated as the property -- no starter makes the wait conditional on the lock --
+ rather than as the list of starters, so a module added later is covered
+ without editing this.
+ """
+
+ PRODUCTION_MODULES = (
+ Path(__file__).resolve().parents[1] / "vibe" / "runtime.py",
+ Path(__file__).resolve().parents[1] / "vibe" / "cli.py",
+ Path(__file__).resolve().parents[1] / "vibe" / "restart_supervisor.py",
+ Path(__file__).resolve().parents[1] / "scripts" / "incus_regression_supervisor.py",
+ )
+
+ def test_no_starter_makes_the_readiness_wait_conditional_on_the_lock(self):
+ import ast
+
+ for module in self.PRODUCTION_MODULES:
+ tree = ast.parse(module.read_text(encoding="utf-8"))
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.If):
+ continue
+ if "service_pid_recorded" not in ast.dump(node.test):
+ continue
+ guarded = [*node.body, *node.orelse]
+ waits = [
+ child
+ for branch in guarded
+ for child in ast.walk(branch)
+ if isinstance(child, ast.Call) and getattr(child.func, "attr", None) == "wait_for_service_ready"
+ ]
+ self.assertEqual(
+ waits,
+ [],
+ f"{module.name}:{node.lineno} waits for readiness only when the lock says so; "
+ "the lock is taken before the database is migrated, so that is the case the "
+ "wait exists for",
+ )
+
+
+class ServiceReadinessGateTests(unittest.TestCase):
+ """What `start_service(wait_for_ready=True)` is allowed to hand back.
+
+ The parameter has always promised readiness, and `_resolve_service_pid()` has
+ seven places it can name a pid -- a recorded pid file, a lock holder whose
+ command does not match this install, a scoped launch adopting its owner, a
+ fresh spawn that took the lock. Exactly one of them ever waited for the
+ running phase. Every other one answered "the lock was taken", which is the
+ state an instance is in while the release that took it is dying on its own
+ migration, so the Dashboard recorded a started service and the doctor
+ recorded a successful repair, both correctly trusting the parameter.
+
+ The property is that the promise is kept however the pid was reached, and it
+ is asserted in two halves that are complete together: the gate holds for the
+ situations below, and the structural test proves there is no way to reach a
+ pid that skips it.
+ """
+
+ def setUp(self):
+ self._extra_service_pids = patch("vibe.runtime.extra_service_process_pids", return_value=[])
+ self._extra_service_pids.start()
+ self._no_scope = patch("vibe.runtime.maybe_systemd_scope_prefix", return_value=[])
+ self._no_scope.start()
+ # A stuck start is the case under test, so the wait has to be allowed to
+ # run out. Two tenths of a second rather than the shipped two minutes.
+ self._short_wait = patch("vibe.runtime.SERVICE_SLOW_START_TIMEOUT_SECONDS", 0.2)
+ self._short_wait.start()
+
+ def tearDown(self):
+ self._short_wait.stop()
+ self._no_scope.stop()
+ self._extra_service_pids.stop()
+
+ def _start_with_phase(self, phase: str, *, already_recorded: bool):
+ """Run the real `start_service()` against a lock record saying `phase`.
+
+ `already_recorded` picks the situation: a service this machine already
+ knows about, or one spawned here. Both used to return on the lock alone.
+ """
+
+ 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"
+ pid = 12345
+ lock_path.write_text(json.dumps({"pid": pid, "phase": phase}), encoding="utf-8")
+ if already_recorded:
+ pid_path.write_text(str(pid), encoding="utf-8")
+
+ def fake_spawn(args, stdout_name, stderr_name, env=None, **kwargs):
+ return SimpleNamespace(pid=pid, poll=lambda: None)
+
+ 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):
+ with patch("vibe.runtime.pid_alive", return_value=True):
+ with patch("vibe.runtime.service_pid_recorded", return_value=True):
+ with patch(
+ "vibe.runtime.get_process_command",
+ return_value=f"{sys.executable} {runtime.get_service_main_path()}",
+ ):
+ with patch(
+ "vibe.runtime.service_instance_lock_available", return_value=(True, None)
+ ):
+ with patch(
+ "vibe.runtime.spawn_service_background_process", side_effect=fake_spawn
+ ):
+ with patch("vibe.runtime.wait_for_service_pid", return_value=True):
+ return runtime.start_service()
+
+ def test_a_service_that_only_took_the_lock_is_not_a_started_service(self):
+ for already_recorded in (True, False):
+ with self.subTest(already_recorded=already_recorded):
+ with self.assertRaises(RuntimeError) as raised:
+ self._start_with_phase("starting", already_recorded=already_recorded)
+ # And says so. Reporting this as "did not acquire the service
+ # lock" sent whoever read the log looking for a lock contention
+ # that was never there.
+ self.assertIn("did not finish starting", str(raised.exception))
+
+ def test_a_service_that_reported_itself_up_is_returned(self):
+ for already_recorded in (True, False):
+ with self.subTest(already_recorded=already_recorded):
+ self.assertEqual(self._start_with_phase("running", already_recorded=already_recorded), 12345)
+
+ def _start_against_a_lock_phase_lasting(self, seconds: float):
+ """Run `start_service()` with the phases on a clock this test drives.
+
+ Returns the timeout the readiness phase was handed, so the assertion is
+ about the bound itself rather than about how long the test took.
+ """
+
+ clock = {"now": 1000.0}
+ handed: list[float] = []
+
+ def slow_resolve(**kwargs):
+ clock["now"] += seconds
+ return 12345
+
+ def record_timeout(pid, timeout=None):
+ handed.append(timeout)
+ return pid
+
+ with patch("vibe.runtime.time", SimpleNamespace(monotonic=lambda: clock["now"])):
+ with patch("vibe.runtime._resolve_service_pid", side_effect=slow_resolve):
+ with patch("vibe.runtime.wait_for_service_ready", side_effect=record_timeout):
+ pid = runtime.start_service()
+
+ self.assertEqual(pid, 12345)
+ self.assertEqual(len(handed), 1)
+ return handed[0]
+
+ def test_the_two_start_phases_spend_one_budget_between_them(self):
+ """A start is one event, so it costs the caller one timeout.
+
+ `SERVICE_SLOW_START_TIMEOUT_SECONDS` is what the configuration says a
+ service is allowed to take to start. Taking the spawn lock and reaching
+ the serving state are two phases of that one event, so handing the
+ constant to each in turn made a start that is slow in both cost twice
+ the stated number -- on the Dashboard and doctor paths, where someone is
+ waiting for the answer.
+ """
+
+ # The budget is 0.2s here (see setUp); the lock phase eats three
+ # quarters of it, so the readiness phase may have the rest and no more.
+ self.assertAlmostEqual(self._start_against_a_lock_phase_lasting(0.15), 0.05)
+
+ def test_a_lock_phase_that_spends_the_whole_budget_leaves_nothing_to_wait_with(self):
+ """And the remainder floors at zero rather than going negative.
+
+ A negative timeout is not a shorter wait; depending on what receives it
+ it is an error or an unbounded one, which would put the doubled wait
+ back in a less visible form.
+ """
+
+ self.assertEqual(self._start_against_a_lock_phase_lasting(0.5), 0.0)
+
+ def test_nothing_reaches_a_service_pid_without_passing_the_gate(self):
+ """The other half: no shipped caller can route around `start_service()`.
+
+ `_resolve_service_pid()` answers only which process is the service, and
+ the gate is applied to its result once. That split is worth nothing if a
+ caller can take the unguarded answer, so the property is that nobody
+ does -- checked by looking, so that a caller written later fails here
+ rather than on someone's instance. A resolution path added inside
+ `_resolve_service_pid()` then inherits the gate by construction, which is
+ the arrangement that was missing when six of its returns did not.
+ """
+
+ import ast
+
+ repo_root = Path(__file__).resolve().parents[1]
+ callers = {}
+ for root in ("main.py", "config", "core", "modules", "storage", "vibe", "scripts"):
+ target = repo_root / root
+ for source in [target] if target.is_file() else sorted(target.rglob("*.py")):
+ tree = ast.parse(source.read_text(encoding="utf-8"))
+ calls = sum(
+ 1
+ for node in ast.walk(tree)
+ if isinstance(node, ast.Call)
+ and (getattr(node.func, "id", None) or getattr(node.func, "attr", None)) == "_resolve_service_pid"
+ )
+ if calls:
+ callers[source.relative_to(repo_root).as_posix()] = calls
+
+ self.assertEqual(callers, {"vibe/runtime.py": 1})
+
if __name__ == "__main__":
unittest.main()
diff --git a/tests/test_service_logging_handlers.py b/tests/test_service_logging_handlers.py
index 062c27cf5..1896354c0 100644
--- a/tests/test_service_logging_handlers.py
+++ b/tests/test_service_logging_handlers.py
@@ -66,6 +66,11 @@ def test_start_service_disables_stdout_logging_for_background_process(monkeypatc
# Stub the real spawn so we never fork a real vibe service, and short-circuit
# the post-spawn lock wait. This captures the env start_service would launch with.
monkeypatch.setattr(runtime, "wait_for_service_pid", lambda pid, *args, **kwargs: True)
+ # And the readiness gate after it: this test is about the env a spawn is
+ # handed, not about whether the process that gets it comes up. The stubbed
+ # process never reports a running phase, so the real gate would sit here for
+ # the full slow-start timeout and then raise.
+ monkeypatch.setattr(runtime, "wait_for_service_ready", lambda pid, timeout=None: pid)
def fake_spawn_service_background_process(args, stdout_name, stderr_name, env=None):
captured["args"] = args
diff --git a/tests/test_service_readiness.py b/tests/test_service_readiness.py
new file mode 100644
index 000000000..287d464ac
--- /dev/null
+++ b/tests/test_service_readiness.py
@@ -0,0 +1,363 @@
+"""Who is entitled to say the service is up.
+
+`vibe status`, the doctor and the restart supervisor all decide whether a release
+started by asking the runtime whether the service instance is ready. Publishing
+that answer is therefore a claim to have observed the service serving, and the
+incident behind this module is what happens when the claim is made by code that
+observed no such thing: a release that died inside its own startup was read as an
+upgrade that worked, for days, because readiness had been announced by the caller
+before the startup it was speaking for was attempted.
+
+The ordering half that `main()` still owns -- lock, then migration, then the
+controller -- is asserted in `tests/test_sqlite_state_startup.py`.
+"""
+
+from __future__ import annotations
+
+import ast
+import asyncio
+import threading
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import Mock
+
+import pytest
+
+from core import controller as controller_module
+from core import internal_server
+from core.controller import Controller
+
+REPO_ROOT = Path(__file__).resolve().parents[1]
+#: Everything shipped to a user's machine. `tests/` is excluded deliberately:
+#: `tests/test_runtime_service_lock.py` calls the primitive to test the primitive,
+#: which is not a claim about any running service.
+SHIPPED_SOURCE_ROOTS = ("main.py", "config", "core", "modules", "storage", "vibe")
+
+
+def _install_runtime_ready_dependencies(controller, events: list[str]) -> None:
+ """The collaborators `_on_runtime_ready` starts, each recording that it ran.
+
+ Kept out of the fixture body because their order is the subject rather than
+ the setup: the readiness line is drawn between the steps whose failure ends
+ startup and the steps that catch their own, so each one has to be visible.
+ """
+
+ async def restore_polls(_platforms):
+ events.append("restore polls")
+
+ async def recover_owners():
+ events.append("recover owners")
+
+ async def post_update_notification(*, ready_platform):
+ events.append("post-update notification")
+
+ async def start_command_watcher():
+ events.append("runtime command watcher")
+
+ controller.primary_platform = "avibe"
+ controller._restore_active_polls = restore_polls
+ controller._recover_runtime_owners = recover_owners
+ controller.update_checker = SimpleNamespace(
+ check_and_send_post_update_notification=post_update_notification,
+ start=lambda: events.append("update checker"),
+ )
+ controller.scheduled_task_service = SimpleNamespace(start=lambda: events.append("scheduled tasks"))
+ controller.watch_service = SimpleNamespace(start=lambda: events.append("watch service"))
+ controller.runtime_command_watcher = SimpleNamespace(start=start_command_watcher)
+ controller._get_idle_cleanup_timeouts = lambda: (0, 0)
+ controller.cleanup_task = None
+
+ def request_shutdown(reason):
+ # Stands in for the real one by its effect, not its mechanism: what a
+ # startup step gets by asking for shutdown is a process on its way out,
+ # and here that is the loop stopping. Left as a bare recorder, a test
+ # whose release fails before readiness would hang instead of failing,
+ # because the fixture's only other way out of `run_forever()` is the
+ # readiness callback the failure is supposed to prevent.
+ events.append(f"shutdown requested: {reason}")
+ controller._loop.call_soon(controller._loop.stop)
+
+ controller.request_shutdown = request_shutdown
+
+
+def startup(monkeypatch):
+ """A controller stripped to the startup steps `run()` performs itself.
+
+ Nothing in `asyncio` or `threading` is stubbed: `core/controller.py` reaches
+ them through the module objects themselves, so replacing an attribute there
+ replaces it for the whole process, and a test that stops the loop by owning
+ `new_event_loop` would be asserting against a loop of its own rather than
+ the one the service runs on. The seams used instead are the two the service
+ genuinely has -- the readiness primitive and the dispatch server -- and the
+ real loop is stopped from the readiness callback, which is exactly the moment
+ under test.
+ """
+
+ events: list[str] = []
+ controller = Controller.__new__(Controller)
+ controller.config = SimpleNamespace()
+ controller.enabled_platforms = ["slack"]
+ controller.show_git_checkpoint_service = SimpleNamespace(start=lambda: events.append("show checkpoints"))
+ controller._shutdown_requested = False
+ controller._im_run_exception = None
+ controller.cleanup_sync = Mock()
+ _install_runtime_ready_dependencies(controller, events)
+
+ def fake_im_runtime():
+ # What `MultiIMClient.run()` does, and the reason readiness can be
+ # announced from the ready callback at all: the platform threads are
+ # started and then the callback is fired unconditionally -- with no
+ # platform configured too. Dispatched onto the loop from this thread the
+ # way the real client dispatches it, which a loop that has not started
+ # yet accepts and runs on its first pass.
+ events.append("im runtime")
+ asyncio.run_coroutine_threadsafe(Controller._on_runtime_ready(controller), controller._loop)
+
+ controller._run_im_runtime = fake_im_runtime
+
+ def publish_readiness():
+ events.append("published ready")
+ # Recorded from inside the loop rather than after `run_forever()`
+ # returns, so "the service is serving" is observed at the instant it
+ # becomes true -- which is the thing readiness claims.
+ controller._loop.call_soon(lambda: (events.append("serving"), controller._loop.stop()))
+
+ monkeypatch.setattr(controller_module, "mark_service_instance_started", publish_readiness)
+ monkeypatch.setattr(internal_server, "start", lambda controller: events.append("internal server"))
+ # `run()`'s cleanup unlinks whatever this returns. Left real, it would name
+ # -- and on a developer machine delete -- the live local service's socket.
+ monkeypatch.setattr(internal_server, "default_socket_path", lambda: REPO_ROOT / "no-such-vibe.sock")
+
+ yield SimpleNamespace(controller=controller, events=events)
+
+ # `run()` installs its loop as the thread's current one and then closes it.
+ # Left behind, the next test in this process inherits a closed loop.
+ asyncio.set_event_loop(None)
+
+
+def test_readiness_is_published_by_the_code_that_reaches_the_serving_loop(startup):
+ """Announced from inside the function that does the starting, not from `run()`.
+
+ Not a claim about which line the call sits on, but about what stands behind
+ it: every structural step a new release can die in has already succeeded, and
+ the loop it speaks for is serving. `run()` starts startup and does not finish
+ it, so announcing from there put every step written afterwards outside the
+ claim -- which is how durable-owner recovery came to be able to fail after
+ the supervisor had already been told the upgrade worked.
+ """
+
+ Controller.run(startup.controller)
+
+ assert "published ready" in startup.events
+ # After the steps whose failure ends startup...
+ assert startup.events.index("recover owners") < startup.events.index("published ready")
+ # ...and the loop it speaks for did reach serving.
+ assert startup.events[-1] == "serving"
+ # And there was a startup for it to be speaking for, rather than the publish
+ # standing at the head of an otherwise empty sequence.
+ assert startup.events[0] != "published ready"
+
+
+def test_recovery_that_fails_takes_readiness_down_with_it(startup):
+ """The round-10 instance, and the reason the line moved rather than grew.
+
+ Durable-owner recovery is a startup step like any other: it can fail on a new
+ release, and when it does it asks for shutdown and re-raises, so the process
+ is on its way out. Announced from `run()`, readiness had already been
+ published by then and the supervisor read the instance as upgraded -- a dark
+ machine with a successful upgrade recorded against it, which is this PR's
+ whole subject arriving through a door it had not been closed on.
+ """
+
+ async def recovery_the_new_release_cannot_do():
+ startup.events.append("recover owners")
+ raise RuntimeError("durable delivery owners are not recoverable on this release")
+
+ startup.controller._recover_runtime_owners = recovery_the_new_release_cannot_do
+
+ Controller.run(startup.controller)
+
+ assert "recover owners" in startup.events
+ assert "published ready" not in startup.events
+ assert "serving" not in startup.events
+ assert [event for event in startup.events if event.startswith("shutdown requested")] == [
+ "shutdown requested: runtime owner recovery failed"
+ ]
+
+
+def test_a_release_that_dies_in_its_own_startup_never_publishes_readiness(startup):
+ """The incident, reproduced at a step that only the new release can fail.
+
+ A release whose startup breaks structurally does not crash the process:
+ `run()` catches, cleans up, and returns, so the service exits through the
+ ordinary path. Everything watching therefore has only the published readiness
+ to go on -- and nothing must have published it.
+ """
+
+ def start_that_the_new_release_cannot_do():
+ startup.events.append("show checkpoints")
+ raise RuntimeError("checkpoint service is not constructible on this release")
+
+ startup.controller.show_git_checkpoint_service = SimpleNamespace(start=start_that_the_new_release_cannot_do)
+
+ # Returns instead of raising. That is the shape of the bug, not a detail of
+ # the test: a non-zero exit would have been noticed years ago.
+ Controller.run(startup.controller)
+
+ assert "published ready" not in startup.events
+ assert "serving" not in startup.events
+ startup.controller.cleanup_sync.assert_called_once()
+
+
+def test_readiness_is_withheld_when_the_im_runtime_already_failed(startup):
+ """The IM runtime is the one startup step that fails on another thread.
+
+ Every other step `run()` performs fails in `run()`'s own `try`, so reaching
+ the publish at all is proof they succeeded. The IM runtime does not: it is
+ handed to a thread, and the publish runs whether or not that thread is still
+ alive. So the publish asks, and a recorded failure withholds the claim -- the
+ supervisor then sees no readiness, and the rollback it exists for fires.
+ """
+
+ startup.controller._loop = asyncio.new_event_loop()
+ startup.controller._im_run_exception = RuntimeError("slack adapter is not constructible on this release")
+ try:
+ Controller._publish_readiness_unless_im_runtime_failed(startup.controller)
+ finally:
+ startup.controller._loop.close()
+
+ assert startup.events == []
+
+
+def test_readiness_asks_for_a_recorded_failure_and_not_for_a_live_thread(startup):
+ """A Web-only install has no IM platform to keep a thread alive.
+
+ `im_client.run()` returns immediately and correctly when nothing is
+ configured, so a liveness check would refuse readiness forever on a service
+ that is working -- turning the rollback into the outage it prevents. The
+ predicate is therefore the recorded exception, and this pins that: a finished
+ IM runtime that recorded nothing still publishes.
+ """
+
+ startup.controller._loop = asyncio.new_event_loop()
+ startup.controller._im_run_exception = None
+ startup.controller._im_thread = SimpleNamespace(is_alive=lambda: False)
+ try:
+ Controller._publish_readiness_unless_im_runtime_failed(startup.controller)
+ startup.controller._loop.run_forever()
+ finally:
+ startup.controller._loop.close()
+
+ assert startup.events == ["published ready", "serving"]
+
+
+def test_an_im_runtime_that_fails_before_the_loop_starts_still_stops_it(startup):
+ """The stop has to survive being sent to a loop that has not started yet.
+
+ `run()` starts this thread on the line before `run_forever()`, so the whole
+ reason the IM runtime fails early -- a bad release -- is also what makes it
+ fail into a loop that exists and is not running. Guarding the stop with
+ `is_running()` discarded it in exactly that case, and `run_forever()` then ran
+ forever: no IM runtime, no service, and nothing left that could ask it to
+ stop. A callback queued beforehand runs as soon as the loop starts.
+
+ Driven from this thread rather than from a real one so the ordering under test
+ is the ordering the test produces, and asserted by whether the loop returns.
+ """
+
+ startup.controller._loop = asyncio.new_event_loop()
+ startup.controller.im_client = SimpleNamespace(
+ run=Mock(side_effect=RuntimeError("adapter died on its first connect"))
+ )
+
+ # Records the failure and asks the not-yet-running loop to stop.
+ Controller._run_im_runtime(startup.controller)
+ assert isinstance(startup.controller._im_run_exception, RuntimeError)
+
+ # A daemon thread, because the assertion for a lost stop is a `run_forever()`
+ # that never returns -- which must fail this test rather than hang the suite.
+ ran = threading.Thread(target=startup.controller._loop.run_forever, daemon=True)
+ ran.start()
+ ran.join(timeout=10)
+ stopped = not ran.is_alive()
+ if stopped:
+ startup.controller._loop.close()
+
+ assert stopped, "the loop never stopped: the IM runtime's stop was dropped"
+
+
+def _on_runtime_ready_body() -> list[ast.stmt]:
+ tree = ast.parse((REPO_ROOT / "core" / "controller.py").read_text(encoding="utf-8"))
+ for node in ast.walk(tree):
+ if isinstance(node, ast.AsyncFunctionDef) and node.name == "_on_runtime_ready":
+ return node.body
+ raise AssertionError("_on_runtime_ready is gone, and the readiness boundary went with it")
+
+
+def test_every_startup_step_below_the_readiness_line_catches_its_own_failure():
+ """The boundary, checked where it actually gets broken: by the next step added.
+
+ Readiness claims every step whose failure means the service is not up has
+ completed. What makes that claim true is not where the call sits but the rule
+ about its two sides -- above it a failure ends startup, below it each step
+ catches its own and the service is up either way. Nobody has ever moved this
+ announcement to the wrong place; what happened four times is that startup grew
+ past it and the new step joined the wrong side in silence. So the rule is
+ asserted rather than the position, and an unguarded step appended below fails
+ here when it is written instead of in someone's dark instance.
+ """
+
+ body = _on_runtime_ready_body()
+ published = [
+ index
+ for index, statement in enumerate(body)
+ if isinstance(statement, ast.Expr)
+ and isinstance(statement.value, ast.Call)
+ and getattr(statement.value.func, "attr", None) == "_publish_readiness_unless_im_runtime_failed"
+ ]
+ assert len(published) == 1, "readiness is not announced exactly once from the boundary"
+
+ unguarded = [
+ ast.unparse(statement).splitlines()[0]
+ for statement in body[published[0] + 1 :]
+ if not isinstance(statement, ast.Try)
+ ]
+ assert unguarded == [], (
+ "these startup steps run after readiness is announced but do not catch their own "
+ "failure, so failing one of them aborts a service that has already been reported up"
+ )
+
+
+def _readiness_calls_in(path: Path) -> int:
+ tree = ast.parse(path.read_text(encoding="utf-8"))
+ return sum(
+ 1
+ for node in ast.walk(tree)
+ if isinstance(node, ast.Call)
+ # Both spellings: the bare name that `core/controller.py` imports, and
+ # the `runtime.` attribute form a new caller is at least as likely to use.
+ and (getattr(node.func, "id", None) or getattr(node.func, "attr", None)) == "mark_service_instance_started"
+ )
+
+
+def test_nothing_else_shipped_publishes_readiness():
+ """One announcer, found by looking rather than by remembering.
+
+ The defect was a second announcer: `main()` published readiness and then
+ called `run()`, so the gap between the two was a service reported up that had
+ not started. Counting over the whole shipped tree closes the class instead of
+ the instance -- a third announcer in a platform adapter, a CLI path or a
+ future supervisor fails here when it is written, rather than in someone's
+ dark instance days later.
+ """
+
+ announcers = {}
+ for root in SHIPPED_SOURCE_ROOTS:
+ target = REPO_ROOT / root
+ for source in [target] if target.is_file() else sorted(target.rglob("*.py")):
+ calls = _readiness_calls_in(source)
+ if calls:
+ announcers[source.relative_to(REPO_ROOT).as_posix()] = calls
+
+ assert announcers == {"core/controller.py": 1}
diff --git a/tests/test_sqlite_state_startup.py b/tests/test_sqlite_state_startup.py
index 1c15ebb1e..bd696f07f 100644
--- a/tests/test_sqlite_state_startup.py
+++ b/tests/test_sqlite_state_startup.py
@@ -1,5 +1,8 @@
from __future__ import annotations
+import ast
+import inspect
+import textwrap
from pathlib import Path
from types import SimpleNamespace
@@ -37,3 +40,35 @@ def test_prepare_sqlite_state_uses_config_primary_platform(monkeypatch) -> None:
assert calls == ["slack"]
assert report.imported is True
+
+
+def test_the_migration_runs_under_the_lock_and_before_the_controller_exists() -> None:
+ """The order `main()` still owns, after readiness moved out of it.
+
+ The lock is taken first because the migration has to run under it, so the
+ lock says only that a process got as far as trying. The migration then runs
+ before anything is constructed against the schema it produces.
+
+ This test used to end by pinning `mark_service_instance_started()` between
+ the controller and `run()`, on the reasoning that building the controller was
+ the last thing a new release could break structurally. That reasoning was
+ wrong: `run()` starts the checkpoint service, the dispatch server and the IM
+ runtime, any of which a new release can fail, and each of which it catches
+ and returns from -- so a release that never served was being announced as
+ serving. Readiness now belongs to `run()`, and the tests for it are in
+ `tests/test_service_readiness.py`. What remains here is the ordering that is
+ genuinely `main()`'s, asserted structurally because the failure mode is a
+ later edit moving a step for a plausible-sounding reason.
+ """
+
+ tree = ast.parse(textwrap.dedent(inspect.getsource(service_main.main)))
+ lines = {}
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.Call):
+ continue
+ name = node.func.id if isinstance(node.func, ast.Name) else getattr(node.func, "attr", None)
+ lines.setdefault(name, node.lineno)
+
+ assert lines["acquire_service_instance_lock"] < lines["prepare_sqlite_state"]
+ assert lines["prepare_sqlite_state"] < lines["Controller"]
+ assert lines["Controller"] < lines["run"]
diff --git a/tests/test_state_backups.py b/tests/test_state_backups.py
index 84aa896ea..67c9a24d2 100644
--- a/tests/test_state_backups.py
+++ b/tests/test_state_backups.py
@@ -757,3 +757,391 @@ def test_background_store_schema_upgrade_uses_migration_backup(tmp_path: Path) -
backups = list((db_path.parent / "backups").glob("avibe-sqlite-migration-*"))
assert len(backups) == 1
+
+
+def test_a_rollback_point_is_offered_only_when_it_was_written_after_the_observation(tmp_path: Path) -> None:
+ # The pair `next_backup_sequence` / `find_restorable_backup` exists to answer
+ # one question -- did the code I just handed the database to migrate it, and
+ # where is the copy it took first -- using only numbers this side wrote and
+ # read. Stated as that property over an arbitrary run of copies rather than
+ # as a list of the cases, because the cases the earlier designs died on were
+ # all cases nobody had listed: a stamp and a schema that stay put across a
+ # migration that commits rows and then fails, and a clock corrected backwards
+ # between two attempts.
+ db_path = tmp_path / "vibe.sqlite"
+ backups_dir = tmp_path / "backups"
+ _stamp(db_path, "20260806_0047")
+ with sqlite3.connect(db_path) as conn:
+ conn.execute("create table payload (value text)")
+ conn.execute("insert into payload (value) values ('before the observation')")
+
+ before = create_sqlite_migration_backup(db_path, backups_dir=backups_dir)
+ watermark = backups.next_backup_sequence(backups_dir)
+
+ # Nothing has been written since the watermark was read, so there is nothing
+ # to put back -- the same answer a restart that failed before starting the
+ # new version has to get.
+ assert backups.find_restorable_backup(backups_dir, written_at_or_after=watermark) is None
+
+ with sqlite3.connect(db_path) as conn:
+ conn.execute("update payload set value = 'committed by the first attempt'")
+ first_attempt = create_sqlite_migration_backup(
+ db_path, backups_dir=backups_dir, now=datetime(2026, 8, 6, 12, 0, tzinfo=timezone.utc)
+ )
+ assert backups.find_restorable_backup(backups_dir, written_at_or_after=watermark) == first_attempt
+
+ # A retry, dated BEFORE the attempt it follows. The answer moves to it anyway:
+ # it holds the rows the first attempt committed, and the earlier copy would
+ # silently discard them.
+ with sqlite3.connect(db_path) as conn:
+ conn.execute("insert into payload (value) values ('committed, then the attempt failed')")
+ retry = create_sqlite_migration_backup(
+ db_path, backups_dir=backups_dir, now=datetime(2026, 8, 6, 11, 0, tzinfo=timezone.utc)
+ )
+ assert backups.find_restorable_backup(backups_dir, written_at_or_after=watermark) == retry
+ # And the copy from before the window is never the answer, at any watermark
+ # at or above it: it predates the observation, so restoring it would throw
+ # away work this rollback was never asked about.
+ assert before != retry
+ assert backups.find_restorable_backup(backups_dir, written_at_or_after=watermark + 1) == retry
+
+
+def test_a_copy_written_before_the_counter_existed_is_never_offered(tmp_path: Path) -> None:
+ # A copy carrying no number was written by a release that did not have one,
+ # which places it before any observation this release could have made. Offering
+ # it would restore a database from an unknown point in the past and report it
+ # as the rollback for this upgrade.
+ db_path = tmp_path / "vibe.sqlite"
+ backups_dir = tmp_path / "backups"
+ _stamp(db_path, "20260806_0047")
+ with sqlite3.connect(db_path) as conn:
+ conn.execute("create table payload (value text)")
+ conn.execute("insert into payload (value) values ('from before the counter')")
+
+ from_the_previous_release = _as_pre_sequence_backup(
+ create_sqlite_migration_backup(db_path, backups_dir=backups_dir)
+ )
+
+ assert from_the_previous_release.exists()
+ assert backups.next_backup_sequence(backups_dir) == 0
+ assert backups.find_restorable_backup(backups_dir, written_at_or_after=0) is None
+
+
+def test_restoring_a_rollback_point_destroys_neither_side(tmp_path: Path) -> None:
+ # A restore is a swap, and the property is that both sides survive it. The
+ # database being rolled back FROM is the only copy of whatever the failing
+ # version committed, and the restore's own outcome can turn out to be the bad
+ # one, so neither the live database nor the rollback point may be consumed to
+ # produce the other.
+ db_path = tmp_path / "vibe.sqlite"
+ backups_dir = tmp_path / "backups"
+ _stamp(db_path, "20260806_0047")
+ with sqlite3.connect(db_path) as conn:
+ conn.execute("create table payload (value text)")
+ conn.execute("insert into payload (value) values ('before the upgrade')")
+
+ rollback_point = create_sqlite_migration_backup(db_path, backups_dir=backups_dir)
+ point_contents = _db_contents(rollback_point / "vibe.sqlite")
+
+ # The failing version migrates: new schema, new rows, new stamp.
+ with sqlite3.connect(db_path) as conn:
+ conn.execute("create table added_by_the_new_version (value text)")
+ conn.execute("insert into payload (value) values ('written by the new version')")
+ _stamp(db_path, "20260819_0051")
+ forward_contents = _db_contents(db_path)
+
+ replaced = backups.restore_sqlite_backup(rollback_point, db_path)
+
+ assert _db_contents(db_path) == point_contents
+ assert replaced == rollback_point / backups.REPLACED_DATABASE_NAME
+ assert _db_contents(replaced) == forward_contents
+ assert _db_contents(rollback_point / "vibe.sqlite") == point_contents
+ assert oct(db_path.stat().st_mode)[-3:] == "600"
+
+
+def test_a_restore_leaves_no_journal_from_the_displaced_generation(tmp_path: Path) -> None:
+ # The sidecars are not tidiness. A `-wal` left beside the restored file
+ # belongs to the database that was displaced, and SQLite would replay it into
+ # the restored one and call the result consistent -- a rollback that reports
+ # success while handing back the schema it was rolling back from.
+ db_path = tmp_path / "vibe.sqlite"
+ backups_dir = tmp_path / "backups"
+ _stamp(db_path, "20260806_0047")
+ with sqlite3.connect(db_path) as conn:
+ conn.execute("create table payload (value text)")
+ conn.execute("insert into payload (value) values ('before the upgrade')")
+ rollback_point = create_sqlite_migration_backup(db_path, backups_dir=backups_dir)
+ point_contents = _db_contents(rollback_point / "vibe.sqlite")
+
+ with sqlite3.connect(db_path) as conn:
+ conn.execute("pragma journal_mode = wal")
+ conn.execute("create table added_by_the_new_version (value text)")
+ assert db_path.with_name(db_path.name + "-wal").exists()
+
+ replaced = backups.restore_sqlite_backup(rollback_point, db_path)
+
+ assert not db_path.with_name(db_path.name + "-wal").exists()
+ assert not db_path.with_name(db_path.name + "-shm").exists()
+ assert _db_contents(db_path) == point_contents
+ # Moved rather than deleted: the displaced generation keeps its own log, so
+ # what the new version committed is still readable beside it.
+ assert replaced is not None and replaced.exists()
+
+
+def test_a_restore_over_a_missing_database_leaves_no_orphan_journal(tmp_path: Path) -> None:
+ # Same rule, on the branch that has nothing to displace. A migration can end
+ # with the live name holding no database and its log still beside it, and a
+ # log is paired to a database by name -- SQLite validates the log's own
+ # checksum chain, not the database it was written for. Renaming the rollback
+ # point in over that name therefore hands the failed generation's tail to the
+ # older database, and SQLite replays it and reports a recovered database:
+ # back comes exactly what the rollback was removing, in the one code path
+ # that only ever runs when something has already gone wrong.
+ db_path = tmp_path / "vibe.sqlite"
+ backups_dir = tmp_path / "backups"
+ _stamp(db_path, "20260806_0047")
+ with sqlite3.connect(db_path) as conn:
+ conn.execute("create table payload (value text)")
+ conn.execute("insert into payload (value) values ('before the upgrade')")
+ rollback_point = create_sqlite_migration_backup(db_path, backups_dir=backups_dir)
+ point_contents = _db_contents(rollback_point / "vibe.sqlite")
+
+ with sqlite3.connect(db_path) as conn:
+ conn.execute("pragma journal_mode = wal")
+ conn.execute("create table added_by_the_new_version (value text)")
+ orphans = [db_path.with_name(db_path.name + suffix) for suffix in ("-wal", "-shm")]
+ assert [orphan.name for orphan in orphans if orphan.exists()] == [orphan.name for orphan in orphans]
+ db_path.unlink()
+
+ replaced = backups.restore_sqlite_backup(rollback_point, db_path)
+
+ assert replaced is None
+ assert [orphan.name for orphan in orphans if orphan.exists()] == []
+ assert _db_contents(db_path) == point_contents
+
+
+def test_a_restore_that_cannot_be_staged_leaves_the_database_alone(tmp_path: Path) -> None:
+ # The replacement is copied and verified before anything about the live
+ # database changes, so a rollback point that turns out to be unreadable costs
+ # nothing. The alternative -- displace first, then discover it -- leaves the
+ # machine with no database at all, which is the failure this whole change
+ # exists to prevent.
+ db_path = tmp_path / "vibe.sqlite"
+ backups_dir = tmp_path / "backups"
+ _stamp(db_path, "20260806_0047")
+ with sqlite3.connect(db_path) as conn:
+ conn.execute("create table payload (value text)")
+ conn.execute("insert into payload (value) values ('the only copy')")
+ rollback_point = create_sqlite_migration_backup(db_path, backups_dir=backups_dir)
+ live_contents = _db_contents(db_path)
+
+ (rollback_point / "vibe.sqlite").write_bytes(b"not a database at all")
+
+ with pytest.raises(sqlite3.DatabaseError):
+ backups.restore_sqlite_backup(rollback_point, db_path)
+
+ assert _db_contents(db_path) == live_contents
+ assert not (rollback_point / backups.REPLACED_DATABASE_NAME).exists()
+ assert not db_path.with_name(db_path.name + ".restoring").exists()
+
+
+def test_repeated_restores_to_one_rollback_point_do_not_grow_the_window(tmp_path: Path) -> None:
+ # A displaced database is a full copy, so it needs a bound like every other
+ # copy in this directory. It gets the one that already exists by living inside
+ # the rollback point it came from: a second restore to the same point replaces
+ # the first displacement instead of accumulating beside it, and pruning the
+ # point takes it along. Otherwise a machine retrying an upgrade adds one copy
+ # of the database per attempt -- the exact growth this window was bounded to
+ # stop.
+ db_path = tmp_path / "vibe.sqlite"
+ backups_dir = tmp_path / "backups"
+ _stamp(db_path, "20260806_0047")
+ with sqlite3.connect(db_path) as conn:
+ conn.execute("create table payload (value text)")
+ conn.execute("insert into payload (value) values ('before the upgrade')")
+ rollback_point = create_sqlite_migration_backup(db_path, backups_dir=backups_dir)
+
+ for attempt in ("first attempt", "second attempt"):
+ with sqlite3.connect(db_path) as conn:
+ conn.execute("insert into payload (value) values (?)", (attempt,))
+ backups.restore_sqlite_backup(rollback_point, db_path)
+
+ displaced = [path.name for path in rollback_point.iterdir() if backups.REPLACED_DATABASE_NAME in path.name]
+ assert displaced == [backups.REPLACED_DATABASE_NAME]
+ # The last attempt's database is the one kept, and it is the one that held
+ # the most work.
+ assert ("second attempt",) in _db_contents(rollback_point / backups.REPLACED_DATABASE_NAME)[1][1]
+
+
[email protected]("linking_available", [True, False], ids=["same-filesystem", "cross-filesystem"])
+def test_no_rename_a_swap_performs_can_cost_the_live_generation(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, linking_available: bool
+) -> None:
+ # The property: at no point during a restore does the machine have no
+ # database, and no copy of anyone's data is destroyed before its replacement
+ # is complete. Both are claims about the instants in between, so the test
+ # interrupts the swap at the instants they can be violated -- a rename that
+ # fails, which is what a crash, a full disk, or a killed process looks like
+ # from here.
+ #
+ # Every rename it performs, not the first one. Failing only the earliest is
+ # how a swap passed this while its LAST rename ran with the live log already
+ # deleted: everything the database had committed since its last checkpoint
+ # was gone the moment that rename failed, and no assertion here was looking.
+ # So the restore runs once per rename, with that rename failing, and the loop
+ # ends when there is no rename left to fail -- which makes the coverage
+ # complete by construction rather than by a list someone has to maintain.
+ #
+ # Run on both filesystem layouts, because the property is about the machine
+ # and not about the fast path. A state directory on its own mount refuses the
+ # hard link, and an implementation that answers that refusal by MOVING the
+ # live database has already broken the property before anything fails: from
+ # then until the rename, `vibe.sqlite` does not exist. That is not a rarity
+ # to accept -- it is the recovery step of a failed upgrade, running on a
+ # machine that is already down.
+ real_replace = os.replace
+ real_link = os.link
+
+ def refuse_link(*args, **kwargs):
+ raise OSError(errno.EXDEV, "cross-device link")
+
+ renames = 0
+ while True:
+ renames += 1
+ root = tmp_path / f"failing-rename-{renames}"
+ root.mkdir()
+ db_path = root / "vibe.sqlite"
+ _stamp(db_path, "20260806_0047")
+ with sqlite3.connect(db_path) as conn:
+ conn.execute("create table payload (value text)")
+ conn.execute("insert into payload (value) values ('before the upgrade')")
+ rollback_point = create_sqlite_migration_backup(db_path, backups_dir=root / "backups")
+ if not linking_available:
+ monkeypatch.setattr(backups.os, "link", refuse_link)
+
+ with sqlite3.connect(db_path) as conn:
+ conn.execute("insert into payload (value) values ('first attempt')")
+ backups.restore_sqlite_backup(rollback_point, db_path)
+ displaced = rollback_point / backups.REPLACED_DATABASE_NAME
+ assert ("first attempt",) in _db_contents(displaced)[1][1]
+
+ with sqlite3.connect(db_path) as conn:
+ conn.execute("insert into payload (value) values ('second attempt')")
+ # A write-ahead log belonging to the live generation, which the swap has
+ # to take a copy of and only then clear: it is the file SQLite would
+ # otherwise replay into whatever database arrives under this name next,
+ # and it holds everything committed since the last checkpoint.
+ db_path.with_name(db_path.name + "-wal").write_bytes(b"live write-ahead log")
+
+ countdown = [renames]
+
+ def fail_the_nth_rename(src, dst, *args, _countdown=countdown, **kwargs):
+ _countdown[0] -= 1
+ if _countdown[0] == 0:
+ raise OSError(errno.EIO, "interrupted")
+ return real_replace(src, dst, *args, **kwargs)
+
+ monkeypatch.setattr(backups.os, "replace", fail_the_nth_rename)
+ try:
+ backups.restore_sqlite_backup(rollback_point, db_path)
+ interrupted = False
+ except OSError:
+ interrupted = True
+ finally:
+ monkeypatch.setattr(backups.os, "replace", real_replace)
+ monkeypatch.setattr(backups.os, "link", real_link)
+
+ if not interrupted:
+ # This restore had fewer renames left than the one being failed, so
+ # every rename the swap performs has now been failed exactly once.
+ break
+
+ # The database the machine is running on is still there, still complete,
+ # and still with the write-ahead log that holds the rest of it.
+ assert db_path.exists()
+ assert ("second attempt",) in _db_contents(db_path)[1][1]
+ assert db_path.with_name(db_path.name + "-wal").read_bytes() == b"live write-ahead log"
+ # And whatever the rollback point holds under the displaced name is a
+ # whole generation: the previous displacement until the new one is
+ # complete on disk, the new one after that. Which of the two depends on
+ # how far the swap got, and both are complete answers. What would not be
+ # is a displacement deleted to make room for one that never landed.
+ assert displaced.is_file()
+ assert _db_contents(displaced)[1][1] in (
+ [("before the upgrade",), ("first attempt",)],
+ [("before the upgrade",), ("second attempt",)],
+ )
+
+ # The database out, its log out, the replacement in. Asserted so that a swap
+ # rewritten to do less can no longer satisfy the loop above by having nothing
+ # left to interrupt.
+ assert renames > 3
+
+
+def test_the_displaced_generation_is_durable_before_the_live_path_commits(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ # The same invariant as the test above, stated against power loss instead of
+ # against an exception. A rename is visible to this process the moment it
+ # returns and durable only once its directory is synced, so the two are
+ # different instants and a crash can land between them. If both syncs waited
+ # until after the live commit, a machine losing power there would come back
+ # with the restored database at the live path and the directory entry naming
+ # the displaced generation still only in cache -- and that generation holds
+ # everything the failed release committed and exists nowhere else, because the
+ # rollback point is a copy of an OLDER database, not of that one.
+ #
+ # Read back from what the swap actually did rather than from a list of files
+ # to check: every rename into the rollback point must be durable before the
+ # live rename, whichever renames those turn out to be. A sidecar added later
+ # is covered without editing this test, which is the point -- the `-shm` and
+ # `-wal` pair is a SQLite detail that has changed before.
+ db_path = tmp_path / "vibe.sqlite"
+ backups_dir = tmp_path / "backups"
+ _stamp(db_path, "20260806_0047")
+ with sqlite3.connect(db_path) as conn:
+ conn.execute("create table payload (value text)")
+ conn.execute("insert into payload (value) values ('before the upgrade')")
+ rollback_point = create_sqlite_migration_backup(db_path, backups_dir=backups_dir)
+
+ # A live generation with a write-ahead log, so the swap has sidecars to
+ # displace and not just the database.
+ with sqlite3.connect(db_path) as conn:
+ conn.execute("pragma journal_mode = wal")
+ conn.execute("insert into payload (value) values ('written by the new version')")
+ assert db_path.with_name(db_path.name + "-wal").exists()
+
+ real_replace = os.replace
+ journal: list[tuple[str, Path]] = []
+
+ def record_replace(src, dst, *args, **kwargs):
+ result = real_replace(src, dst, *args, **kwargs)
+ journal.append(("rename", Path(dst)))
+ return result
+
+ def record_fsync_file(path: Path) -> None:
+ journal.append(("sync file", Path(path)))
+
+ def record_fsync_directory(path: Path) -> None:
+ journal.append(("sync dir", Path(path)))
+
+ monkeypatch.setattr(backups.os, "replace", record_replace)
+ monkeypatch.setattr(backups, "_fsync_file", record_fsync_file)
+ monkeypatch.setattr(backups, "_fsync_directory", record_fsync_directory)
+
+ backups.restore_sqlite_backup(rollback_point, db_path)
+
+ live_commit = journal.index(("rename", db_path))
+ into_the_point = [
+ path for operation, path in journal[:live_commit] if operation == "rename" and path.parent == rollback_point
+ ]
+ # The swap displaced something, so the ordering below is a claim about real
+ # renames rather than a vacuous one over an empty list.
+ assert into_the_point
+
+ for displaced in into_the_point:
+ assert journal.index(("sync file", displaced)) < live_commit
+ assert journal.index(("sync dir", rollback_point)) < live_commit
+ # And the directory sync comes after the renames it is there to persist:
+ # syncing it earlier records entries that do not exist yet.
+ assert journal.index(("sync dir", rollback_point)) > max(journal.index(("rename", path)) for path in into_the_point)
diff --git a/tests/test_update_checker_platforms.py b/tests/test_update_checker_platforms.py
index 4c641fd00..813dd58a4 100644
--- a/tests/test_update_checker_platforms.py
+++ b/tests/test_update_checker_platforms.py
@@ -932,6 +932,35 @@ def test_post_update_notification_skips_success_when_running_version_mismatches(
assert not marker.exists()
+def test_a_version_that_did_not_take_effect_is_blocked_even_with_no_one_to_tell(monkeypatch, tmp_path):
+ """Blocking is decided by the version, not by whether anyone can be told.
+
+ An instance whose upgrade failed and was rolled back is running the old
+ version again, which is precisely the mismatch this check reads -- and it is
+ also, by construction, an instance nobody is watching. If the block were a
+ step on the notification path, the machine with no reachable admin would
+ retry the release that just took it down, roll back, and retry, while the one
+ with a Slack channel is protected. So the record is written from the version
+ fact alone, before any question of delivery, and the marker being discarded
+ here for want of a target must not take the block with it.
+ """
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ SettingsStore.reset_instance()
+ controller = _StubController(SettingsStore.get_instance())
+ controller.im_clients = {}
+ checker = UpdateChecker(controller, UpdateConfig())
+ checker._write_update_marker("3.0.11", platform="telegram")
+ monkeypatch.setattr("vibe.__version__", "3.0.10", raising=False)
+
+ asyncio.run(checker.check_and_send_post_update_notification())
+
+ assert checker.state.blocked_auto_update_version == "3.0.11"
+ assert checker.state.blocked_auto_update_reason == "post_update_version_mismatch"
+ assert checker.state.blocked_auto_update_current_version == "3.0.10"
+ assert not (tmp_path / "state" / "pending_update_notification.json").exists()
+
+
def test_stop_returns_cancellable_task(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
SettingsStore.reset_instance()
diff --git a/tests/test_upgrade_flow.py b/tests/test_upgrade_flow.py
index 3d2c12bef..27f975f4f 100644
--- a/tests/test_upgrade_flow.py
+++ b/tests/test_upgrade_flow.py
@@ -1,14 +1,18 @@
from __future__ import annotations
+import ast
import os
import subprocess
import sys
from pathlib import Path
from typing import Any
+import pytest
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from vibe import api, cli
+from vibe.runtime import ServiceLauncher
from vibe.upgrade import (
UpgradePlan,
build_upgrade_plan,
@@ -21,9 +25,35 @@ from vibe.upgrade import (
get_restart_shell_command,
get_running_vibe_path,
get_safe_cwd,
+ installed_package_name,
+ pinned_package_spec,
+ RollbackTarget,
+ rollback_target,
)
[email protected](autouse=True)
+def _tree_is_not_an_installed_distribution(monkeypatch):
+ """Every test here describes a machine, not the machine running the tests.
+
+ `installed_package_name()` asks this process's own metadata which
+ distribution provides `vibe`, and the answer differs by checkout: a developer
+ running from a source tree gets nothing, while CI installs the package first
+ and gets `avibe-os`. Tests written against the first answer pass locally and
+ then fail on a runner for a reason that has nothing to do with the change --
+ `test_a_spec_that_cannot_carry_a_pin_is_refused` did exactly that, because an
+ installed name outranks the configured spec whose refusal it was asserting.
+
+ Answering `[]` here is the honest state for a checkout, and it is the state
+ every test in this module was already written against. Only the ambient
+ metadata is removed; the interpreter-path heuristic stays live, so a test can
+ still hand in a uv tool path and be answered from it, and a test that wants a
+ measured name sets one explicitly.
+ """
+
+ monkeypatch.setattr("vibe.upgrade._distributions_providing_this_package", lambda: [])
+
+
def test_build_upgrade_plan_uses_uv_and_preserves_tool_bin_dir(monkeypatch):
monkeypatch.setattr("vibe.upgrade.os.path.exists", lambda path: True)
monkeypatch.setattr("vibe.upgrade.os.access", lambda path, mode: True)
@@ -92,6 +122,403 @@ def test_build_upgrade_plan_uses_env_package_spec(monkeypatch):
]
+#: How each installer spells "do it even though you believe it is already done".
+#: Written as a mapping rather than as two assertions so that an installer added
+#: to `build_upgrade_plan` later fails this test until someone decides what its
+#: word is, instead of silently shipping a rollback path that can no-op.
+FORCES_THE_INSTALL = {"uv": "--force", "pip": "--force-reinstall"}
+
+
+def test_a_pinned_plan_never_asks_for_an_upgrade_and_always_forces_the_install(monkeypatch):
+ # Two ways for a rollback command to install nothing and still exit 0, one
+ # per word, and both silent on every installer path.
+ #
+ # Asking for an upgrade resolves forward to the exact release being rolled
+ # back FROM: uv resolves past the pin, pip declines to move backwards at all.
+ #
+ # Not forcing leaves the installer free to decide the pin is already
+ # satisfied -- and on the case this change exists for, it is. Installing
+ # `avibe-os` over a `vibe-remote` machine never uninstalls `vibe-remote`, so
+ # that distribution's metadata still stands and still claims the old version,
+ # while the files under `vibe/` are the new release's, written over the top.
+ # `pip install vibe-remote==<old>` reads as satisfied, pip does nothing, and
+ # the supervisor starts the failed generation again and calls it a recovery.
+ monkeypatch.setattr("vibe.upgrade.os.path.exists", lambda path: True)
+ monkeypatch.setattr("vibe.upgrade.os.access", lambda path, mode: True)
+
+ uv_plan = build_upgrade_plan(
+ python_executable="/tmp/.local/share/uv/tools/avibe-os/bin/python",
+ uv_path="/usr/local/bin/uv",
+ vibe_path="/custom/bin/vibe",
+ base_env={"PATH": "/usr/bin"},
+ version="3.0.10",
+ )
+ assert uv_plan.method == "uv"
+ assert uv_plan.command == [
+ "/usr/local/bin/uv",
+ "tool",
+ "install",
+ "avibe-os==3.0.10",
+ # Unconditional here: the version already installed is the newer one, so
+ # without it uv reports the tool as satisfied and installs nothing.
+ "--force",
+ ]
+ assert "--upgrade" not in uv_plan.command
+
+ pip_plan = build_upgrade_plan(
+ python_executable="/usr/bin/python3",
+ uv_path=None,
+ base_env={"PATH": "/usr/bin"},
+ version="3.0.10",
+ )
+ assert pip_plan.method == "pip"
+ assert pip_plan.command == [
+ "/usr/bin/python3",
+ "-m",
+ "pip",
+ "install",
+ "--force-reinstall",
+ "avibe-os==3.0.10",
+ ]
+
+ for plan in (uv_plan, pip_plan):
+ assert "--upgrade" not in plan.command
+ assert FORCES_THE_INSTALL[plan.method] in plan.command
+
+
+def _metadata_records(monkeypatch, distribution: str, version: str) -> None:
+ """One distribution provides `vibe`, and its metadata records `version`."""
+
+ monkeypatch.setattr("vibe.upgrade._distributions_providing_this_package", lambda: [distribution])
+ monkeypatch.setattr("importlib.metadata.version", lambda name: version if name == distribution else "0")
+
+
+def test_a_forward_upgrade_forces_the_install_once_metadata_stops_describing_the_code(monkeypatch):
+ """The rollback's own no-op, one release later and with a person watching.
+
+ A rollback installs `vibe-remote==3.0.10` over a machine whose forward upgrade
+ installed `avibe-os==3.0.11`, and pip never uninstalls the distribution it
+ replaced. So the tree ends up holding both: the files under `vibe/` are 3.0.10,
+ and `avibe-os` still records 3.0.11 with nothing on disk behind it.
+
+ Then `vibe upgrade` runs. It compares this process's 3.0.10 against the
+ published 3.0.11 and decides to install; pip reads `avibe-os==3.0.11` as
+ already satisfied and does nothing; the command reports success and the
+ machine keeps running 3.0.10 -- silently, indefinitely, and now on the path a
+ user invokes by hand.
+
+ So `--force-reinstall` is not a property of pinned plans, it is a property of
+ asking for a version that is not the version on disk. Measured from our own
+ two answers, never read off the metadata that is the thing in doubt.
+ """
+
+ monkeypatch.setattr("vibe.upgrade.os.path.exists", lambda path: True)
+ monkeypatch.setattr("vibe.upgrade.os.access", lambda path, mode: True)
+ _metadata_records(monkeypatch, "avibe-os", "3.0.11")
+ monkeypatch.setattr("vibe.__version__", "3.0.10")
+
+ plan = build_upgrade_plan(
+ python_executable="/usr/bin/python3",
+ uv_path=None,
+ base_env={"PATH": "/usr/bin"},
+ )
+
+ assert plan.method == "pip"
+ # Still an upgrade: the version being asked for is whatever the index has
+ # newest. Forced as well, because the metadata pip would consult to decide is
+ # describing a release that is not what is running.
+ assert "--upgrade" in plan.command
+ assert "--force-reinstall" in plan.command
+
+
+def test_the_rename_pair_left_by_a_rollback_forces_the_next_install(monkeypatch):
+ """The state this check exists for is the one where two distributions are present.
+
+ A rollback across the rename installs `vibe-remote==3.0.10` over a tree whose
+ forward upgrade installed `avibe-os==3.0.11`, and pip does not uninstall the
+ distribution it replaced. So both are recorded and only one of them can be
+ describing the files under `vibe/`. Asking a single distribution -- or
+ treating "more than one" as unreadable -- would make this exact machine the
+ one machine that answers "metadata agrees", which is how the no-op ships:
+ the next upgrade asks pip for a version `avibe-os` already claims, pip does
+ nothing, and the instance keeps running the rolled-back code forever.
+ """
+
+ monkeypatch.setattr("vibe.upgrade.os.path.exists", lambda path: True)
+ monkeypatch.setattr("vibe.upgrade.os.access", lambda path, mode: True)
+ monkeypatch.setattr(
+ "vibe.upgrade._distributions_providing_this_package",
+ lambda: ["avibe-os", "vibe-remote"],
+ )
+ recorded = {"avibe-os": "3.0.11", "vibe-remote": "3.0.10"}
+ monkeypatch.setattr("importlib.metadata.version", lambda name: recorded[name])
+ monkeypatch.setattr("vibe.__version__", "3.0.10")
+
+ plan = build_upgrade_plan(
+ python_executable="/usr/bin/python3",
+ uv_path=None,
+ base_env={"PATH": "/usr/bin"},
+ )
+
+ assert "--force-reinstall" in plan.command
+
+
+def test_a_forward_upgrade_on_an_undamaged_install_is_left_to_the_installer(monkeypatch):
+ """Forcing is the exception, and has to stay one.
+
+ `--force-reinstall` makes pip rebuild and rewrite every dependency in the
+ tree, so making it unconditional turns each routine upgrade into a much longer
+ and much wider write on a machine nobody is watching. The ordinary case is an
+ install whose metadata and files agree, and there the installer's own
+ already-satisfied judgement is correct and cheaper.
+ """
+
+ monkeypatch.setattr("vibe.upgrade.os.path.exists", lambda path: True)
+ monkeypatch.setattr("vibe.upgrade.os.access", lambda path, mode: True)
+ _metadata_records(monkeypatch, "avibe-os", "3.0.11")
+ monkeypatch.setattr("vibe.__version__", "3.0.11")
+
+ plan = build_upgrade_plan(
+ python_executable="/usr/bin/python3",
+ uv_path=None,
+ base_env={"PATH": "/usr/bin"},
+ )
+
+ assert "--upgrade" in plan.command
+ assert "--force-reinstall" not in plan.command
+
+
+ ("case", "distributions", "recorded", "running"),
+ [
+ # A source checkout or an editable install: nothing published to compare.
+ ("no distribution provides the package", [], "3.0.11", "3.0.11"),
+ # Mid-rename, or a vendored environment. Both are asked, and here both
+ # agree with the code, so there is nothing to force -- the count of
+ # distributions is not by itself a disagreement.
+ ("two distributions provide it and both agree", ["avibe-os", "vibe-remote"], "3.0.11", "3.0.11"),
+ # A regression build. Its version describes a tree, not a release, so a
+ # disagreement with published metadata is expected rather than evidence.
+ ("the running version names no release", ["avibe-os"], "3.0.11", "0.0.0.dev0+abc1234"),
+ ("the recorded version names no release", ["avibe-os"], "0.0.0.dev0+abc1234", "3.0.11"),
+ ],
+)
+def test_an_unknown_install_shape_is_never_forced_on_a_guess(monkeypatch, case, distributions, recorded, running):
+ """Only a disagreement between two published releases is evidence.
+
+ Every other answer is an environment this measurement cannot read, and the
+ honest response to one is to leave the installer alone rather than to force a
+ full reinstall on a machine whose shape we guessed at. Stated as the property
+ -- unknown means unforced -- so a shape nobody has met yet inherits it.
+ """
+
+ monkeypatch.setattr("vibe.upgrade.os.path.exists", lambda path: True)
+ monkeypatch.setattr("vibe.upgrade.os.access", lambda path, mode: True)
+ monkeypatch.setattr("vibe.upgrade._distributions_providing_this_package", lambda: distributions)
+ monkeypatch.setattr("importlib.metadata.version", lambda name: recorded)
+ monkeypatch.setattr("vibe.__version__", running)
+
+ plan = build_upgrade_plan(
+ python_executable="/usr/bin/python3",
+ uv_path=None,
+ base_env={"PATH": "/usr/bin"},
+ )
+
+ assert "--force-reinstall" not in plan.command, case
+
+
+def test_a_rollback_pins_the_distribution_the_install_actually_came_from(monkeypatch):
+ # Which distribution published the running version and which one the next
+ # upgrade should ask for are different questions, and on a machine that
+ # predates the rename they have different answers. Going forward wants the
+ # configured spec -- that is what the rename is for. Going back wants this,
+ # because `avibe-os==2.x` names a release that was never published under that
+ # name, so the rollback resolves to nothing and the instance stays dark.
+ monkeypatch.setenv("VIBE_UPGRADE_PACKAGE_SPEC", "avibe-os")
+
+ legacy = "/home/ai/.local/share/uv/tools/vibe-remote/bin/python"
+ assert pinned_package_spec("2.9.4", python_executable=legacy) == "vibe-remote==2.9.4"
+ plan = build_upgrade_plan(
+ python_executable=legacy,
+ uv_path="/usr/local/bin/uv",
+ base_env={"PATH": "/usr/bin"},
+ version="2.9.4",
+ )
+ assert "vibe-remote==2.9.4" in plan.command
+ assert not any(argument.startswith("avibe-os") for argument in plan.command)
+
+ # An install whose path says nothing about a distribution -- pip into a shared
+ # environment -- has only the configured spec to go on, and gets it.
+ assert pinned_package_spec("3.0.10", python_executable="/usr/bin/python3") == "avibe-os==3.0.10"
+
+
+def test_the_rename_pair_still_names_the_distribution_that_describes_the_code(monkeypatch):
+ """Two providers is not an unreadable machine, it is the aftermath of a rollback.
+
+ Installing `avibe-os` over a `vibe-remote` machine never uninstalls the older
+ distribution, so once a rollback has crossed the rename the tree holds both
+ for good. Every upgrade after that measures its rollback target in this state,
+ which is why reading two providers as unanswerable does not cost one recovery
+ -- it costs every recovery the machine will ever attempt.
+
+ The metadata is what tells them apart: `avibe-os` records the release that
+ failed, `vibe-remote` records the files that are running. Naming neither left
+ `package=None`, `pinned_package_spec` fell back to the configured forward
+ name, and `avibe-os==2.9.0` was never published under that name -- so the one
+ recovery attempt could only fail, on an instance that is already down.
+ """
+
+ monkeypatch.setenv("VIBE_UPGRADE_PACKAGE_SPEC", "avibe-os")
+ monkeypatch.setattr(
+ "vibe.upgrade._distributions_providing_this_package",
+ lambda: ["avibe-os", "vibe-remote"],
+ )
+ recorded = {"avibe-os": "3.0.11", "vibe-remote": "2.9.0"}
+ monkeypatch.setattr("importlib.metadata.version", lambda name: recorded[name])
+ monkeypatch.setattr("vibe.__version__", "2.9.0", raising=False)
+
+ assert installed_package_name() == "vibe-remote"
+
+ # And the consequence the name is measured for: the pin this machine's next
+ # failed upgrade rolls back to names a release that exists.
+ launcher = ServiceLauncher(python="/uv/tools/vibe-remote/bin/python", main="/uv/tools/vibe-remote/service_main.py")
+ monkeypatch.setattr("vibe.runtime.current_service_launcher", lambda: launcher)
+ target = rollback_target()
+ assert target is not None and target.package == "vibe-remote"
+ assert pinned_package_spec(target.version, package_name=target.package) == "vibe-remote==2.9.0"
+
+
+def test_providers_that_cannot_be_told_apart_are_left_to_the_path(monkeypatch):
+ """Metadata answers this only while it distinguishes them.
+
+ Two distributions recording the same release is a vendored or mid-rename
+ environment, not a rollback, and there is nothing in the metadata to prefer
+ one name over the other. Guessing would put the pin on a distribution that may
+ never have published the version -- the same failure, arrived at from the
+ opposite direction -- so the interpreter path answers instead, and `None` when
+ it cannot either.
+ """
+
+ monkeypatch.setattr(
+ "vibe.upgrade._distributions_providing_this_package",
+ lambda: ["avibe-os", "vibe-remote"],
+ )
+ monkeypatch.setattr("importlib.metadata.version", lambda name: "3.0.11")
+ monkeypatch.setattr("vibe.__version__", "3.0.11", raising=False)
+
+ monkeypatch.setattr("vibe.upgrade.sys.executable", "/usr/bin/python3")
+ assert installed_package_name() is None
+
+ monkeypatch.setattr("vibe.upgrade.sys.executable", "/home/ai/.local/share/uv/tools/vibe-remote/bin/python")
+ assert installed_package_name() == "vibe-remote"
+
+
+def test_a_spec_that_cannot_carry_a_pin_is_refused(monkeypatch):
+ # The alternative to refusing is falling back to the unpinned spec, which is
+ # the reinstall-the-failure command above. Whoever configured a wheel path or
+ # an index URL as the upgrade source gets a rollback that fails loudly instead
+ # of one that lies. The message must not quote the spec: it can be an index
+ # URL carrying credentials, and it is written to a restart log.
+ monkeypatch.setenv("VIBE_UPGRADE_PACKAGE_SPEC", "https://user:[email protected]/simple/avibe-os")
+
+ with pytest.raises(ValueError) as refusal:
+ pinned_package_spec("3.0.10")
+ assert "secret" not in str(refusal.value)
+
+ monkeypatch.setattr("vibe.upgrade.os.path.exists", lambda path: True)
+ monkeypatch.setattr("vibe.upgrade.os.access", lambda path, mode: True)
+ with pytest.raises(ValueError):
+ build_upgrade_plan(
+ python_executable="/usr/bin/python3",
+ uv_path=None,
+ base_env={"PATH": "/usr/bin"},
+ version="3.0.10",
+ )
+
+
+def test_a_tree_with_no_published_release_has_no_rollback_target(monkeypatch):
+ # A source checkout, an editable install, and a regression build all report
+ # the same placeholder version, which names no release. Handing it on as a
+ # target buys an index round-trip that fails, and then tells whoever is
+ # looking at a dark instance that the rollback mechanism is broken, when the
+ # truth is that this install never had a release to go back to.
+ from vibe import UNKNOWN_VERSION
+
+ monkeypatch.setattr("vibe.__version__", UNKNOWN_VERSION, raising=False)
+ assert rollback_target() is None
+
+ # And a tree that does name a release answers with the distribution and the
+ # install too, in one value: all three are read here, in the process that
+ # still predates the install, and there is no way to obtain one without the
+ # others. The install matters as much as the version -- a rollback across the
+ # `vibe-remote` -> `avibe-os` rename reinstalls into a directory this process
+ # is not running out of, so a target that named only the version would be
+ # restored correctly and then started from the wrong generation.
+ launcher = ServiceLauncher(python="/uv/tools/vibe-remote/bin/python", main="/uv/tools/vibe-remote/service_main.py")
+ monkeypatch.setattr("vibe.__version__", "3.0.10", raising=False)
+ monkeypatch.setattr("vibe.upgrade.installed_package_name", lambda *args, **kwargs: "vibe-remote")
+ monkeypatch.setattr("vibe.runtime.current_service_launcher", lambda: launcher)
+ assert rollback_target() == RollbackTarget(version="3.0.10", package="vibe-remote", launcher=launcher)
+
+
+REPO_ROOT = Path(__file__).resolve().parents[1]
+#: Everything shipped to a user's machine.
+SHIPPED_SOURCE_ROOTS = ("main.py", "config", "core", "modules", "storage", "vibe")
+
+
+def test_only_the_plan_builder_can_ask_what_this_install_is():
+ """One caller, found by looking rather than by remembering.
+
+ The measurement has always been documented as something to take before the
+ install and never after, and both upgrade paths took it after anyway --
+ inside `if result.returncode == 0:`, describing an install that by then had
+ already been overwritten. A rule that lives in a docstring is enforced by
+ whoever happens to have read it.
+
+ Moving it into `UpgradePlan` removes the ordering from every caller: a plan
+ is what produces the command, so the measurement cannot happen later than the
+ install unless someone reaches past the plan. This counts over the whole
+ shipped tree so that reaching past it fails here, when it is written, rather
+ than on a machine that predates the rename months later.
+ """
+
+ callers = {}
+ for root in SHIPPED_SOURCE_ROOTS:
+ target = REPO_ROOT / root
+ for source in [target] if target.is_file() else sorted(target.rglob("*.py")):
+ tree = ast.parse(source.read_text(encoding="utf-8"))
+ calls = sum(
+ 1
+ for node in ast.walk(tree)
+ if isinstance(node, ast.Call)
+ and (getattr(node.func, "id", None) or getattr(node.func, "attr", None)) == "rollback_target"
+ )
+ if calls:
+ callers[source.relative_to(REPO_ROOT).as_posix()] = calls
+
+ assert callers == {"vibe/upgrade.py": 1}
+
+
+def test_the_plan_that_installs_carries_what_it_is_replacing(monkeypatch):
+ # A forward plan describes an install that is about to stop existing, so it
+ # takes the measurement while there is still something to measure. A pinned
+ # plan IS the rollback -- the process building one is the release that failed
+ # -- so measuring there would hand the failure forward as its own recovery
+ # target, which is the shape of every way this has gone wrong so far.
+ launcher = ServiceLauncher(python="/uv/tools/vibe-remote/bin/python", main="/uv/tools/vibe-remote/service_main.py")
+ monkeypatch.setattr("vibe.__version__", "3.0.10", raising=False)
+ monkeypatch.setattr("vibe.upgrade.installed_package_name", lambda *args, **kwargs: "vibe-remote")
+ monkeypatch.setattr("vibe.runtime.current_service_launcher", lambda: launcher)
+
+ forward = build_upgrade_plan(python_executable="/usr/bin/python3", uv_path=None, base_env={"PATH": "/usr/bin"})
+ assert forward.rollback_to == RollbackTarget(version="3.0.10", package="vibe-remote", launcher=launcher)
+
+ pinned = build_upgrade_plan(
+ python_executable="/usr/bin/python3", uv_path=None, base_env={"PATH": "/usr/bin"}, version="3.0.9"
+ )
+ assert pinned.rollback_to is None
+
+
def test_build_upgrade_plan_finds_uv_outside_current_path(monkeypatch):
monkeypatch.setattr(
"vibe.upgrade.shutil.which",
@@ -408,11 +835,24 @@ def test_get_restart_environment_normalizes_relative_pythonpath_entries(monkeypa
assert env["PYTHONPATH"] == f"{source_root}{os.pathsep}{tmp_path}{os.pathsep}{tmp_path / 'src'}"
+#: A machine that predates the rename, as its own plan describes it. The upgrade
+#: paths below cannot be handed this any other way, which is the point: the
+#: measurement is a field of the plan precisely so that no caller is left with an
+#: ordering to remember, and a test that could still inject it late would be
+#: describing a seam that no longer exists.
+LEGACY_INSTALL = RollbackTarget(
+ version="3.0.10",
+ package="vibe-remote",
+ launcher=ServiceLauncher("/uv/tools/vibe-remote/bin/python", "/uv/tools/vibe-remote/service_main.py"),
+)
+
+
def test_do_upgrade_uses_upgrade_plan_env_and_restarts(monkeypatch):
plan = UpgradePlan(
command=["/usr/local/bin/uv", "tool", "install", "avibe-os", "--upgrade"],
env={"UV_TOOL_BIN_DIR": "/custom/bin"},
method="uv",
+ rollback_to=LEGACY_INSTALL,
)
calls: dict[str, Any] = {}
@@ -446,6 +886,12 @@ def test_do_upgrade_uses_upgrade_plan_env_and_restarts(monkeypatch):
"vibe_path": "/custom/bin/vibe",
"trigger": "upgrade",
"prepare_show_runtime": True,
+ # The install this process was running, taken BEFORE it was replaced and
+ # carried here by the plan that replaced it: what the restart reinstalls
+ # if it cannot bring the new one up. Version, distribution and launcher
+ # together, because a pin needs the first two and a machine that predates
+ # the rename does not answer "avibe-os" for either.
+ "rollback_to": LEGACY_INSTALL,
}
@@ -657,6 +1103,7 @@ def test_cmd_upgrade_uses_upgrade_plan_env(monkeypatch):
command=["/usr/local/bin/uv", "tool", "install", "avibe-os", "--upgrade"],
env={"UV_TOOL_BIN_DIR": "/custom/bin"},
method="uv",
+ rollback_to=LEGACY_INSTALL,
)
calls: dict[str, Any] = {}
@@ -695,6 +1142,8 @@ def test_cmd_upgrade_uses_upgrade_plan_env(monkeypatch):
"vibe_path": "/custom/bin/vibe",
"trigger": "upgrade",
"prepare_show_runtime": True,
+ # See the do_upgrade case: the restart is handed the install to fall back to.
+ "rollback_to": LEGACY_INSTALL,
}
diff --git a/tests/test_vibe_cli.py b/tests/test_vibe_cli.py
index ad7dda289..1cde1ca73 100644
--- a/tests/test_vibe_cli.py
+++ b/tests/test_vibe_cli.py
@@ -288,6 +288,79 @@ def test_render_status_keeps_a_recorded_error_when_the_service_is_stopped(tmp_pa
assert "stale" not in payload["internal_server"]
+def _age_status_record(seconds: float) -> None:
+ """Backdate the persisted status by `seconds`, leaving everything else alone."""
+
+ path = paths.get_runtime_status_path()
+ status = runtime.read_json(path) or {}
+ status["updated_at"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(time.time() - seconds))
+ runtime.write_json(path, status)
+
+
+def test_render_status_keeps_a_recent_starting_record_over_a_stopped_service(tmp_path, monkeypatch):
+ """The window `starting` exists to cover, and it must still be covered.
+
+ Between the spawn and the moment the child takes the instance lock nothing
+ resolves as running. Reporting that window as `stopped` would make every
+ healthy start look like a failure, so a resolved `stopped` does not overwrite
+ a fresh `starting`.
+ """
+
+ monkeypatch.setattr(paths, "get_vibe_remote_dir", lambda: tmp_path / ".vibe_remote")
+ runtime.ensure_dirs()
+ runtime.write_status("starting", detail="waiting for service process", service_pid=4242)
+ monkeypatch.setattr(runtime, "resolve_service_owner_pid", lambda include_starting=False: None)
+
+ payload = json.loads(runtime.render_status(detect_extra_processes=False))
+
+ assert payload["state"] == "starting"
+
+
+def test_render_status_stops_believing_a_starting_record_that_outlived_its_start(tmp_path, monkeypatch):
+ """`starting` is a claim about a process expected to arrive, so it expires.
+
+ Unlike `setup` and `error`, which describe a machine deliberately not
+ running, `starting` describes one in flight -- and a release that dies inside
+ its own startup leaves that record behind with nothing coming to replace it.
+ Believing it forever is how an instance with no service reports that it is
+ coming up, for eight days. The deadline is `wait_for_service_ready`'s own:
+ past the point where the waiter gives up, the record no longer describes a
+ machine coming up.
+ """
+
+ monkeypatch.setattr(paths, "get_vibe_remote_dir", lambda: tmp_path / ".vibe_remote")
+ runtime.ensure_dirs()
+ runtime.write_status("starting", detail="waiting for service process", service_pid=4242)
+ _age_status_record(runtime.SERVICE_SLOW_START_TIMEOUT_SECONDS + 30)
+ monkeypatch.setattr(runtime, "resolve_service_owner_pid", lambda include_starting=False: None)
+
+ payload = json.loads(runtime.render_status(detect_extra_processes=False))
+
+ assert payload["state"] == "stopped"
+ assert payload["running"] is False
+
+
+def test_render_status_treats_an_undatable_starting_record_as_expired(tmp_path, monkeypatch):
+ """An undatable `starting` that is believed lasts forever.
+
+ Every status write stamps `updated_at`, so a record without a readable one
+ cannot be dated at all -- and the whole point of the deadline is that this
+ state must not be permanent. Defaulting the other way would restore the
+ original bug through the one input the deadline cannot measure.
+ """
+
+ monkeypatch.setattr(paths, "get_vibe_remote_dir", lambda: tmp_path / ".vibe_remote")
+ runtime.ensure_dirs()
+ runtime.write_status("starting", detail="waiting for service process", service_pid=4242)
+ status_path = paths.get_runtime_status_path()
+ runtime.write_json(status_path, {**(runtime.read_json(status_path) or {}), "updated_at": "not a timestamp"})
+ monkeypatch.setattr(runtime, "resolve_service_owner_pid", lambda include_starting=False: None)
+
+ payload = json.loads(runtime.render_status(detect_extra_processes=False))
+
+ assert payload["state"] == "stopped"
+
+
def test_render_status_reports_degraded_show_checkpoints_without_git(monkeypatch):
monkeypatch.setattr("core.git_binary.resolve_git", lambda: None)
@@ -730,7 +803,7 @@ def test_cmd_start_ensures_services_without_stopping(monkeypatch):
"start_ui",
lambda host, port, **kwargs: calls.append(("start_ui", host, port, kwargs)) or 5678,
)
- monkeypatch.setattr(cli.runtime, "service_pid_recorded", lambda pid: True)
+ monkeypatch.setattr(cli.runtime, "wait_for_service_ready", lambda pid, timeout: pid)
monkeypatch.setattr(cli.runtime, "write_status", lambda *args: calls.append(("runtime_status", args)))
assert cli.cmd_start() == 0
@@ -761,7 +834,6 @@ def test_cmd_start_keeps_ui_up_while_service_lock_is_slow(monkeypatch):
"start_ui",
lambda host, port, **kwargs: calls.append(("start_ui", host, port, kwargs)) or 5678,
)
- monkeypatch.setattr(cli.runtime, "service_pid_recorded", lambda pid: False)
monkeypatch.setattr(cli.runtime, "wait_for_service_ready", lambda pid, timeout: None)
monkeypatch.setattr(cli.runtime, "pid_alive", lambda pid: pid == 1234)
monkeypatch.setattr(cli.runtime, "write_status", lambda *args: calls.append(("runtime_status", args)))
@@ -776,6 +848,53 @@ def test_cmd_start_keeps_ui_up_while_service_lock_is_slow(monkeypatch):
assert ("runtime_status", ("starting", "service process is still starting", 1234, 5678)) in calls
+def test_cmd_start_against_a_live_service_neither_resets_its_uptime_nor_skips_the_wait(monkeypatch):
+ """`vibe start` is idempotent, and has to be observably idempotent.
+
+ `write_status` carries `started_at` forward only across consecutive `running`
+ writes, so announcing a `starting` transition for a service this command did
+ not start resets the recorded uptime to now -- every status consumer, the
+ dashboard included, then reads a service that has been up for weeks as one
+ that just began starting.
+
+ The wait is the other half, and it is the half that was broken the other way:
+ the predicate that used to guard it was the service lock, taken before the
+ database is migrated, so it read true for a process that had not finished
+ starting and skipped the wait in exactly the case the wait exists for. So
+ only the provisional write is conditional; the wait is always asked, and a
+ service that is already up answers it on the first probe.
+ """
+
+ calls = []
+ config = SimpleNamespace(
+ has_configured_platform_credentials=lambda: True,
+ ui=SimpleNamespace(setup_host="127.0.0.1", setup_port=5123, open_browser=False),
+ )
+
+ monkeypatch.setattr(cli.paths, "ensure_data_dirs", lambda: None)
+ monkeypatch.setattr(cli, "_ensure_config", lambda: config)
+ monkeypatch.setattr(cli, "_write_status", lambda *args, **kwargs: None)
+ # The live pair: `start_service` hands back the pid that already holds the
+ # lock, which is what makes this a reuse rather than a start.
+ monkeypatch.setattr(cli.runtime, "resolve_service_owner_pid", lambda **kwargs: 1234)
+ monkeypatch.setattr(cli, "_live_ui_server_pid", lambda: 5678)
+ monkeypatch.setattr(cli.runtime, "start_service", lambda **kwargs: 1234)
+ monkeypatch.setattr(cli.runtime, "effective_ui_bind_host", lambda cfg: "127.0.0.1")
+ monkeypatch.setattr(cli.runtime, "start_ui", lambda host, port, **kwargs: 5678)
+ monkeypatch.setattr(
+ cli.runtime,
+ "wait_for_service_ready",
+ lambda pid, timeout=None: calls.append(("wait", pid)) or pid,
+ )
+ monkeypatch.setattr(cli.runtime, "write_status", lambda *args: calls.append(("runtime_status", args)))
+
+ assert cli.cmd_start() == 0
+
+ assert ("wait", 1234) in calls, "the readiness wait must be asked even for a service already up"
+ announced = [args[0] for kind, args in calls if kind == "runtime_status"]
+ assert "starting" not in announced, f"a reused service was announced as starting: {announced}"
+
+
def test_cmd_start_fails_only_when_slow_service_exits(monkeypatch):
config = SimpleNamespace(
has_configured_platform_credentials=lambda: True,
@@ -790,7 +909,6 @@ def test_cmd_start_fails_only_when_slow_service_exits(monkeypatch):
monkeypatch.setattr(cli.runtime, "start_service", lambda **kwargs: 1234)
monkeypatch.setattr(cli.runtime, "effective_ui_bind_host", lambda cfg: "127.0.0.1")
monkeypatch.setattr(cli.runtime, "start_ui", lambda host, port, **kwargs: 5678)
- monkeypatch.setattr(cli.runtime, "service_pid_recorded", lambda pid: False)
monkeypatch.setattr(cli.runtime, "wait_for_service_ready", lambda pid, timeout: None)
monkeypatch.setattr(cli.runtime, "pid_alive", lambda pid: False)
monkeypatch.setattr(cli.runtime, "write_status", lambda *args: statuses.append(args))
@@ -831,7 +949,7 @@ def test_cmd_start_restarts_a_surviving_ui_so_it_shares_the_new_service_secret(m
"start_ui",
lambda host, port, **kwargs: calls.append(("start_ui", kwargs)) or 9012,
)
- monkeypatch.setattr(cli.runtime, "service_pid_recorded", lambda pid: True)
+ monkeypatch.setattr(cli.runtime, "wait_for_service_ready", lambda pid, timeout: pid)
monkeypatch.setattr(cli.runtime, "write_status", lambda *args: None)
assert cli.cmd_start() == 0
@@ -877,7 +995,7 @@ def test_cmd_start_never_signs_with_a_secret_a_reused_service_cannot_verify(
"start_ui",
lambda host, port, **kwargs: calls.append(("start_ui", kwargs)) or 9012,
)
- monkeypatch.setattr(cli.runtime, "service_pid_recorded", lambda pid: True)
+ monkeypatch.setattr(cli.runtime, "wait_for_service_ready", lambda pid, timeout: pid)
monkeypatch.setattr(cli.runtime, "write_status", lambda *args: None)
assert cli.cmd_start() == 0
@@ -910,7 +1028,7 @@ def test_cmd_start_keeps_a_reused_pair_untouched(monkeypatch, capsys):
"start_ui",
lambda host, port, **kwargs: calls.append(("start_ui", kwargs)) or 5678,
)
- monkeypatch.setattr(cli.runtime, "service_pid_recorded", lambda pid: True)
+ monkeypatch.setattr(cli.runtime, "wait_for_service_ready", lambda pid, timeout: pid)
monkeypatch.setattr(cli.runtime, "write_status", lambda *args: None)
assert cli.cmd_start() == 0
@@ -1403,7 +1521,15 @@ def _seed_restart_status(payload: dict, *, age_seconds: float = 0.0) -> Path:
return restart_path
-def _stub_service_liveness(monkeypatch, *, owner_pid=None, starting_pid=None, extra_pids=(), lock_held=None):
+def _stub_service_liveness(
+ monkeypatch,
+ *,
+ owner_pid=None,
+ starting_pid=None,
+ extra_pids=(),
+ lock_held=None,
+ holder_finished_starting=True,
+):
"""Describe a machine state, and let the real predicates read it.
Stubbing ``verified_service_running`` itself would only assert which helper
@@ -1413,10 +1539,15 @@ def _stub_service_liveness(monkeypatch, *, owner_pid=None, starting_pid=None, ex
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
+ case. Pass it True with no ``owner_pid`` for the 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.
+ service has not written it yet or because it was corrupted.
+
+ ``holder_finished_starting`` is the holder's own report, and it is a separate
+ axis from the lock because the lock is taken before the database is migrated:
+ a holder can occupy the instance for days without ever having finished
+ starting. Describing a lock owner without it would describe only half a
+ machine state.
"""
reserved = owner_pid if starting_pid is None else starting_pid
@@ -1428,6 +1559,11 @@ def _stub_service_liveness(monkeypatch, *, owner_pid=None, starting_pid=None, ex
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))
+ monkeypatch.setattr(
+ cli.runtime,
+ "service_instance_started",
+ lambda pid: holder_finished_starting and pid == owner_pid,
+ )
@pytest.mark.parametrize(
@@ -1501,34 +1637,40 @@ def test_the_failure_action_only_tells_the_reader_to_run_real_commands(monkeypat
({"starting_pid": 5555}, "fail"),
({"extra_pids": (7777,)}, "fail"),
({"starting_pid": 5555, "extra_pids": (5555,)}, "fail"),
+ ({"owner_pid": 4321, "holder_finished_starting": False}, "fail"),
+ ({"lock_held": True}, "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-owner-still-starting",
"lock-held-but-its-record-answers-no-pid",
+ "lock-owner-that-finished-starting",
+ "that-owner-beside-a-stray-process",
],
)
-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.
+def test_a_restart_failure_is_downtime_until_a_started_service_says_otherwise(monkeypatch, liveness, expected):
+ """One record against every liveness shape: only a service that finished starting ends downtime.
+
+ The shapes that hold no lock 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.
+
+ The two lock-holding failures are the ones this PR exists for. A holder is not
+ a service by virtue of holding the lock, because the lock is taken before the
+ database is migrated: the fifth shape is a process that took it and hung in a
+ migration, which is #1567's eight-day outage, and the sixth is a holder whose
+ record answers no pid, so nothing it did can be verified at all. Both occupy
+ the instance without serving it, and calling either one recovery is how the
+ outage stayed invisible behind a green health check.
+
+ Only a holder that published its own start ends the failure -- with or without
+ a stray process beside it, which is a separate item's problem.
"""
_seed_restart_status(
diff --git a/vibe/__init__.py b/vibe/__init__.py
index 18de9f035..50fdf7f60 100644
--- a/vibe/__init__.py
+++ b/vibe/__init__.py
@@ -1,6 +1,13 @@
"""avibe - local-first Agent OS runtime."""
+#: The version a build-less tree reports: a source checkout, an editable
+#: install, or a regression environment built with a pretend version. It names no
+#: published release, so anything that has to INSTALL a specific version has to
+#: treat it as "unknown" instead of as a target -- see
+#: `vibe.upgrade.rollback_target`.
+UNKNOWN_VERSION = "0.0.0.dev0"
+
try:
from vibe._version import __version__
except ImportError:
- __version__ = "0.0.0.dev0" # Fallback for editable installs without build
+ __version__ = UNKNOWN_VERSION # Fallback for editable installs without build
diff --git a/vibe/api.py b/vibe/api.py
index 3f4c29f2f..0c237211a 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -6042,6 +6042,7 @@ def do_upgrade(auto_restart: bool = True) -> dict:
vibe_path=current_vibe_path,
trigger="upgrade",
prepare_show_runtime=not should_skip_show_runtime_prepare(),
+ rollback_to=plan.rollback_to,
)
restarting = True
except Exception as exc:
diff --git a/vibe/cli.py b/vibe/cli.py
index 4ffe1f532..47563819f 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -1242,29 +1242,42 @@ def _restart_state_items() -> list[dict]:
# 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.
+ # suppress the very failure it came from. Nor does holding the lock make a
+ # process a service, because the lock is taken before the database is
+ # migrated -- the generation that hung mid-migration in #1567 held it for
+ # eight days -- so the owner also requires the holder's own published start.
+ #
+ # What that leaves the reader is a 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
+ # that starts the service itself. So it names each command once, 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.
+ # reading `ServiceAlreadyRunningError` as a failed recovery.
+ #
+ # The occupier decides which command, and only one of them can be prescribed
+ # blind: `duplicate-service-processes` stops what the scan sees beside the lock
+ # owner, so it reaches a holder whose record answers no pid and skips one that
+ # answers its own -- and a holder stuck mid-startup is exactly the second kind.
+ # `vibe stop` is what covers that one. Anything beyond naming both 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.",
+ "service already running, the failed generation is still occupying this instance: run "
+ "`vibe doctor repair duplicate-service-processes`, which stops a process holding no lock and "
+ "brings the service up, or `vibe stop` if the failed process holds the lock itself, and then "
+ "repeat the start above.",
code="runtime.restart_failed",
)
return items
@@ -11820,19 +11833,13 @@ def _doctor_repair_result(target: str, status: str, message: str, **details) ->
def _write_refreshed_runtime_status() -> None:
+ # Asked, not re-derived. A repair that wrote its own idea of the state word
+ # would be the second place deciding one fact -- and the one that persists
+ # it, so a lock holder still migrating would be recorded as `running` and
+ # every later reader would inherit that answer instead of measuring.
status = runtime.read_status()
- ui_pid = status.get("ui_pid")
- owner_pid = runtime.resolve_service_owner_pid(include_starting=False)
- extra_pids = runtime.extra_service_process_pids(owner_pid=owner_pid)
- if owner_pid:
- detail = f"pid={owner_pid}"
- if extra_pids:
- detail = f"{detail}; extra_service_pids={','.join(map(str, extra_pids))}"
- runtime.write_status("running", detail, owner_pid, ui_pid)
- elif extra_pids:
- runtime.write_status("degraded", f"lockless service process detected pid={extra_pids[0]}", extra_pids[0], ui_pid)
- else:
- runtime.write_status("stopped", "process not running", None, ui_pid)
+ resolved = runtime.resolve_service_state()
+ runtime.write_status(resolved.state, resolved.detail, resolved.service_pid, status.get("ui_pid"))
def _start_service_after_repair(target: str, success_message: str, failure_message: str, *, stopped_pids: list[int]) -> dict:
@@ -12317,20 +12324,31 @@ def cmd_start():
language = normalize_language(getattr(config, "language", None))
print(i18n_t("memory.cli.partialRestartWarning", language))
print("")
- service_ready = runtime.service_pid_recorded(service_pid)
- if not service_ready:
+ # The WAIT below is asked unconditionally. The predicate that used to guard
+ # it is the lock, which is taken before the database is migrated -- so it is
+ # already true of a process that has not finished starting and may never, and
+ # guarding with it skipped the wait in exactly the case the wait exists for.
+ # Nothing is paid for asking: a service that is up answers on the first probe.
+ #
+ # The provisional "starting" WRITE is guarded, and the difference is the
+ # point: `write_status` carries `started_at` forward only across consecutive
+ # `running` writes, so announcing a transition for a service this command did
+ # not start resets its recorded uptime to now and briefly shows a starting
+ # service to every status consumer. `vibe start` against a live instance is
+ # idempotent and must stay observably so.
+ if not service_reused:
runtime.write_status("starting", "waiting for service process", service_pid, ui_pid)
- # Resolve the authoritative service.lock holder rather than waiting on the
- # raw pid start_service handed back: under a delegated user scope that pid
- # can be a launcher that never takes the lock, so wait_for_service_ready
- # adopts and returns the real owner instead of stalling the full timeout.
- resolved_pid = runtime.wait_for_service_ready(
- service_pid,
- timeout=runtime.SERVICE_SLOW_START_TIMEOUT_SECONDS,
- )
- if resolved_pid is not None:
- service_pid = resolved_pid
- service_ready = True
+ # The wait resolves the authoritative service.lock holder rather than waiting
+ # on the raw pid start_service handed back: under a delegated user scope that
+ # pid can be a launcher that never takes the lock, so wait_for_service_ready
+ # adopts and returns the real owner instead of stalling the full timeout.
+ resolved_pid = runtime.wait_for_service_ready(
+ service_pid,
+ timeout=runtime.SERVICE_SLOW_START_TIMEOUT_SECONDS,
+ )
+ service_ready = resolved_pid is not None
+ if resolved_pid is not None:
+ service_pid = resolved_pid
if service_ready:
runtime.write_status("running", "pid={}".format(service_pid), service_pid, ui_pid)
elif runtime.pid_alive(service_pid):
@@ -14036,6 +14054,7 @@ def cmd_upgrade():
vibe_path=current_vibe_path,
trigger="upgrade",
prepare_show_runtime=not should_skip_show_runtime_prepare(),
+ rollback_to=plan.rollback_to,
)
except Exception as exc:
print("\033[33mUpgrade installed, but restart scheduling failed.\033[0m")
@@ -14433,13 +14452,11 @@ def build_parser():
default=0,
help="Schedule the restart to run asynchronously after N seconds, then exit immediately.",
)
- supervisor_parser = subparsers.add_parser("__restart-supervisor", help=argparse.SUPPRESS)
- supervisor_parser.add_argument("--job-id", required=True)
- supervisor_parser.add_argument("--delay-seconds", type=_non_negative_float, default=0)
- supervisor_parser.add_argument("--trigger", default="cli")
- supervisor_parser.add_argument("--scope", default="all", choices=("all", "service"))
- supervisor_parser.add_argument("--vibe-path")
- supervisor_parser.add_argument("--prepare-show-runtime", action="store_true")
+ # `__restart-supervisor` is deliberately absent here. It is never typed: this
+ # program spawns it, and `vibe/restart_supervisor.py` owns both the argv it
+ # builds and the parser that reads it back. Restating those flags here made
+ # this parser a second, silently authoritative owner -- and the one that runs
+ # first. See `_dispatch_restart_supervisor`.
subparsers.add_parser("status", help="Show service status")
doctor_parser = subparsers.add_parser(
"doctor",
@@ -16139,8 +16156,32 @@ def build_parser():
return parser
+def _dispatch_restart_supervisor(argv: list[str]) -> int:
+ """Hand a spawned restart job's own argv straight to its own parser.
+
+ `__restart-supervisor` is not a command a person types; `schedule_restart`
+ builds this argv and `vibe/restart_supervisor.py` parses it back. Declaring
+ those flags on the top-level parser as well made two owners for one command,
+ with a hand-copied translation between them -- and the top-level one runs
+ first, so a flag added only to the supervisor's parser was not merely
+ unavailable, it was rejected. That is how the rollback flags shipped dead:
+ every unit test called `restart_supervisor.main([...])` directly, and the one
+ path that goes through this file was the one path nothing exercised.
+
+ Passing the tail through leaves a single parser for the command, so the two
+ can no longer disagree.
+ """
+
+ from vibe.restart_supervisor import main as restart_supervisor_main
+
+ return restart_supervisor_main(argv)
+
+
def main():
cache_running_vibe_path()
+ argv = sys.argv[1:]
+ if argv and argv[0] == "__restart-supervisor":
+ sys.exit(_dispatch_restart_supervisor(argv[1:]))
parser = build_parser()
args = parser.parse_args()
@@ -16150,24 +16191,6 @@ def main():
sys.exit(cmd_start())
if args.command == "restart":
sys.exit(_cmd_restart_with_delay(args.delay_seconds))
- if args.command == "__restart-supervisor":
- from vibe.restart_supervisor import main as restart_supervisor_main
-
- sys.exit(
- restart_supervisor_main(
- [
- "--job-id",
- args.job_id,
- "--delay-seconds",
- str(args.delay_seconds),
- "--trigger",
- args.trigger,
- *(["--scope", args.scope] if args.scope != "all" else []),
- *(["--prepare-show-runtime"] if args.prepare_show_runtime else []),
- *(["--vibe-path", args.vibe_path] if args.vibe_path else []),
- ]
- )
- )
if args.command == "status":
sys.exit(cmd_status())
if args.command == "memory":
diff --git a/vibe/restart_supervisor.py b/vibe/restart_supervisor.py
index 514191166..615e8f76c 100644
--- a/vibe/restart_supervisor.py
+++ b/vibe/restart_supervisor.py
@@ -9,15 +9,82 @@ import time
import uuid
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
+from typing import NamedTuple
from config import paths
+
+# Imported here, at the top, rather than where the rollback path uses it. This
+# process runs the version being rolled back FROM, and a pinned reinstall
+# replaces the source tree underneath it, so a first import taken after that
+# install reads the OTHER release's source into this process. Importing at module
+# load makes every later use a `sys.modules` hit that touches no file. The module
+# is pure stdlib, so paying for it on every restart costs nothing.
+from storage.backups import find_restorable_backup, next_backup_sequence, restore_sqlite_backup
from vibe import runtime
-from vibe.upgrade import get_restart_command, get_restart_environment, get_restart_invocation_command, get_safe_cwd
+from vibe.upgrade import (
+ RollbackTarget,
+ build_upgrade_plan,
+ get_restart_command,
+ get_restart_environment,
+ get_restart_invocation_command,
+ get_safe_cwd,
+)
logger = logging.getLogger(__name__)
_RESTART_LOG_RETENTION = 10
_SERVICE_LOCK_RELEASE_TIMEOUT_SECONDS = 30.0
+# Long enough for a package index to be slow, short enough that a hung download
+# does not leave the machine sitting with no service forever. A rollback that
+# times out is recorded as failed, which is a diagnosable state; a rollback that
+# waits without a bound is not.
+_ROLLBACK_INSTALL_TIMEOUT_SECONDS = 600.0
+# A cold UI process has an interpreter to start and an ASGI app to import before
+# it answers, so the 5s default of `wait_for_ui_server` -- sized for a UI started
+# next to an already-warm CLI -- is not the right bound here. This one is only
+# ever paid in full when the UI is genuinely not coming.
+_ROLLBACK_UI_READY_TIMEOUT_SECONDS = 60.0
+
+
+class StartedRuntime(NamedTuple):
+ """What a start actually launched, and where its UI can be checked.
+
+ The health target travels with the pids because `_start_runtime_processes` is
+ the only place that resolves it -- it loads the config to decide the bind host
+ and port -- and a caller that recomputed it would become a second answer to
+ "where is the UI", free to drift from the one the UI was actually started on.
+ It is `None` when this job does not own the UI, which is also the answer to
+ whether this job is in a position to judge the UI at all.
+ """
+
+ service_pid: int
+ ui_pid: int | None
+ ui_health_target: tuple[str, int] | None
+
+
+def _live_ui_pid(candidate: object) -> int | None:
+ """The UI pid a `running` status may carry, or None.
+
+ Publishing the pid of a UI that has already exited makes the status file say
+ the Web UI is serving when nothing is listening, and every reader of that
+ file -- doctor, the dashboard, the CLI -- repeats it. Liveness is checked at
+ the moment of the claim rather than assumed from the moment of the spawn.
+ """
+
+ if not isinstance(candidate, int) or candidate <= 0:
+ return None
+ return candidate if runtime.pid_alive(candidate) else None
+
+
+def _ui_is_serving(started: StartedRuntime) -> bool:
+ """Whether the UI this job started is answering its health endpoint."""
+
+ if not started.ui_pid or started.ui_health_target is None:
+ return False
+ if not runtime.pid_alive(started.ui_pid):
+ return False
+ host, port = started.ui_health_target
+ return runtime.wait_for_ui_server(host, port, timeout=_ROLLBACK_UI_READY_TIMEOUT_SECONDS)
def _now_iso() -> str:
@@ -160,7 +227,20 @@ def _runtime_ready_for_config(config) -> bool:
return bool(getattr(getattr(config, "slack", None), "bot_token", ""))
-def _start_runtime_processes(start_ui: bool = True) -> tuple[int, int | None]:
+def _start_runtime_processes(
+ start_ui: bool = True,
+ launcher: runtime.ServiceLauncher | None = None,
+) -> StartedRuntime:
+ """Start the service, and the UI when this job owns it.
+
+ `launcher` is the install to start them from, and `None` means this one --
+ which is the right answer for every restart except a rollback, where this
+ process is running the release being replaced and so is the one install that
+ must not be started. It is taken once here and handed to both spawns, because
+ the service and the UI are two halves of one generation: starting them from
+ different installs is a state neither release was ever tested in.
+ """
+
from core.memory.ui_access import generate_ui_read_secret, process_ui_read_secret
from core.services import settings as settings_service
@@ -185,27 +265,34 @@ def _start_runtime_processes(start_ui: bool = True) -> tuple[int, int | None]:
wait_for_ready=False,
initial_ready_timeout=0,
memory_ui_secret=memory_ui_secret,
+ launcher=launcher,
)
+ ui_health_target: tuple[str, int] | None = None
if start_ui:
bind_host = runtime.effective_ui_bind_host(config)
+ ui_health_target = (bind_host, config.ui.setup_port)
ui_pid = runtime.start_ui(
bind_host,
config.ui.setup_port,
wait_for_ready=False,
memory_ui_secret=memory_ui_secret,
+ launcher=launcher,
)
else:
ui_pid = preserved_ui_pid
- if runtime.service_pid_recorded(service_pid):
- runtime.write_status("running", f"pid={service_pid}", service_pid, ui_pid)
- elif runtime.pid_alive(service_pid):
- runtime.write_status("starting", "waiting for service process", service_pid, ui_pid)
+ # Provisional, and never "running": holding the lock is not having started, so
+ # this helper is not in a position to claim it. Both callers wait for the
+ # service's own report and promote the status themselves. Claiming it here
+ # published `running` to anyone reading the status file -- doctor, the Web UI --
+ # for a process still migrating, which is the same wrong answer one layer down.
+ if runtime.pid_alive(service_pid):
+ runtime.write_status("starting", "waiting for service to finish starting", service_pid, ui_pid)
else:
runtime.write_status("error", "service process exited before startup completed", service_pid, ui_pid)
raise RuntimeError(f"Vibe service process pid={service_pid} exited before acquiring the service lock")
- return service_pid, ui_pid
+ return StartedRuntime(service_pid, ui_pid, ui_health_target)
def _stop_ui_for_restart() -> tuple[bool, dict[str, float | bool], float, int | None]:
@@ -236,6 +323,237 @@ def _stop_runtime_for_restart(stop_ui: bool = True) -> tuple[bool, dict[str, flo
return ui_stopped, ui_timings, stop_ui_seconds, ui_pid, service_stopped, stop_service_seconds
+def _failed_generation_still_running(*, include_ui: bool) -> bool:
+ """Whether anything the failed generation left behind is still alive.
+
+ Measured -- from the lock, the pid file and the process table -- and never
+ read off whether the stop helpers reported killing something. That report
+ answers a different question and answers it backwards on the ordinary case: a
+ version that died in its migration leaves nothing to kill, so `stop_service`
+ says it stopped nothing, exactly as it does for a process that refused to
+ die. The restart path above already knew this and asks
+ `_remaining_service_pids_after_stop` rather than believe the report; asking
+ it here too is what keeps one fact from having two answers.
+ """
+
+ if _remaining_service_pids_after_stop():
+ return True
+ return bool(include_ui and runtime.ui_pid_file_points_to_running_ui())
+
+
+def _restore_database_for_rollback(backup_watermark: int | None, write) -> dict:
+ """Put back the database the version being rolled back from migrated, if it did.
+
+ Whether a migration happened is decided from a number this job read out of
+ the backup window itself before the new version was allowed to start. Any
+ rollback point recorded at or above it was written during that window, so it
+ was written by the version now being rolled back from -- measured by our own
+ code, before and after, with nothing in between that the failing version got
+ to report about itself.
+
+ Every cheaper test compares labels and every one of them is wrong on a real
+ case: the revision stamp and the schema both stay put when a migration
+ commits rows and then fails, and the wall clock reverses the order of two
+ attempts if it is corrected backwards between them. `storage.backups` refuses
+ to answer from those for the same reason.
+
+ No watermark means the job never reached the point of starting the new
+ version, so no migration of its doing can exist and there is nothing to put
+ back. That is a normal outcome, not a degraded one.
+ """
+
+ if backup_watermark is None:
+ return {"restored": False, "reason": "no_migration_window"}
+
+ backups_dir = paths.get_state_backups_dir()
+ rollback_point = find_restorable_backup(backups_dir, written_at_or_after=backup_watermark)
+ if rollback_point is None:
+ write(f"no rollback point was written at or after backup sequence {backup_watermark}; database left as it is")
+ return {"restored": False, "reason": "no_rollback_point"}
+
+ db_path = paths.get_sqlite_state_path()
+ write(f"restoring the database from {rollback_point}")
+ replaced = restore_sqlite_backup(rollback_point, db_path)
+ write(f"database restored; the one it replaced is at {replaced}" if replaced else "database restored")
+ return {
+ "restored": True,
+ "restored_from": str(rollback_point),
+ "replaced_database": str(replaced) if replaced else None,
+ }
+
+
+def _roll_back_failed_upgrade(
+ *,
+ rollback_to: RollbackTarget,
+ vibe_path: str | None,
+ start_ui: bool,
+ backup_watermark: int | None,
+ write,
+ record,
+) -> dict:
+ """Put the machine back on the version it was upgrading from.
+
+ Reached only when a restart has failed AND nothing holds the service lock.
+ That second half is the whole condition, and it is deliberately not a list of
+ the failure branches that ought to qualify: such a list is complete only
+ until the next branch is added, and the branch nobody remembered is exactly
+ the one that leaves an instance dark. "No service is running" is the property
+ the upgrade must not be able to produce, so it is what gets asked -- and it
+ answers correctly for free on the failures that changed nothing, like a stop
+ that did not stop, where the old service is still serving and rolling back
+ underneath it would be the damage.
+
+ Nothing of the failed generation is left running first. "No service is
+ running" is a statement about the lock, and a process can be alive without it
+ -- one that died before reaching it, or one still on its way there. Left
+ alone that process is not merely litter: `start_service` adopts a live
+ recorded pid instead of launching what was just reinstalled, so the rollback
+ would report success while the failed version is what is running, and the
+ restore would rewrite the database file under a process holding it open.
+
+ Install, then restore, then start. The install is the step that needs a
+ package index and so the step most likely to fail, and it is the only one
+ with no effect on the data: failing there leaves the database exactly as the
+ upgrade left it, and a rollback that changed nothing is a far better thing to
+ find than one that half-changed the schema. Restoring before starting is what
+ makes the started version able to read what it finds.
+
+ Each step is recorded before the next begins, because this process can be
+ killed mid-rollback and what it has already done to the database has to be
+ readable afterwards from the status record rather than inferred from the
+ disk.
+
+ Start comes from `rollback_to.launcher`, never from this process. This
+ process is the release the rollback is undoing: an upgrade spawns the restart
+ job through the `vibe` on PATH, which the install has already replaced, so by
+ the time this runs `sys.executable` names the failed generation. Reading it
+ here was how a rollback across the `vibe-remote` -> `avibe-os` rename
+ reinstalled the right release into the right directory, started the wrong one
+ out of the other directory, and recorded success.
+ """
+
+ version = rollback_to.version
+ rollback: dict = {"target_version": version, "state": "running", "started_at": _now_iso()}
+ record(rollback)
+ write(f"rolling back to {version}: no service is running after the failed restart")
+
+ # `start_ui` is also the answer to whether the UI is this job's to manage: a
+ # service-only restart left the running UI alone on purpose, and quiescing
+ # must not take it down when starting will not bring it back.
+ #
+ # The outcome is then measured rather than taken from what the stop helpers
+ # report, because a process that resists termination is the entire reason
+ # this step exists and "did the stop kill something" is not that question.
+ _stop_runtime_for_restart(stop_ui=start_ui)
+ quiesced = not _failed_generation_still_running(include_ui=start_ui)
+ rollback["quiesced"] = quiesced
+ record(rollback)
+ if not quiesced:
+ # Nothing further is safe. The restore rewrites a database file this
+ # process holds open, and the final start adopts its pid instead of
+ # launching what was reinstalled -- so a rollback that continued here
+ # would report success for the version it was rolling back from.
+ rollback.update(
+ state="failed",
+ error=f"the failed generation is still running; not rolling back to {version}",
+ )
+ record(rollback)
+ write(f"cannot roll back to {version}: the failed generation did not stop")
+ return rollback
+
+ try:
+ plan = build_upgrade_plan(vibe_path=vibe_path, version=version, package_name=rollback_to.package)
+ except Exception as exc:
+ rollback.update(state="failed", error=f"cannot build a pinned install for {version}: {exc}")
+ record(rollback)
+ return rollback
+
+ rollback["install"] = {"method": plan.method, "ok": None}
+ record(rollback)
+ try:
+ result = subprocess.run(
+ plan.command,
+ capture_output=True,
+ text=True,
+ env=plan.env,
+ cwd=get_safe_cwd(),
+ timeout=_ROLLBACK_INSTALL_TIMEOUT_SECONDS,
+ )
+ except Exception as exc:
+ rollback["install"] = {"method": plan.method, "ok": False, "error": str(exc)}
+ rollback.update(state="failed", error=f"installing {version} failed: {exc}")
+ record(rollback)
+ return rollback
+ if result.returncode != 0:
+ # The installer's own stderr, trimmed: it is the only account of why the
+ # rollback could not proceed, and the full text can be megabytes of
+ # resolver output.
+ detail = (result.stderr or result.stdout or "").strip()[-2000:]
+ rollback["install"] = {"method": plan.method, "ok": False, "error": detail or f"exit code {result.returncode}"}
+ rollback.update(state="failed", error=f"installing {version} failed with exit code {result.returncode}")
+ record(rollback)
+ write(f"pinned install of {version} failed: {detail}")
+ return rollback
+ rollback["install"] = {"method": plan.method, "ok": True}
+ record(rollback)
+ write(f"installed {version} using {plan.method}")
+
+ try:
+ rollback["database"] = _restore_database_for_rollback(backup_watermark, write)
+ except Exception as exc:
+ rollback["database"] = {"restored": False, "error": str(exc)}
+ rollback.update(state="failed", error=f"restoring the database failed: {exc}")
+ record(rollback)
+ return rollback
+ record(rollback)
+
+ try:
+ started = _start_runtime_processes(start_ui=start_ui, launcher=rollback_to.launcher)
+ except Exception as exc:
+ rollback.update(state="failed", error=f"starting {version} failed: {exc}")
+ record(rollback)
+ return rollback
+ ready_pid = runtime.wait_for_service_ready(started.service_pid, timeout=runtime.SERVICE_SLOW_START_TIMEOUT_SECONDS)
+ if ready_pid is None:
+ rollback.update(
+ state="failed",
+ service_pid=started.service_pid,
+ error=f"{version} started but service pid {started.service_pid} did not finish starting",
+ )
+ record(rollback)
+ return rollback
+
+ # The UI is checked too, and only here. It is started with
+ # `wait_for_ready=False` so a slow asset load cannot stall the service's own
+ # readiness, but not waiting for it is not the same as not checking it: this
+ # rollback is unattended and is the last line of defence, so "the machine is
+ # back" has to mean every process this job took down came back. An ordinary
+ # `vibe restart` deliberately does not gate on this -- a human is watching it,
+ # and failing a restart on a slow UI would be a worse answer than reporting
+ # it (see the PR's known-by-design ledger).
+ ui_serving: bool | None = None
+ if start_ui:
+ ui_serving = _ui_is_serving(started)
+ rollback["ui"] = {"pid": started.ui_pid, "serving": ui_serving}
+ runtime.write_status("running", f"pid={ready_pid}", ready_pid, _live_ui_pid(started.ui_pid))
+ if ui_serving is False:
+ rollback.update(
+ state="failed",
+ service_pid=ready_pid,
+ error=(
+ f"rolled back to {version} and the service is running as pid {ready_pid}, "
+ f"but the Web UI this rollback restarted never started serving"
+ ),
+ )
+ record(rollback)
+ write(f"rolled back to {version} but the Web UI did not come back; service pid={ready_pid}")
+ return rollback
+ rollback.update(state="succeeded", service_pid=ready_pid, error=None)
+ record(rollback)
+ write(f"rolled back to {version}; service pid={ready_pid}")
+ return rollback
+
+
def _wait_for_service_lock_release(timeout: float = _SERVICE_LOCK_RELEASE_TIMEOUT_SECONDS) -> bool:
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
@@ -255,6 +573,7 @@ def _run_restart_job(
trigger: str,
scope: str = "all",
prepare_show_runtime: bool = False,
+ rollback_to: RollbackTarget | None = None,
) -> int:
# "service": restart only the service process, leaving the Web UI process
# running (a config change shouldn't tear down the open Web UI). "all"
@@ -284,6 +603,48 @@ def _run_restart_job(
def mark_duration(name: str, started_at: float) -> float:
return record_duration(name, _rounded_seconds(time.monotonic() - started_at))
+ # The backup sequence read just before the new version was allowed to
+ # start, which is what tells a rollback whether that version migrated the
+ # database. None until then, and None is the right answer for a failure
+ # that never got that far: nothing it could have migrated exists.
+ backup_watermark: int | None = None
+
+ def record_rollback(rollback: dict) -> None:
+ payload["rollback"] = dict(rollback)
+ _write_status(payload)
+
+ def fail(error: str, return_code: int, *, started_at: float | None = None) -> int:
+ """End this job as failed, rolling back first when nothing is running.
+
+ Every failure in this job goes through here rather than each branch
+ deciding whether it is the kind that warrants a rollback. Which
+ branches those are is not knowable as a list -- the next branch added
+ would not be on it -- so the decision is made once, from the state the
+ upgrade must never be able to produce: no service holding the lock.
+ """
+
+ if rollback_to and not runtime.verified_service_running():
+ try:
+ _roll_back_failed_upgrade(
+ rollback_to=rollback_to,
+ vibe_path=vibe_path,
+ start_ui=restart_ui,
+ backup_watermark=backup_watermark,
+ write=write,
+ record=record_rollback,
+ )
+ except Exception as exc:
+ # A rollback that raises must not swallow the failure that
+ # caused it: the original error is what the operator needs,
+ # and the rollback's own is recorded beside it.
+ record_rollback({"target_version": rollback_to.version, "state": "failed", "error": str(exc)})
+ write(f"rollback to {rollback_to.version} raised: {exc}")
+ elif rollback_to:
+ record_rollback(
+ {"target_version": rollback_to.version, "state": "skipped", "reason": "service_running"}
+ )
+ return _fail(payload, error, log, return_code, started_at=started_at)
+
old_pid = _read_recorded_pid()
payload = {
"ok": None,
@@ -299,6 +660,15 @@ def _run_restart_job(
"trigger": trigger,
"delay_seconds": delay_seconds,
"scope": scope,
+ # Recorded whether or not a rollback ends up happening, so a failed
+ # restart with no `rollback` record is readable: armed and killed
+ # before it could recover, versus never recoverable at all. All three
+ # fields of the target, because a record that named the version and
+ # the distribution but not the install would be silent about the one
+ # of the three that has actually been wrong in production.
+ "rollback_to": rollback_to.version if rollback_to else None,
+ "rollback_package": rollback_to.package if rollback_to else None,
+ "rollback_launcher": rollback_to.launcher._asdict() if rollback_to else None,
"old_pid": old_pid,
"new_pid": None,
"log_path": str(log_path),
@@ -324,22 +694,20 @@ def _run_restart_job(
try:
ui_stopped, ui_timings, stop_ui_seconds, ui_pid, stopped, stop_service_seconds = _stop_runtime_for_restart(stop_ui=restart_ui)
except Exception as exc:
- return _fail(payload, f"stop runtime failed: {exc}", log, 2, started_at=restart_started_at)
+ return fail(f"stop runtime failed: {exc}", 2, started_at=restart_started_at)
stage_durations.update(ui_timings)
record_duration("stop_ui_total_seconds", stop_ui_seconds)
record_duration("stop_service_seconds", stop_service_seconds)
mark_duration("stop_runtime_seconds", stop_runtime_started_at)
if restart_ui and ui_pid and ui_stopped is False and runtime.pid_alive(ui_pid):
- return _fail(payload, f"UI pid {ui_pid} did not stop", log, 2, started_at=restart_started_at)
+ return fail(f"UI pid {ui_pid} did not stop", 2, started_at=restart_started_at)
if stopped is False:
remaining_service_pids = _remaining_service_pids_after_stop()
if remaining_service_pids:
payload["remaining_service_pids"] = remaining_service_pids
pid_list = ",".join(str(pid) for pid in remaining_service_pids)
- return _fail(
- payload,
+ return fail(
f"service stop failed; remaining service pid(s): {pid_list}",
- log,
2,
started_at=restart_started_at,
)
@@ -347,15 +715,25 @@ def _run_restart_job(
wait_lock_release_started_at = time.monotonic()
if not _wait_for_service_lock_release():
mark_duration("wait_service_lock_release_seconds", wait_lock_release_started_at)
- return _fail(payload, "service lock did not release after stopping runtime", log, 2, started_at=restart_started_at)
+ return fail("service lock did not release after stopping runtime", 2, started_at=restart_started_at)
mark_duration("wait_service_lock_release_seconds", wait_lock_release_started_at)
+ if rollback_to:
+ # Read here and nowhere else: the service is stopped, its lock is
+ # released, and the new version has not run yet, so this is the last
+ # instant at which the window still holds only what earlier versions
+ # put there. Every backup numbered at or above it afterwards was
+ # written by the version about to start.
+ backup_watermark = next_backup_sequence(paths.get_state_backups_dir())
+ write(f"pre-start backup sequence is {backup_watermark}; rollback target is {rollback_to.version}")
+
write("starting service")
start_runtime_started_at = time.monotonic()
try:
- new_pid, ui_pid = _start_runtime_processes(start_ui=restart_ui)
+ started = _start_runtime_processes(start_ui=restart_ui)
+ new_pid, ui_pid = started.service_pid, started.ui_pid
except Exception as exc:
- return _fail(payload, f"start runtime failed: {exc}", log, 1, started_at=restart_started_at)
+ return fail(f"start runtime failed: {exc}", 1, started_at=restart_started_at)
mark_duration("start_runtime_seconds", start_runtime_started_at)
service_status = runtime.read_status()
@@ -363,27 +741,31 @@ def _run_restart_job(
new_pid = _service_pid_from_status(_read_starting_service_status())
service_status = runtime.read_status()
if not new_pid or not runtime.pid_alive(new_pid):
- return _fail(payload, "start runtime completed but service pid is not alive", log, 3, started_at=restart_started_at)
+ return fail("start runtime completed but service pid is not alive", 3, started_at=restart_started_at)
if not runtime.service_pid_recorded(new_pid):
write(f"start runtime returned while service pid={new_pid} is still acquiring its lock")
- wait_lock_started_at = time.monotonic()
- # Resolve the real lock holder: under a delegated user scope the
- # returned pid may be a launcher that never records itself, so adopt
- # the authoritative owner instead of waiting on a pid that can't win.
- resolved_pid = runtime.wait_for_service_ready(new_pid, timeout=runtime.SERVICE_SLOW_START_TIMEOUT_SECONDS)
- if resolved_pid is None:
- mark_duration("wait_service_lock_seconds", wait_lock_started_at)
- return _fail(
- payload,
- f"service pid {new_pid} did not acquire the service lock",
- log,
- 3,
- started_at=restart_started_at,
- )
- new_pid = resolved_pid
+ wait_lock_started_at = time.monotonic()
+ # Asked unconditionally, and asked of the SERVICE rather than of the lock.
+ # Holding the lock was never the end of starting up -- the database is
+ # migrated and the controller built after it -- so a job that skipped this
+ # whenever the lock had already been taken was skipping it in exactly the
+ # case a bad migration produces: lock acquired, then dead, then a restart
+ # recorded as succeeded over an instance with nothing running.
+ # `wait_for_service_ready` also resolves the real holder, since under a
+ # delegated user scope the returned pid may be a launcher that never
+ # records itself.
+ resolved_pid = runtime.wait_for_service_ready(new_pid, timeout=runtime.SERVICE_SLOW_START_TIMEOUT_SECONDS)
+ if resolved_pid is None:
mark_duration("wait_service_lock_seconds", wait_lock_started_at)
- recorded_ui_pid = service_status.get("ui_pid") if service_status else ui_pid
- runtime.write_status("running", f"pid={new_pid}", new_pid, recorded_ui_pid if isinstance(recorded_ui_pid, int) else None)
+ return fail(
+ f"service pid {new_pid} did not finish starting",
+ 3,
+ started_at=restart_started_at,
+ )
+ new_pid = resolved_pid
+ mark_duration("wait_service_lock_seconds", wait_lock_started_at)
+ recorded_ui_pid = service_status.get("ui_pid") if service_status else ui_pid
+ runtime.write_status("running", f"pid={new_pid}", new_pid, _live_ui_pid(recorded_ui_pid))
mark_duration("restart_total_seconds", restart_started_at)
payload.update(ok=True, state="succeeded", new_pid=new_pid, error=None)
@@ -451,7 +833,26 @@ def schedule_restart(
scope: str = "all",
prepare_show_runtime: bool = False,
memory_ui_secret: str | None = None,
+ rollback_to: RollbackTarget | None = None,
) -> dict:
+ """Spawn the detached restart job.
+
+ `rollback_to` is the install currently on the machine, and passing it is what
+ makes this restart recoverable: if the restart fails and leaves nothing
+ holding the service lock, the job reinstalls exactly that release, puts back
+ the database if the new one migrated it, and starts the service again. Only
+ an upgrade has an answer for it -- a plain restart is already running the
+ version it would roll back to, so there is nothing to reinstall and the
+ failure is the operator's to look at.
+
+ It arrives as one value from `rollback_target()` rather than as a version, a
+ distribution name and an install, because a caller that can pass one without
+ the others eventually does, and what it produces then is a pin naming a
+ release that was never published, or a reinstall of the right release
+ followed by a start of the wrong one. The argv below is the only place the
+ three are apart, and only because a command line has no other shape; `main()`
+ is the only place they are put back together.
+ """
from core.memory.ui_access import process_ui_read_secret
from storage.migrations import guard_source_checkout_default_state_bootstrap
@@ -470,6 +871,24 @@ def schedule_restart(
command.extend(["--vibe-path", vibe_path])
if prepare_show_runtime:
command.append("--prepare-show-runtime")
+ if rollback_to:
+ command.extend(
+ [
+ "--rollback-to",
+ rollback_to.version,
+ # Not optional the way the package name is. A missing package
+ # name still leaves `build_upgrade_plan` a defensible default,
+ # while a missing launcher leaves the job with only its own --
+ # which, in the case this exists for, is the release being
+ # undone.
+ "--rollback-python",
+ rollback_to.launcher.python,
+ "--rollback-main",
+ rollback_to.launcher.main,
+ ]
+ )
+ if rollback_to.package:
+ command.extend(["--rollback-package", rollback_to.package])
env = get_restart_environment(vibe_path=vibe_path)
log_path = _restart_log_path(job_id)
log_path.parent.mkdir(parents=True, exist_ok=True)
@@ -539,7 +958,25 @@ def main(argv: list[str] | None = None) -> int:
parser.add_argument("--scope", default="all", choices=("all", "service"))
parser.add_argument("--vibe-path")
parser.add_argument("--prepare-show-runtime", action="store_true")
+ parser.add_argument("--rollback-to")
+ parser.add_argument("--rollback-package")
+ parser.add_argument("--rollback-python")
+ parser.add_argument("--rollback-main")
args = parser.parse_args(argv)
+ # The one place a rollback target is apart, and so the one place it is put
+ # back together. Reassembling here rather than passing four values inward
+ # means nothing downstream can hold a version without the install it names --
+ # and an incomplete `--rollback-*` set is refused outright rather than
+ # quietly completed from this process, which is the failed release.
+ rollback_to = None
+ if args.rollback_to:
+ if not args.rollback_python or not args.rollback_main:
+ parser.error("--rollback-to requires --rollback-python and --rollback-main")
+ rollback_to = RollbackTarget(
+ version=args.rollback_to,
+ package=args.rollback_package,
+ launcher=runtime.ServiceLauncher(python=args.rollback_python, main=args.rollback_main),
+ )
return _run_restart_job(
job_id=args.job_id,
delay_seconds=max(0.0, args.delay_seconds),
@@ -547,6 +984,7 @@ def main(argv: list[str] | None = None) -> int:
trigger=args.trigger,
scope=args.scope,
prepare_show_runtime=args.prepare_show_runtime,
+ rollback_to=rollback_to,
)
diff --git a/vibe/runtime.py b/vibe/runtime.py
index f6bcae7af..c9c1be7fd 100644
--- a/vibe/runtime.py
+++ b/vibe/runtime.py
@@ -1,3 +1,4 @@
+import calendar
import getpass
import ipaddress
import json
@@ -16,6 +17,7 @@ import urllib.error
import urllib.request
import uuid
from pathlib import Path
+from typing import NamedTuple
import psutil
@@ -38,6 +40,16 @@ SHUTDOWN_INTENT_ENV = "VIBE_REQUIRE_SHUTDOWN_INTENT"
SERVICE_LOCK_READY_TIMEOUT_SECONDS = 5.0
SERVICE_SLOW_START_TIMEOUT_SECONDS = 120.0
+#: The service takes the lock before it migrates the database and builds its
+#: controller, because both of those have to be done under the exclusion the lock
+#: provides. So the lock marks the START of startup, not the end of it, and the
+#: record it writes says which of the two the holder has reached. Anything asking
+#: "is this instance up" has to wait for the second one: a migration that fails
+#: kills the holder, and a watcher that stopped at the lock has already recorded
+#: a success by then.
+SERVICE_PHASE_STARTING = "starting"
+SERVICE_PHASE_RUNNING = "running"
+
def get_package_root() -> Path:
"""Get the root directory of the vibe package."""
@@ -83,6 +95,41 @@ def get_service_main_path() -> Path:
return dev_main_path
+class ServiceLauncher(NamedTuple):
+ """The install that a service or UI process should be started from.
+
+ One value rather than an ambient fact, because there is exactly one case
+ where the answer is not "this process" and it is the case that matters: a
+ rollback that crosses the `vibe-remote` -> `avibe-os` tool rename reinstalls
+ into a different directory than the one the rolling-back process is running
+ out of. Every spawn site read `sys.executable` for itself, so the reinstall
+ succeeded and the failed release was started again -- twice over, since the
+ service and the UI each read it separately and would otherwise have to be
+ fixed separately, and a third spawn site would have to be found and fixed
+ again.
+
+ The interpreter and the entry point travel together because they are one
+ install. Pairing an interpreter with another install's entry point runs the
+ replaced release's code under the replacement's imports, which is neither
+ generation and is the failure this exists to avoid.
+ """
+
+ python: str
+ main: str
+
+
+def current_service_launcher() -> ServiceLauncher:
+ """The install THIS process is running from.
+
+ The default for every spawn, so nothing changes for the ordinary restart:
+ the interpreter that is running is the one that should run the next
+ generation. Only a rollback overrides it, and only because by then this
+ process is no longer the install being started.
+ """
+
+ return ServiceLauncher(python=sys.executable, main=str(get_service_main_path()))
+
+
def get_working_dir() -> Path:
"""Get the working directory for subprocess execution."""
# In development mode, use project root
@@ -254,6 +301,12 @@ def acquire_service_instance_lock() -> None:
holder_pid = _lock_file_pid(lock_file)
lock_file.close()
raise ServiceAlreadyRunningError(lock_path=lock_path, holder_pid=holder_pid)
+ _write_service_instance_lock_record(lock_file, SERVICE_PHASE_STARTING)
+ paths.get_runtime_pid_path().write_text(str(os.getpid()), encoding="utf-8")
+ _SERVICE_INSTANCE_LOCK_HANDLE = lock_file
+
+
+def _write_service_instance_lock_record(lock_file, phase: str) -> None:
lock_file.seek(0)
lock_file.truncate()
lock_file.write(
@@ -263,7 +316,7 @@ def acquire_service_instance_lock() -> None:
"instance_id": uuid.uuid4().hex,
"created_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
"started_at": process_create_time(os.getpid()),
- "phase": "running",
+ "phase": phase,
"command": get_process_command(os.getpid()),
},
indent=2,
@@ -274,8 +327,78 @@ def acquire_service_instance_lock() -> None:
os.fsync(lock_file.fileno())
except OSError:
logger.debug("Failed to fsync service instance lock", exc_info=True)
- paths.get_runtime_pid_path().write_text(str(os.getpid()), encoding="utf-8")
- _SERVICE_INSTANCE_LOCK_HANDLE = lock_file
+
+
+def mark_service_instance_started() -> None:
+ """Record that this service is past startup and into its normal life.
+
+ Called once the database is migrated and the controller is built -- the last
+ point at which a new release can still fail structurally, and so the first
+ point at which "the upgrade worked" is a statement about anything. Whoever
+ started this process is waiting on exactly this write; until it lands, a
+ watcher only knows the lock was taken.
+
+ Rewrites the record through the handle that holds the lock, so the fact and
+ the lock cannot come apart: the kernel drops the lock when this process dies,
+ taking the claim with it.
+ """
+
+ lock_file = _SERVICE_INSTANCE_LOCK_HANDLE
+ if lock_file is None:
+ return
+ _write_service_instance_lock_record(lock_file, SERVICE_PHASE_RUNNING)
+
+
+def read_service_instance_lock_record() -> dict | None:
+ """The service lock record as written by its holder, or None if unreadable."""
+ try:
+ payload = json.loads(get_service_lock_path().read_text(encoding="utf-8") or "{}")
+ except (OSError, json.JSONDecodeError, TypeError, ValueError):
+ return None
+ return payload if isinstance(payload, dict) else None
+
+
+def service_instance_started(pid: int) -> bool:
+ """Whether the service running as ``pid`` has reported it finished starting.
+
+ Keyed on the pid, because the record is the one thing here the holder does not
+ write atomically with the lock: between taking the lock and rewriting the
+ record, the file still holds whatever the PREVIOUS holder last said, and that
+ is a finished startup. The previous holder's pid is in it too, so requiring
+ the two to agree is what keeps a departed instance's record from answering for
+ this one.
+
+ A release that predates the phase distinction wrote ``running`` when it took
+ the lock, so it reads as started immediately. That is the behavior this
+ replaced, kept deliberately: it is what a rollback target on an older version
+ can offer, and demanding a write it will never make would turn every rollback
+ into a reported failure.
+ """
+
+ record = read_service_instance_lock_record()
+ if record is None:
+ return False
+ return record.get("pid") == pid and record.get("phase") == SERVICE_PHASE_RUNNING
+
+
+def service_instance_still_starting(pid: int) -> bool:
+ """Whether ``pid``'s own record says it is still on its way up.
+
+ The mirror of :func:`service_instance_started`, and deliberately not its
+ negation. That one asks whether a new generation PROVED it works, so a
+ missing or unreadable record has to count as no proof. This one is read by
+ everything that reports a state word to a human, where the same absence means
+ only that nothing here knows -- and answering ``starting`` on no evidence
+ would leave a service whose lock record was lost looking stuck forever.
+
+ So only the holder's own record, naming this pid and this phase, moves the
+ word off ``running``. Anything less says what it has always said.
+ """
+
+ record = read_service_instance_lock_record()
+ if record is None:
+ return False
+ return record.get("pid") == pid and record.get("phase") == SERVICE_PHASE_STARTING
def release_service_instance_lock() -> None:
@@ -773,22 +896,31 @@ def verified_service_running() -> bool:
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.
+ That argument does not stop at the lock, and this function used to. A process
+ that acquired the lock and never finished starting is not a working service
+ either -- it is the same failed start one step further along, since the lock is
+ taken BEFORE the database is migrated and the controller built. So the holder
+ must also have published ``SERVICE_PHASE_RUNNING``. Without that, a release
+ that hangs in its migration holds the lock forever and reads as healthy, which
+ is precisely the state the upgrade rollback exists to end.
+
+ A dead holder cannot keep the lock, since the kernel drops it when the process
+ goes, so liveness needs no separate check beyond that.
+
+ This is the one owner of "does this instance have a working service".
+ ``service_instance_lock_available`` owns the different question ``start_service``
+ asks -- whether anything at all would block a second start -- and callers must
+ not mix them: a holder mid-startup blocks a start AND is not yet running, and
+ both answers are correct for their own question.
+
+ Cheap by construction: one open, one non-blocking lock attempt, and one small
+ read, and unlike the broader probe it never scans the process table.
"""
- lock_available, _holder_pid = service_instance_lock_available()
- return not lock_available
+ lock_available, holder_pid = service_instance_lock_available()
+ if lock_available:
+ return False
+ return holder_pid is not None and service_instance_started(holder_pid)
def _pid_reservation_is_fresh(pid_path: Path, pid: int, *, max_age: float = SERVICE_SLOW_START_TIMEOUT_SECONDS) -> bool:
@@ -1187,28 +1319,112 @@ def _pid_mismatches_service(pid: int) -> bool:
return not _command_looks_like_service_entry(command, cwd=cwd)
-def render_status(*, detect_extra_processes: bool = True):
- status = read_status()
+class ServiceState(NamedTuple):
+ """What this data dir's service is doing right now."""
+
+ state: str
+ detail: str
+ service_pid: int | None
+ owner_pid: int | None
+ extra_pids: list[int]
+
+ @property
+ def running(self) -> bool:
+ return self.state in {"running", "degraded"}
+
+
+def resolve_service_state(*, detect_extra_processes: bool = True) -> ServiceState:
+ """The one answer to what state word describes this instance's service.
+
+ Everything that reports or records that word asks here, because the word is
+ the same fact each time and every place that derived it independently got the
+ same case wrong: the lock is taken BEFORE the database is migrated and the
+ controller is built, so its holder occupies this instance long before it can
+ serve anything. Reading that occupancy as `running` is how a release that
+ hung in its migration read as healthy for eight days with nobody served.
+
+ `starting` is therefore a state of its own rather than a shade of running:
+ something is here, it holds the lock, and it is not serving. `degraded` stays
+ what it was -- a service process holding no lock, which is a different fault
+ with a different repair.
+
+ Only a record that positively says so produces `starting`, never the absence
+ of one saying otherwise. This function reports; it does not adjudicate. A
+ machine that lost its lock record has a service on it either way, and telling
+ its owner it is starting -- forever, since nothing will ever write the record
+ it is waiting for -- trades a stuck instance that reads healthy for a healthy
+ instance that reads stuck.
+ """
+
owner_pid = resolve_service_owner_pid(include_starting=False)
extra_pids: list[int] = []
if detect_extra_processes:
extra_pids = extra_service_process_pids(owner_pid=owner_pid)
- running = bool(owner_pid or extra_pids)
if owner_pid:
- status["state"] = "running"
- status["service_pid"] = owner_pid
+ detail = f"pid={owner_pid}"
if extra_pids:
- status["detail"] = f"pid={owner_pid}; extra_service_pids={','.join(str(pid) for pid in extra_pids)}"
- else:
- status["detail"] = f"pid={owner_pid}"
- elif extra_pids:
- status["state"] = "degraded"
- status["service_pid"] = extra_pids[0]
- status["detail"] = f"lockless service process detected pid={extra_pids[0]}"
- elif status.get("state") in {"running", "degraded"}:
- status["state"] = "stopped"
- status["detail"] = "process not running"
- status["service_pid"] = None
+ detail = f"{detail}; extra_service_pids={','.join(str(pid) for pid in extra_pids)}"
+ if service_instance_still_starting(owner_pid):
+ return ServiceState("starting", f"{detail} has not finished starting", owner_pid, owner_pid, extra_pids)
+ return ServiceState("running", detail, owner_pid, owner_pid, extra_pids)
+ if extra_pids:
+ return ServiceState(
+ "degraded",
+ f"lockless service process detected pid={extra_pids[0]}",
+ extra_pids[0],
+ None,
+ extra_pids,
+ )
+ return ServiceState("stopped", "process not running", None, None, [])
+
+
+def _starting_record_outlived_its_start(status: dict) -> bool:
+ """Whether a persisted `starting` has outlived the start it describes.
+
+ `starting` survives a resolved `stopped` on purpose: between the spawn and
+ the moment the child takes the instance lock there is a window where nothing
+ resolves as running, and reporting that window as `stopped` would make every
+ healthy start look like a failure. But unlike `setup` and `error`, `starting`
+ is a claim about a process that is expected to arrive, so it holds only for
+ as long as that arrival is still possible. `wait_for_service_ready` gives up
+ after SERVICE_SLOW_START_TIMEOUT_SECONDS; past that same deadline a
+ `starting` record no longer describes a machine coming up, it describes one
+ that died on the way -- which is the exact failure this change exists to stop
+ reporting as healthy.
+ """
+
+ updated_at = status.get("updated_at")
+ if not isinstance(updated_at, str):
+ return True
+ try:
+ written_at = calendar.timegm(time.strptime(updated_at, "%Y-%m-%dT%H:%M:%SZ"))
+ except (ValueError, TypeError):
+ # Every status write stamps `updated_at`, so a record without a readable
+ # one cannot be dated at all. Treat it as expired rather than as fresh:
+ # an undatable `starting` that is believed lasts forever, and the whole
+ # point of the deadline is that this state must not be permanent.
+ return True
+ return time.time() - written_at > SERVICE_SLOW_START_TIMEOUT_SECONDS
+
+
+def render_status(*, detect_extra_processes: bool = True):
+ status = read_status()
+ resolved = resolve_service_state(detect_extra_processes=detect_extra_processes)
+ owner_pid = resolved.owner_pid
+ extra_pids = resolved.extra_pids
+ running = resolved.running
+ # A resolved `stopped` does not overwrite a persisted `setup`, `starting` or
+ # `error`: those describe a machine with nothing running on purpose, and this
+ # function reports what is running, not what was meant to. `starting` is the
+ # exception with a deadline -- see above -- because it is the only one of the
+ # three that describes something in flight.
+ overwritable = {"running", "degraded"}
+ if status.get("state") == "starting" and _starting_record_outlived_its_start(status):
+ overwritable.add("starting")
+ if resolved.state != "stopped" or status.get("state") in overwritable:
+ status["state"] = resolved.state
+ status["detail"] = resolved.detail
+ status["service_pid"] = resolved.service_pid
if extra_pids:
status["extra_service_pids"] = extra_pids
else:
@@ -1255,6 +1471,31 @@ def _raise_service_start_not_ready(pid: int, *, timeout: float) -> None:
raise RuntimeError(f"Vibe service process pid={pid} did not acquire the service lock")
+def _raise_service_started_but_never_ran(pid: int, *, timeout: float) -> None:
+ """The service was identified and never reported itself up.
+
+ Kept apart from :func:`_raise_service_start_not_ready` because the two are
+ different failures that used to be reported as one. That one means nothing
+ on this machine ever claimed to be the service. This one is the incident
+ behind the rollback work: something did claim it, took the lock, and then
+ died or hung inside its own startup -- which is exactly how an upgrade to a
+ release that cannot start looks from outside, and saying "did not acquire
+ the service lock" about it sends whoever reads the log looking for a lock
+ contention that is not there.
+ """
+
+ owner_pid = resolve_service_owner_pid() or pid
+ if not pid_alive(owner_pid):
+ _clear_service_pid_reservation(owner_pid)
+ raise RuntimeError(f"Vibe service process pid={owner_pid} exited while starting up")
+ if service_instance_still_starting(owner_pid):
+ raise RuntimeError(
+ f"Vibe service process pid={owner_pid} acquired the service lock but did not "
+ f"finish starting within {timeout:.0f} seconds"
+ )
+ _raise_service_start_not_ready(owner_pid, timeout=timeout)
+
+
# --- cgroup resource-governance bootstrap -----------------------------------
#
# ``core/resource_governance.py`` can only move agent subprocesses into a
@@ -1465,18 +1706,38 @@ def _wait_for_scoped_service_pid(spawn_pid: int, timeout: float) -> int | None:
def wait_for_service_ready(
spawn_pid: int, timeout: float = SERVICE_SLOW_START_TIMEOUT_SECONDS
) -> int | None:
- """Wait until the service is lock-verified and return the authoritative owner pid.
-
- Unlike ``wait_for_service_pid()``, which only confirms a *specific* pid, this
- resolves the real ``service.lock`` holder: if the pid handed back by
- ``start_service()`` was a launcher/wrapper that never takes the lock (e.g. a
- surviving ``systemd-run`` parent under some host configuration), this adopts
- and returns the live lock holder instead of waiting forever on a pid that can
- never be recorded. Returns the resolved owner pid, or ``None`` if no owner
- became ready within ``timeout``. In the common case ``spawn_pid`` already IS
- the owner and this behaves like ``wait_for_service_pid`` returning that pid.
+ """Wait until the service has finished starting and return its owner pid.
+
+ Two questions, in order. WHICH process is the service: unlike
+ ``wait_for_service_pid()``, which only confirms a *specific* pid, this
+ resolves the real ``service.lock`` holder, so a pid handed back by
+ ``start_service()`` that was a launcher/wrapper never taking the lock (e.g. a
+ surviving ``systemd-run`` parent under some host configuration) is replaced by
+ the live owner instead of waited on forever. Then: is that process UP --
+ ``SERVICE_PHASE_RUNNING``, which it publishes after migrating the database and
+ building its controller.
+
+ The second question is the one a caller acting on the answer needs. The lock
+ is taken before the migration runs, so a holder can own the lock and then die
+ on it; anything that stopped at the lock reports a healthy start and leaves.
+ That is the whole shape of an upgrade taking an instance dark.
+
+ Returns the resolved owner pid, or ``None`` if none finished starting within
+ ``timeout`` -- including when the owner dies while starting, which is that
+ failure arriving early rather than as a timeout.
"""
- return _wait_for_scoped_service_pid(spawn_pid, timeout)
+ deadline = time.monotonic() + timeout
+ owner_pid = _wait_for_scoped_service_pid(spawn_pid, timeout)
+ if owner_pid is None:
+ return None
+ while True:
+ if service_instance_started(owner_pid):
+ return owner_pid
+ if not pid_alive(owner_pid):
+ return None
+ if time.monotonic() >= deadline:
+ return None
+ time.sleep(0.05)
def _start_scoped_service_result(
@@ -1527,7 +1788,67 @@ def start_service(
wait_for_ready: bool = True,
initial_ready_timeout: float = SERVICE_LOCK_READY_TIMEOUT_SECONDS,
memory_ui_secret: str | None = None,
-):
+ launcher: ServiceLauncher | None = None,
+) -> int:
+ """Start the service and return the pid, by default only once it is up.
+
+ Two questions, and this function exists because they were being answered by
+ the same value. WHICH process is the service is settled below, by taking the
+ spawn lock, reconciling the pid file against the live lock holder and
+ launching if nobody holds it. WHETHER that process is up is settled here,
+ once, for every way the answer can be reached.
+
+ The split is the fix. `_resolve_service_pid()` has seven places it can hand a
+ pid back -- a recorded pid file, a lock holder whose command does not match,
+ a scoped launch adopting its owner, a fresh spawn taking the lock -- and only
+ one of them ever waited for the running phase. Every other caller of
+ `wait_for_ready=True` got "the lock was taken", which is the state an
+ instance is in when the release that took it is about to die on its own
+ migration. The Dashboard recorded that as a started service and the doctor
+ recorded it as a successful repair, both correctly trusting the parameter.
+
+ Waiting out here also takes the wait off the spawn lock, where a slow start
+ used to block every other caller for the length of it.
+
+ Both phases spend one deadline, not one each. `SERVICE_SLOW_START_TIMEOUT_SECONDS`
+ is the budget for a service starting, and taking the lock and reaching the
+ serving state are two phases of that single event -- so passing the constant
+ to each in turn let a start that is slow in both cost a caller twice the
+ number the configuration states, on the Dashboard and doctor paths where
+ someone is waiting for the answer. Measuring from here also makes the bound
+ mean what it says whichever of `_resolve_service_pid`'s several returns
+ produced the pid, including the ones that did no waiting at all.
+ """
+
+ deadline = time.monotonic() + SERVICE_SLOW_START_TIMEOUT_SECONDS
+ pid = _resolve_service_pid(
+ wait_for_ready=wait_for_ready,
+ initial_ready_timeout=initial_ready_timeout,
+ memory_ui_secret=memory_ui_secret,
+ launcher=launcher,
+ )
+ if not wait_for_ready:
+ return pid
+ ready_pid = wait_for_service_ready(pid, timeout=max(0.0, deadline - time.monotonic()))
+ if ready_pid is None:
+ _raise_service_started_but_never_ran(pid, timeout=SERVICE_SLOW_START_TIMEOUT_SECONDS)
+ return ready_pid
+
+
+def _resolve_service_pid(
+ *,
+ wait_for_ready: bool,
+ initial_ready_timeout: float,
+ memory_ui_secret: str | None,
+ launcher: ServiceLauncher | None,
+) -> int:
+ """Which process is the service, starting one if nothing holds the lock.
+
+ Answers only that. Whether the process it names has finished starting is
+ `start_service()`'s to establish -- see its docstring for why that is not
+ left to the individual returns below.
+ """
+
from storage.migrations import guard_source_checkout_default_state_bootstrap
from core.memory.ui_access import process_ui_read_secret
@@ -1546,15 +1867,12 @@ def start_service(
if service_pid_recorded(existing_pid):
return existing_pid
if _pid_reservation_is_fresh(pid_path, existing_pid):
- if not wait_for_ready:
- return existing_pid
- ready_pid = wait_for_service_ready(
- existing_pid,
- timeout=SERVICE_SLOW_START_TIMEOUT_SECONDS,
- )
- if ready_pid is not None:
- return ready_pid
- _raise_service_start_not_ready(existing_pid, timeout=SERVICE_SLOW_START_TIMEOUT_SECONDS)
+ # A reservation this recent names the service whether or
+ # not it is up yet, so the question is answered. Waiting
+ # for the running phase used to happen here, and only
+ # here, which is precisely why every other return below
+ # answered a question it had not asked.
+ return existing_pid
logger.warning(
"Ignoring stale service pid file pid=%s because it never acquired the service lock",
existing_pid,
@@ -1587,7 +1905,7 @@ def start_service(
if extra_pids:
raise ServiceAlreadyRunningError(lock_path=get_service_lock_path(), holder_pid=extra_pids[0])
- main_path = get_service_main_path()
+ launcher = launcher or current_service_launcher()
scope_prefix = maybe_systemd_scope_prefix()
if scope_prefix:
logger.info("cgroup scope bootstrap: launching service inside a delegated user scope")
@@ -1597,7 +1915,7 @@ def start_service(
else {}
)
process = spawn_service_background_process(
- [*scope_prefix, sys.executable, str(main_path)],
+ [*scope_prefix, launcher.python, launcher.main],
"service_stdout.log",
"service_stderr.log",
env={
@@ -1759,6 +2077,7 @@ def start_ui(
*,
wait_for_ready: bool = True,
memory_ui_secret: str | None = None,
+ launcher: ServiceLauncher | None = None,
):
from core.memory.ui_access import process_ui_read_secret
@@ -1786,6 +2105,10 @@ def start_ui(
)
pid_path.unlink(missing_ok=True)
+ # Named entry point, not a body of code: whatever release the launcher's
+ # interpreter belongs to supplies its own `run_ui_server`. A rollback that
+ # sent source text across the generation boundary would run the replacement's
+ # idea of startup inside the replaced install.
command = "from vibe.ui_server import run_ui_server; run_ui_server('{}', {})".format(host, port)
spawn_kwargs = (
{"memory_ui_secret": memory_ui_secret}
@@ -1793,7 +2116,7 @@ def start_ui(
else {}
)
pid = spawn_background(
- [sys.executable, "-c", command],
+ [(launcher or current_service_launcher()).python, "-c", command],
pid_path,
"ui_stdout.log",
"ui_stderr.log",
diff --git a/vibe/upgrade.py b/vibe/upgrade.py
index 884611cb3..bd20fc25a 100644
--- a/vibe/upgrade.py
+++ b/vibe/upgrade.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import json
+import logging
import os
import re
import shlex
@@ -11,8 +12,12 @@ import urllib.request
from collections.abc import Mapping
from dataclasses import dataclass
from pathlib import Path
-from typing import cast
+from typing import NamedTuple, cast
+from vibe import runtime as runtime_mod
+
+
+logger = logging.getLogger(__name__)
PACKAGE_NAME = "avibe-os"
LEGACY_PACKAGE_NAME = "vibe-remote"
@@ -21,6 +26,14 @@ CURRENT_VIBE_EXECUTABLE_ENV = "VIBE_CURRENT_EXECUTABLE"
SHOW_RUNTIME_SKIP_ENV = "VIBE_INSTALL_SKIP_SHOW_RUNTIME"
TRUTHY_ENV_VALUES = {"1", "true", "yes", "on"}
UV_FALLBACK_BIN_DIRS = (".local/bin", ".cargo/bin")
+# A spec that names nothing but a package, so appending ``==<version>`` to it
+# yields a requirement rather than a broken string. PEP 508 names only:
+# anything with a path separator, a URL scheme, extras, a marker, or a version
+# of its own is deliberately excluded. See `pinned_package_spec`.
+_BARE_PACKAGE_NAME_RE = re.compile(r"[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?")
+# uv names a tool's directory after the distribution it installed, so this reads
+# back the name THIS process was installed under. See `installed_package_name`.
+_UV_TOOL_PATH_RE = re.compile(r"/uv/tools/(?P<name>[^/]+)/")
# PEP 440-ish parser: release + optional pre-release (a/b/rc) + optional
# post + optional dev, plus a local version segment (``+local``) that we
# accept but ignore for ordering. Word forms (alpha/beta/preview) are listed
@@ -49,9 +62,28 @@ _PRE_ORDER = {
@dataclass(frozen=True)
class UpgradePlan:
+ """A command that installs a version of avibe, and what it will replace.
+
+ `rollback_to` travels with the command because of WHEN it has to be taken,
+ not because the two are related ideas. It describes the install this command
+ is about to overwrite, and running the command is what destroys the evidence
+ it is read from -- so the only safe moment to take it is before there is a
+ command to run.
+
+ Left as a function the caller was told to call early, both call sites called
+ it late: after `subprocess.run(plan.command)` had already installed
+ `avibe-os` over a `vibe-remote` machine, so the question "what was this
+ install published as" had two answers and returned neither, and the rollback
+ pinned `avibe-os==2.x`, a release that was never published under that name.
+ Writing the ordering rule into a docstring is what failed; a field cannot be
+ called late, because there is no plan without the measurement and no install
+ without the plan.
+ """
+
command: list[str]
env: dict[str, str] | None
method: str
+ rollback_to: RollbackTarget | None = None
def resolve_command_path(command: str | None, search_path: str | None = None) -> str | None:
@@ -435,6 +467,164 @@ def is_legacy_uv_tool_install(python_executable: str | None = None) -> bool:
return f"/uv/tools/{LEGACY_PACKAGE_NAME}/" in executable
+def installed_package_name(python_executable: str | None = None) -> str | None:
+ """The distribution this install was published as.
+
+ Which distribution published the running version is not the same question as
+ which one the next install should ask for, and the two genuinely differ: a
+ machine still on `vibe-remote` upgrades to `avibe-os`, that being the rename.
+ Anything going FORWARD wants the configured spec. Anything going BACK wants
+ this, because `avibe-os==2.x` names a release that was never published under
+ that name and an install of it can only fail.
+
+ Asked of the installed metadata first, because that is where the answer
+ actually is: the distribution that provides the running `vibe` package says
+ so itself, whatever layout it was installed into. Reading it off the
+ interpreter path recognised exactly one layout -- uv's tool directory -- and
+ answered `None` for every supported install that is not one, pip into a
+ virtualenv among them. `None` there is not neutral: the caller falls back to
+ the configured FORWARD package, so a `vibe-remote` install in a virtualenv
+ armed a rollback to `avibe-os==2.x` and spent the one recovery attempt on a
+ release that was never published.
+
+ The path heuristic stays as the fallback for the case metadata genuinely
+ cannot answer -- a source checkout, or providers that record the same release,
+ where naming one would be a guess. `None` when neither can say, which is the
+ honest answer for a tree that was never installed at all.
+ """
+
+ executable = (python_executable or sys.executable or "").replace("\\", "/")
+ # Only this process can be asked about its own metadata. A path belonging to
+ # some OTHER interpreter is answerable only by the layout it is written in.
+ if not python_executable or executable == (sys.executable or "").replace("\\", "/"):
+ distributions = _distributions_providing_this_package()
+ if len(distributions) == 1:
+ return distributions[0]
+ # More than one provider is not an unanswerable environment. It is the
+ # state a rollback leaves behind and never cleans up, so it is the state
+ # every subsequent upgrade measures its own rollback target in -- see
+ # `_providers_describing_running_code`.
+ describing = _providers_describing_running_code()
+ if len(describing) == 1:
+ return describing[0]
+
+ match = _UV_TOOL_PATH_RE.search(executable)
+ return match.group("name") if match else None
+
+
+def _distributions_providing_this_package() -> list[str]:
+ """Every installed distribution that provides the package this module is in."""
+
+ try:
+ from importlib.metadata import packages_distributions
+ except ImportError: # pragma: no cover - importlib.metadata ships with 3.10+
+ return []
+ try:
+ return sorted(set(packages_distributions().get(__name__.split(".")[0], [])))
+ except Exception: # pragma: no cover - a broken environment answers nothing
+ logger.debug("Failed to read installed distribution metadata", exc_info=True)
+ return []
+
+
+def _providers_recording_a_published_release() -> list[tuple[str, str]]:
+ """Every distribution providing this package, with the release it records.
+
+ Unpublished recordings are dropped rather than reported. A `dev` or local
+ version records the tree it was built from, so it can neither confirm nor
+ contradict a released one, and an environment that answers nothing at all --
+ no provider, unreadable metadata, nothing published -- comes back empty. Both
+ callers read empty as "no evidence", never as evidence of disagreement.
+ """
+
+ distributions = _distributions_providing_this_package()
+ if not distributions:
+ return []
+ try:
+ from importlib.metadata import version as distribution_version
+
+ recorded = [(name, distribution_version(name)) for name in distributions]
+ except Exception: # pragma: no cover - a broken environment answers nothing
+ logger.debug("Failed to read the installed distribution version", exc_info=True)
+ return []
+ return [(name, version) for name, version in recorded if _names_a_published_release(version)]
+
+
+def _providers_describing_running_code() -> list[str]:
+ """The providers whose recorded release is the one this process is running.
+
+ One owner for a question two callers ask for different purposes:
+ `installed_package_name` wants WHICH provider describes the files on disk,
+ and `installed_metadata_describes_running_code` wants WHETHER they all do.
+ Answering them separately is how the rename pair got two different rulings one
+ function apart -- the second was taught that two providers is the state it
+ exists for, while the first went on reading it as unanswerable.
+
+ That asymmetry is not academic, because the pair is permanent: installing
+ `avibe-os` over a `vibe-remote` machine never uninstalls the older
+ distribution, so once a rollback has crossed the rename the tree holds both
+ forever. `avibe-os` records the release that failed and `vibe-remote` records
+ the files actually running, and the metadata is what distinguishes them --
+ naming neither meant every later upgrade armed its rollback with no
+ distribution, and `pinned_package_spec` fell back to the configured forward
+ name. `avibe-os==2.9.0` was never published, so that one recovery attempt
+ could only fail, on a machine that is already down.
+ """
+
+ from vibe import __version__
+
+ return [
+ name
+ for name, recorded in _providers_recording_a_published_release()
+ if recorded == __version__
+ ]
+
+
+def installed_metadata_describes_running_code() -> bool:
+ """Whether the installed distribution's recorded version matches the files.
+
+ pip decides whether to act by reading metadata, and a rollback is the one
+ operation that makes metadata stop describing the code. Installing `avibe-os`
+ over a `vibe-remote` machine never uninstalls the older distribution, so
+ after the rollback reinstalls `vibe-remote==3.0.10` the tree holds two: the
+ files under `vibe/` are 3.0.10, and `avibe-os` still records 3.0.11 with
+ nothing on disk to back it.
+
+ The next forward upgrade is then a silent no-op. `vibe upgrade` compares this
+ process's 3.0.10 against the published 3.0.11 and decides to install; pip
+ reads `avibe-os==3.0.11` as already satisfied and does nothing; the command
+ reports success and the machine keeps running 3.0.10. Same shape as the
+ rollback no-op, one release later and with a person watching it happen.
+
+ Measured by comparing our own two answers rather than by trusting either --
+ the version this process bound at import against the version the metadata
+ records for each distribution providing it. Unknown answers `True`: only a
+ disagreement between two published releases is evidence, so a source checkout
+ or an editable install is never forced on a guess.
+
+ Every provider is asked, not just a single one, because the rename pair is
+ the state this exists for: after a rollback across `vibe-remote` ->
+ `avibe-os` the tree holds BOTH, and only one of them can be describing the
+ files on disk. Treating "more than one provider" as unknown would have made
+ the exact state described above the one state that answers `True` -- the
+ check declining to fire on its own scenario. `installed_package_name` reads
+ the same measurement for the other half of that state; both go through
+ `_providers_describing_running_code` so neither can be taught it alone.
+ """
+
+ from vibe import __version__
+
+ if not _names_a_published_release(__version__):
+ return True
+
+ published = _providers_recording_a_published_release()
+ if not published:
+ return True
+ # Metadata describes the code only if EVERY provider recording a published
+ # release records this one; a single dissenter is a distribution pip would
+ # read as already satisfied.
+ return len(_providers_describing_running_code()) == len(published)
+
+
def get_current_vibe_bin_dir(vibe_path: str | None = None) -> str | None:
current_vibe = get_running_vibe_path(vibe_path=vibe_path)
if not current_vibe:
@@ -443,35 +633,201 @@ def get_current_vibe_bin_dir(vibe_path: str | None = None) -> str | None:
return get_launcher_bin_dir(current_vibe)
+class RollbackTarget(NamedTuple):
+ """The install being replaced, described completely enough to restore it.
+
+ Every field travels with the others because they are one measurement, and
+ splitting them is exactly how this went wrong, repeatedly and in the same
+ shape each time: the version was read in the process that predates the
+ install and the distribution in the one that follows it, so a `vibe-remote`
+ machine pinned `avibe-os==2.9.4`, a release that never existed. Then the same
+ seam reappeared one step later -- the right distribution reinstalled, and the
+ service started from whatever interpreter the restarting process happened to
+ be running, which after a rename is the tool that replaced this one. It put
+ the failed release back up and reported the rollback a success.
+
+ So the rule is that nothing about the replaced install is looked up again
+ later. Anything a rollback needs to know about it is measured here, once, in
+ the only process that can still see it, and carried. There is no constructor
+ that reads one field.
+ """
+
+ version: str
+ package: str | None
+ launcher: runtime_mod.ServiceLauncher
+
+
+def _names_a_published_release(version: str) -> bool:
+ """Whether an index could serve `version`, as opposed to it naming this tree.
+
+ A development build's version describes the tree it was built from rather
+ than anything published: PEP 440 spells that as a `dev` segment, a local
+ segment (`+<sha>`), or both, and the regression builder emits exactly that
+ shape. Testing for one hard-coded sentinel string recognised the fallback
+ version and nothing else, so a regression instance armed a rollback to
+ `avibe-os==0.0.0.dev0+<sha>` and spent its one recovery attempt asking an
+ index for a release that cannot exist there.
+
+ Asking the property instead of listing the strings is what stops the next
+ unlisted shape from costing the same attempt. Unparseable reads as
+ unpublished for the same reason: a version this codebase cannot even order is
+ not one it should pin an install to.
+ """
+
+ match = _VERSION_RE.match(version)
+ if match is None:
+ return False
+ return not (match.group("dev") or match.group("local"))
+
+
+def rollback_target() -> RollbackTarget | None:
+ """The install a failed restart of THIS process could be put back on.
+
+ Everything here is measured from the running process, and that is the whole
+ point rather than an implementation detail: this describes the install the
+ upgrade is about to replace, and once it has been replaced there is nothing
+ left on the machine to measure. Calling this from the detached restart job
+ would answer for the install that did the replacing, which is not a rollback.
+
+ Which is why the only caller is :func:`build_upgrade_plan`, and why the
+ answer reaches everyone else as `UpgradePlan.rollback_to`. As a function
+ anyone could reach, it was reached at the wrong time -- both upgrade paths
+ called it after the install they were describing had already been overwritten.
+
+ So: the version from this process's already-bound `__version__`, which the
+ install on disk cannot change underneath it; the distribution from this
+ install's own metadata; and the launcher that started this process, because
+ reinstalling a distribution does not tell anyone how to run it and a rollback
+ that crosses the `vibe-remote` -> `avibe-os` rename lands in a different tool
+ directory than the one this process is running out of.
+
+ `None` when the running tree reports no release an index could serve -- a
+ source checkout, an editable install, a regression build. Handing that string
+ on as a target would spend the one recovery attempt on a round-trip that
+ fails, and then report a broken rollback mechanism to whoever is looking at a
+ dark instance, when the truth is that this install never had a release to go
+ back to.
+ """
+
+ from vibe import __version__
+
+ if not _names_a_published_release(__version__):
+ return None
+ return RollbackTarget(
+ version=__version__,
+ package=installed_package_name(),
+ launcher=runtime_mod.current_service_launcher(),
+ )
+
+
+def pinned_package_spec(
+ version: str, *, python_executable: str | None = None, package_name: str | None = None
+) -> str:
+ """The distribution this install came from, pinned to exactly one version.
+
+ `package_name` is the name measured before the forward install ran, and it
+ wins when given. Reading the name here instead would read it on the wrong side
+ of the event: the upgrade replaces the tool before it schedules the restart,
+ so by the time the detached supervisor asks, the install it can see is the new
+ one. Only the caller that ran before the install can answer for what was
+ replaced.
+
+ Falling back to the install on disk, and to configuration after that. A pin is
+ a claim that a specific release exists under a specific name, and something
+ has to witness which name that was.
+
+ Raises when the resulting name cannot carry a pin -- a local path, a direct
+ URL, or a spec that already states its own version. Refusing is the whole
+ point of the function existing: the caller that wants a pin is rolling back,
+ and an unpinned command resolves forward to the release it is rolling back
+ FROM, reinstalling the failure and reporting success. A rollback that cannot
+ be pinned has to fail loudly instead.
+
+ The message never quotes the spec. An operator-supplied spec can be an index
+ URL carrying credentials, and this error is written to a restart log.
+ """
+
+ spec = package_name or installed_package_name(python_executable) or get_upgrade_package_spec()
+ if _BARE_PACKAGE_NAME_RE.fullmatch(spec) is None:
+ raise ValueError("The configured upgrade package spec cannot carry a version pin")
+ return f"{spec}=={version}"
+
+
def build_upgrade_plan(
*,
python_executable: str | None = None,
uv_path: str | None = None,
vibe_path: str | None = None,
base_env: dict[str, str] | None = None,
+ version: str | None = None,
+ package_name: str | None = None,
) -> UpgradePlan:
+ """How to install avibe: the newest release, or `version` exactly.
+
+ A pinned plan is not an upgrade plan with an extra argument. It never asks
+ for the newest release, because the caller pinning a version is going
+ backwards from one -- and both package managers treat "upgrade" as a
+ direction, not a preference: uv resolves forward past the pin's own
+ requirement, and pip's `--upgrade` declines to install an older version than
+ the one already there. So the pin replaces the upgrade request rather than
+ qualifying it, and `--force` becomes unconditional on the uv path, where
+ installing over an existing tool is otherwise refused.
+ """
+
executable = python_executable or sys.executable
+ # Taken here, before the command below exists, because that command is what
+ # makes it unanswerable. A pinned plan is itself a rollback and has none of
+ # its own: the process building one is the release that failed, so measuring
+ # there would carry the failure forward as its own recovery target.
+ rollback_to = None if version else rollback_target()
uv_binary = find_uv_binary(uv_path=uv_path, base_env=base_env)
- package_spec = get_upgrade_package_spec()
+ package_spec = (
+ pinned_package_spec(version, python_executable=executable, package_name=package_name)
+ if version
+ else get_upgrade_package_spec()
+ )
if is_uv_tool_install(executable) and uv_binary:
env = dict(base_env or os.environ)
vibe_bin_dir = get_current_vibe_bin_dir(vibe_path)
if vibe_bin_dir:
env["UV_TOOL_BIN_DIR"] = vibe_bin_dir
- command = [uv_binary, "tool", "install", package_spec, "--upgrade"]
- if package_spec != PACKAGE_NAME or is_legacy_uv_tool_install(executable):
+ command = [uv_binary, "tool", "install", package_spec]
+ if not version:
+ command.append("--upgrade")
+ if version or package_spec != PACKAGE_NAME or is_legacy_uv_tool_install(executable):
command.append("--force")
return UpgradePlan(
command=command,
env=env,
method="uv",
+ rollback_to=rollback_to,
)
+ command = [executable, "-m", "pip", "install"]
+ if not version:
+ command.append("--upgrade")
+ # Neither a pin nor `--upgrade` makes pip act; metadata does, and a rollback
+ # is what makes metadata stop describing the code. So the command forces
+ # whenever the version being asked for is not already the version on disk --
+ # measured here, never read off the metadata that is the thing in doubt.
+ #
+ # A pinned plan always forces: it IS the rollback, running on a machine where
+ # `avibe-os` was just installed over `vibe-remote`, so `pip install
+ # vibe-remote==<old>` reads as already satisfied, pip does nothing, and the
+ # supervisor starts the failed generation again and reports success. The uv
+ # branch above has always forced a pinned install; this branch quietly did
+ # not. A forward plan forces only once that has happened -- the leftover
+ # `avibe-os==3.0.11` metadata would otherwise make the next upgrade a no-op
+ # too, silently, with a person watching it report success.
+ if version or not installed_metadata_describes_running_code():
+ command.append("--force-reinstall")
+ command.append(package_spec)
return UpgradePlan(
- command=[executable, "-m", "pip", "install", "--upgrade", package_spec],
+ command=command,
env=dict(base_env or os.environ),
method="pip",
+ rollback_to=rollback_to,
)