Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(regression): make worktree cleanup and the ui device honest (#1614)

Call White594c94a4a2c1
diff --git a/AGENTS.md b/AGENTS.md
index b3529d55d..753cc0cbb 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -112,9 +112,32 @@ Hard rules:
preparation, readiness checks, Show Runtime setup, metadata, and cleanup
- `master` is the long-running unified four-platform environment; keep it online,
preserve product state, sync source, and restart the service in place
-- `worktree` targets are temporary isolated environments; delete with
- `python3 scripts/incus_regression.py delete --target worktree --yes` or
- `cleanup-stale --yes` when merged, abandoned, or stale
+- `worktree` targets are temporary isolated environments; delete each one
+ explicitly with
+ `python3 scripts/incus_regression.py delete --target worktree --slug <slug> --yes`
+ when merged, abandoned, or stale
+- `reconcile` lists every worktree environment Incus holds — including ones
+ created outside the runner, which no metadata-driven command can see — and
+ forgets metadata rows whose environment is already gone. It never deletes an
+ environment: no recorded field can prove one is unwanted, so that call stays
+ with the operator. It reports the names the daemon gave, never re-derived from
+ the slug, because a discovered name is bounded by what Incus accepts and
+ `--slug` is stricter; one it would reject gets its objects named for a manual
+ reclamation instead of a command that would exit on its own argument
+- a metadata row is dropped only when the daemon that owns it completed a
+ listing whose every entry was readable, that listing held neither its project
+ nor its instance, and the row is not a reservation whose `up` may still be
+ running. A reservation lives exactly as long as its run: an `up` that fails
+ gives its row back while the daemon reports no project for that slug and the
+ row is still the one that run wrote, both read at that moment rather than
+ remembered from an earlier one — so a project that may bind the port, a
+ listing that cannot answer, and a concurrent `up` that took the slug over all
+ keep the row. `worktrees.json` is reached only through an accessor bound to the
+ daemon it describes — it reserves host ports on this machine and records what
+ this machine's daemon holds — so a `--remote` command cannot name it and
+ neither reads nor writes it: `reconcile --remote` reports the remote inventory
+ with no local provenance, `delete --remote` keeps the local row, and
+ `up --remote` requires `--host-port`
- never use `--reset-config` / `--reset-all`, wipe regression state, or overwrite
Avibe Cloud pairing / `remote_access` just to make probes pass unless asked
- after any regression update, verify service health before reporting success
diff --git a/docs/regression/README.md b/docs/regression/README.md
index 7e653ca3c..ed7cfdb39 100644
--- a/docs/regression/README.md
+++ b/docs/regression/README.md
@@ -124,13 +124,137 @@ Temporary worktree environment:
python3 scripts/incus_regression.py up --target worktree
python3 scripts/incus_regression.py status --target worktree
python3 scripts/incus_regression.py delete --target worktree --yes
-python3 scripts/incus_regression.py cleanup-stale --yes
+python3 scripts/incus_regression.py reconcile
+python3 scripts/incus_regression.py reconcile --yes
```
Delete worktree environments promptly after the worktree is merged, abandoned,
or removed. The persistent `master` environment should stay running and preserve
its product state across normal source updates.
+`reconcile` answers "what is actually still here?". It enumerates worktree
+environments from Incus rather than from the runner's metadata, so an
+environment created outside the runner shows up too — otherwise it is invisible
+to every command that reads `.runtime/incus-regression/worktrees.json`, and can
+only be removed by hand. For each one it prints what Incus was observed to hold
+— its project and its instance, reported separately, because an environment can
+be half gone — plus whatever provenance the metadata holds and the `delete`
+command that removes it. Every instance Incus reported under that name is listed,
+because Incus scopes instance names per project and one name can be several
+instances. An instance living in a project other than the one its slug implies is
+listed with that project and warned about by hand: `delete --slug` derives the
+project from the slug, so it would report success without touching the instance.
+An environment holding both kinds gets both the command and the warning — one
+statement covers what the convention reaches, the other what it does not.
+
+Those names are the ones the daemon reported, never derived a second time from
+the slug. A slug here is an observed name with a known prefix removed, so it is
+bounded by what Incus accepts rather than by what the runner would choose — and
+`--slug` is stricter than Incus. A discovered name the runner would not have
+minted therefore gets no command at all: the report names its project and
+instance for a manual reclamation instead of printing a `delete --slug` that
+would exit on its own argument.
+
+Deletion stays a separate, explicit call. Nothing recorded about an environment
+can prove it is no longer wanted: the recorded path is the checkout the runner
+was invoked from, shared by every environment created there and still present
+long after that worktree is gone; the slug is chosen by the caller; and an
+environment may sit on a detached HEAD with no branch whose merge status could
+be checked. `reconcile --yes` therefore changes exactly one thing — it drops
+metadata rows for environments Incus no longer has, releasing their reserved
+host ports. Without `--yes` it only reports, and `--dry-run` withholds the write
+even with it.
+
+Reporting is what the command is for, so having something to report is not a
+failure: `reconcile` exits 0 whether or not any row was stale. A non-zero exit
+for the case the command exists to show cannot be told apart from a command that
+broke, by a `&&` chain, a CI step, or anyone reading `$?` — while the report it
+just printed says the run went fine.
+
+"No longer has" is read strictly, because releasing a port that is still in use
+is worse than keeping a row nobody needs:
+
+- The daemon must have completed a listing that held neither the environment's
+ project nor its instance, and every entry in that listing must have been
+ readable. A daemon that could not be reached, or an entry the runner could not
+ identify, is an unanswered question rather than an absence, and aborts instead.
+- A row whose slug a live `up` is still holding is left alone. `up` records the
+ slug and its port before it creates the project and the instance, so this is
+ what a concurrent `up` looks like from the outside. Who holds a slug is asked
+ of the kernel, not of the file: an `up` takes that environment's update lock —
+ named by the daemon and the project, so a `--remote` run is never read as the
+ local environment of the same name — before it writes the row and holds it until
+ the environment is built, so `reconcile` answers the question by trying to take
+ the same lock. Every command that changes what a slug names holds it, not just
+ `up`: a `delete` takes it across removing the objects and forgetting the row,
+ and stops rather than waiting when somebody else has it. Those two halves are
+ one change, and a delete that split them around a live `up` would remove
+ nothing — the objects do not exist yet — drop that run's reservation anyway,
+ and leave the finished environment untracked with its host port free for the
+ next slug. Nothing a run writes
+ could answer it. A record over-reports — a run killed outright leaves its own
+ behind — and under-reports, since a run from an older checkout writes no field
+ a newer `reconcile` would recognise; a lock does neither, because the kernel
+ drops it however the run ends and every version of the runner that builds a
+ worktree environment takes the same one. So an abandoned reservation is
+ reported as an environment the daemon no longer has and `--yes` prunes it,
+ while a live run's row is kept without any operator having to tell the two
+ apart. Not knowing counts as held: a platform without `flock`, or a lock file
+ that cannot be opened, keeps the row like every other unanswered question here.
+ Two things the rule does not cover, and both are in older checkouts rather than
+ in the rule. Their `up` writes the row and then takes the lock, so a
+ `reconcile --yes` landing between the two prunes a reservation whose build is
+ about to start. What that exposes is those two operations and not the build:
+ between releasing the mapping lock and acquiring the update lock they run one
+ `git rev-parse` and the two lock calls, and contention shortens the window
+ rather than widening it, since a slug whose lock somebody is already holding
+ reads as in flight. The older run then repairs the row itself, because its `up`
+ rewrites the mapping when the build finishes. What is left of it needs a third
+ `up` to start inside that same window and take the freed port, and that ends
+ loudly: an `up` creating a local environment re-checks the host port inside its
+ own update lock before it builds. Their `up` also keys the lock on the project
+ alone, so a released `up --remote` takes the local environment's lock and reads
+ as a local run — which errs towards in flight, and keeps a row. Closing either
+ from this side would mean deciding on the row's stamp again, written by a clock
+ this command cannot check and no evidence about whether a run is live, or never
+ pruning a row without a claim, which is every row any release has written.
+
+ Giving a row back at the end of a failed `up` is still worth doing — it frees
+ the port now instead of at the next `reconcile --yes` — and both of its
+ conditions are read at that moment rather than remembered from an earlier one.
+ The daemon must report no project for the slug, since a project it holds may
+ bind that port. The row must also still be the one that run wrote, which is
+ what the opaque claim in it is for: `up` merges over whatever row it finds, so
+ a later run can take the row over, and the first one failing afterwards must
+ not free a port the second is building on. `reserved_at` and `updated_at` are
+ provenance for whoever reads the file, and nothing decides on them: a stamp
+ written by another machine's clock, or by this one before it was corrected, is
+ no evidence about whether an `up` is running right now. For the same reason a
+ reservation records no branch or commit until it completes — the run that built
+ the environment is the one that can say what it built — so a slug reserved
+ again reports the branch it is still running, not the one being installed over
+ it.
+- `worktrees.json` is reached only through an accessor bound to the daemon it
+ describes. The file reserves host ports on this machine and records what this
+ machine's daemon holds, so every read of it and every write to it is a claim
+ about exactly one authority, and a `--remote` command has no name for it: it
+ neither reads nor writes a byte. `reconcile --remote` reports the remote
+ inventory and says once that runner metadata is not shown; `delete --remote`
+ removes the remote environment and says it kept the local row; `up --remote`
+ requires `--host-port`, because allocating from this machine's reservations is
+ no evidence about which of another daemon's ports are free. The `delete`
+ commands `reconcile --remote` prints carry `--remote`, or they would name the
+ same slug on the wrong daemon. The lock over that file belongs to the same
+ accessor, for the same reason: a `--remote` command holds nothing of this
+ file's inside its listings, so it does not keep local runs out of the file
+ while it waits on another daemon.
+- An empty `--remote` names this machine's daemon, normalized once where the
+ flag is defined rather than at each reader. An unexpanded
+ `--remote "$INCUS_REMOTE"` would otherwise be two authorities at once: the
+ environment created here, while the accessor bound to some other daemon and
+ recorded nothing about it — leaving the host port allocated with no row naming
+ it.
+
Useful flags:
- `--host-port <port>`: set the host-side Web UI proxy port.
diff --git a/scripts/incus_regression.py b/scripts/incus_regression.py
index 359272631..f77b5882c 100644
--- a/scripts/incus_regression.py
+++ b/scripts/incus_regression.py
@@ -26,7 +26,7 @@ from contextlib import contextmanager
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
-from typing import Container, Iterator, Sequence
+from typing import Callable, Container, Iterable, Iterator, Sequence
try:
import fcntl
@@ -119,8 +119,8 @@ class Runner:
kwargs["input"] = input_text
return subprocess.run(list(command), **kwargs)
- def names(self, command: Sequence[str], *, what: str) -> list[str]:
- """Return the names the daemon enumerated, or raise if it could not answer.
+ def records(self, command: Sequence[str], *, what: str) -> list[dict]:
+ """Return the objects the daemon enumerated, or raise if it could not answer.
Existence must come from a listing the daemon actually completed, never
from a lookup's exit status: `incus` exits non-zero both when an object
@@ -128,6 +128,14 @@ class Runner:
is stalled. Collapsing the second into the first turns "cannot tell"
into "not there", and callers then set out to create what already
exists.
+
+ A zero exit is not on its own an answer either. An entry this runner
+ cannot read -- a client and daemon disagreeing about the listing schema,
+ say -- used to be filtered out, which turns a listing nobody could parse
+ into an inventory that looks complete and happens to be empty. That reads
+ as a confirmed absence, and `reconcile --yes` acts on it by releasing
+ host ports that are still in use. Every entry is therefore either
+ understood or fatal.
"""
if self.dry_run:
return []
@@ -140,7 +148,17 @@ class Runner:
raise RegressionError(f"Could not parse the {what} listing returned by Incus: {exc}") from exc
if not isinstance(payload, list):
raise RegressionError(f"Unexpected {what} listing returned by Incus: {type(payload).__name__}")
- return [item["name"] for item in payload if isinstance(item, dict) and isinstance(item.get("name"), str)]
+ for item in payload:
+ if not isinstance(item, dict) or not isinstance(item.get("name"), str):
+ raise RegressionError(
+ f"Unreadable entry in the {what} listing returned by Incus: {item!r}\n"
+ "Every caller identifies an object by name, so an entry without one cannot be reasoned about."
+ )
+ return payload
+
+ def names(self, command: Sequence[str], *, what: str) -> list[str]:
+ """The names from `records`, for callers that only ask whether something exists."""
+ return [item["name"] for item in self.records(command, what=what)]
def incus(*args: str, project: str | None = None) -> list[str]:
@@ -151,6 +169,35 @@ def incus(*args: str, project: str | None = None) -> list[str]:
return command
+def normalized_remote(value: str) -> str | None:
+ """One spelling of "the local daemon" past argv.
+
+ `remote_ref` has always read an empty name as this machine's daemon, and the
+ metadata accessor reads `--remote` itself, so an unexpanded
+ `--remote "$INCUS_REMOTE"` was two authorities at once: the environment was
+ created locally while the accessor bound to some other daemon and recorded
+ nothing, leaving the host port allocated with no row naming it. Either reader
+ could be written to agree with the other, which is why agreement is not the
+ fix -- normalizing at the parser leaves one value to read, for every reader
+ that exists now and every one added later.
+
+ That one value has to be a name and not an arbitrary string, because two of
+ those readers spell it into places that only hold one: `remote_ref` joins it
+ to an object with `:`, and `target_lock_path` makes it part of a filename. A
+ separator in it would name a different daemon than the one written, or put a
+ lock outside the directory that holds them, so it is refused here -- the one
+ point both readers are downstream of.
+ """
+ name = value.strip()
+ if not name:
+ return None
+ if name in {".", ".."} or any(char in name for char in "/\\:"):
+ raise argparse.ArgumentTypeError(
+ f"invalid Incus remote name {value!r}: a remote is one name, without '/', '\\' or ':'"
+ )
+ return name
+
+
def remote_ref(remote: str | None, name: str = "") -> str:
if not remote:
return name
@@ -251,37 +298,167 @@ def runtime_root(repo_root: Path) -> Path:
return git_common_root(repo_root) / ".runtime" / "incus-regression"
+def target_lock_path(repo_root: Path, remote: str | None, project: str) -> Path:
+ """Where the lock for one environment lives, on this machine.
+
+ An environment is identified by the daemon that holds it and the project on
+ it, never by the project alone -- the same rule `worktrees.json` follows,
+ because project names are per-daemon and every remote has the same ones. The
+ lock file is local wherever the environment is, so a `--remote` run that keyed
+ on the project would take the lock of the local environment with that name and
+ be read as one, which is what `remote_ref` exists to stop everywhere else.
+ Local runs keep exactly the path they have always had: `remote_ref` renders no
+ authority as no prefix, so this is byte-identical to every released version,
+ and their lock is the same file as ours -- the reason a lock can answer for
+ them at all.
+ """
+ return runtime_root(repo_root) / "locks" / f"{remote_ref(remote, project)}.lock"
+
+
@contextmanager
-def target_update_lock(repo_root: Path, target: RegressionTarget, *, dry_run: bool):
+def target_update_lock(repo_root: Path, remote: str | None, project: str, *, dry_run: bool, blocking: bool = True):
+ """Serialize runs against one environment, and say so to `reconcile`.
+
+ Keyed on the daemon and the project name rather than on a resolved target,
+ because that is the whole key: a caller can name the lock before it has asked
+ the mapping for a port, which is what lets the port be allocated inside the
+ lock that protects it.
+
+ Which commands have to hold it is a property of the environment rather than
+ of any one of them, so it is written here instead of at each call site. Every
+ command that changes what a slug names -- its Incus objects, its row, or both
+ -- holds it: `up` from before it reserves until after it stamps the row,
+ `delete` across removing the objects and forgetting the row. `reconcile` is
+ the one command that drops rows without holding it, and deliberately: it
+ exists to observe whoever else holds it, so taking it would answer its own
+ question. Nothing else belongs to the class. `down`, `status`, `logs` and
+ `shell` cannot break what the lock protects -- that a row reserves a host
+ port exactly while its environment exists or is being built -- because none
+ of them creates, destroys or forgets either half; a `down` that interrupts a
+ build makes that `up` fail, and its reservation gives the row back.
+
+ `blocking=False` is for a caller whose answer to "somebody else holds this"
+ is to stop rather than to wait. The acquire is then both the proof that
+ nobody holds it and the protection, which is the only order with no window
+ between the two -- the same reason `target_run_in_flight` trusts a lock it
+ took itself and nothing else. Waiting would also be a new reading of a held
+ lock: every other reader treats one as a live run whose slug it must leave
+ alone, and behind an `up` that is stuck it would never return.
+ """
if dry_run or fcntl is None:
yield
return
- lock_dir = runtime_root(repo_root) / "locks"
- lock_dir.mkdir(parents=True, exist_ok=True)
- lock_path = lock_dir / f"{target.project}.lock"
+ lock_path = target_lock_path(repo_root, remote, project)
+ lock_path.parent.mkdir(parents=True, exist_ok=True)
with lock_path.open("w", encoding="utf-8") as fh:
print(f"Acquiring regression update lock: {lock_path}")
- fcntl.flock(fh.fileno(), fcntl.LOCK_EX)
+ if blocking:
+ fcntl.flock(fh.fileno(), fcntl.LOCK_EX)
+ else:
+ try:
+ fcntl.flock(fh.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
+ except BlockingIOError:
+ # Only contention is turned into this message. Any other way the
+ # lock can fail is re-raised as itself, because a wrong
+ # explanation of a real fault costs more than no explanation.
+ raise RegressionError(
+ f"Another run holds the regression update lock for {remote_ref(remote, project)}: {lock_path}\n"
+ "It is building or removing that environment right now. Wait for it to finish, or stop it, then retry."
+ ) from None
try:
yield
finally:
fcntl.flock(fh.fileno(), fcntl.LOCK_UN)
+def target_run_in_flight(repo_root: Path, remote: str | None, project: str) -> bool:
+ """Whether some live process is changing `project` on `remote` right now.
+
+ Changing, not building: a `delete` holds the same lock while it removes the
+ environment and its row, and a row kept for the moment that takes is a row
+ its holder is about to drop itself. Either way the answer is the same one,
+ which is why the question is about the lock and not about what its holder
+ intends.
+
+ Asked of the kernel rather than of `worktrees.json`, because no field a run
+ writes can answer it. A record lies in both directions: a run that dies
+ without unwinding leaves its own behind, and a run from a checkout that
+ predates the field writes nothing recognisable at all. The lock above cannot
+ do either. The kernel drops it when the holder exits however it exits, so it
+ cannot outlive its run, and every version of this runner that has ever built
+ a worktree environment takes it, at a path derived from the shared git common
+ root -- so this answers for an `up` started from another worktree, an older
+ checkout, or an installed release exactly as well as for one of ours. Those
+ older runs take the lock a moment after writing their row rather than before
+ it, so what is exposed there is that instant, not the build; reading the row
+ instead would mean trusting a stamp from another clock, which says nothing
+ about whether a run is live. Nor do they carry which daemon they are updating:
+ they key the lock on the project alone, so a released `up --remote` takes the
+ local environment's lock. That is the one direction still left, and it errs
+ towards in flight, which keeps a row rather than dropping a live one.
+
+ Not-yet-known answers in flight, as every unanswered question in `reconcile`
+ does: a platform without `flock`, a lock file this user cannot open. Only a
+ lock this call took itself proves nobody holds it.
+ """
+ if fcntl is None:
+ return True
+ lock_path = target_lock_path(repo_root, remote, project)
+ try:
+ # Read-only, and no `mkdir`: a probe must not create the artifact whose
+ # absence is the answer. `flock` is owned by the open file description,
+ # so this conflicts with a lock held by this same process too -- the
+ # conservative side, and the only side it could safely land on.
+ fd = os.open(lock_path, os.O_RDONLY)
+ except FileNotFoundError:
+ return False
+ except OSError:
+ return True
+ try:
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
+ except OSError:
+ return True
+ finally:
+ # Closing the descriptor drops whatever this probe just took, so the
+ # answer costs nothing beyond the moment it was read.
+ os.close(fd)
+ return False
+
+
+_held_mapping_locks: set[Path] = set()
+
+
@contextmanager
def worktree_mapping_lock(repo_root: Path, *, dry_run: bool):
+ """Serialize every read-modify-write of `worktrees.json`, and nest safely.
+
+ Re-entrant on purpose, because the mapping's writers now take this lock
+ themselves rather than trusting a caller to have taken it: `up` holds it
+ across resolving a target and reserving its slug, `reconcile` holds it across
+ a listing and the decision that listing feeds, and both end in a write that
+ acquires it again. `flock` is owned by an open file description, not by a
+ process, so a second `open` plus `flock` here would block forever on a lock
+ this very process holds -- a deadlock rather than a wait. Remembering what is
+ already held makes the inner acquisition a no-op and keeps the outer span
+ exactly as wide as it was.
+ """
if dry_run or fcntl is None:
yield
return
lock_dir = runtime_root(repo_root) / "locks"
lock_dir.mkdir(parents=True, exist_ok=True)
- lock_path = lock_dir / "worktrees.lock"
+ lock_path = (lock_dir / "worktrees.lock").resolve()
+ if lock_path in _held_mapping_locks:
+ yield
+ return
with lock_path.open("w", encoding="utf-8") as fh:
print(f"Acquiring regression worktree mapping lock: {lock_path}")
fcntl.flock(fh.fileno(), fcntl.LOCK_EX)
+ _held_mapping_locks.add(lock_path)
try:
yield
finally:
+ _held_mapping_locks.discard(lock_path)
fcntl.flock(fh.fileno(), fcntl.LOCK_UN)
@@ -408,7 +585,8 @@ def mapping_path(repo_root: Path) -> Path:
return runtime_root(repo_root) / "worktrees.json"
-def load_worktree_mapping(repo_root: Path) -> dict:
+def _load_worktree_mapping(repo_root: Path) -> dict:
+ """Read the mapping file. Private: reach it through `WorktreeMetadata`."""
path = mapping_path(repo_root)
if not path.is_file():
return {"schema_version": 1, "worktrees": {}}
@@ -423,27 +601,285 @@ def load_worktree_mapping(repo_root: Path) -> dict:
return payload
-def save_worktree_mapping(repo_root: Path, payload: dict) -> None:
+def _write_worktree_mapping(repo_root: Path, payload: dict) -> None:
+ """Write the mapping file. Private: reach it through `WorktreeMetadata`."""
path = mapping_path(repo_root)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
-def allocated_worktree_ports(repo_root: Path) -> set[int]:
- payload = load_worktree_mapping(repo_root)
- ports: set[int] = set()
- for item in (payload.get("worktrees") or {}).values():
+@dataclass(frozen=True)
+class WorktreeMetadata:
+ """`worktrees.json`, bound to the Incus daemon it is evidence about.
+
+ The file reserves host ports on this machine and records what this machine's
+ daemon holds, so every read of it and every write to it is a claim about
+ exactly one authority. Binding that authority to the accessor is what makes
+ the claim true by construction: a caller holding one of these cannot name
+ another daemon's metadata, so it cannot read or write it.
+
+ A predicate each command was expected to consult came first, and being a
+ question is what made it forgettable. `delete --remote` and
+ `reconcile --remote` asked it; `up --remote` did not, and so a remote
+ environment reserved a host port on this machine, overwrote whatever live
+ local row shared its slug, and -- because the other two commands had learned
+ to keep the file -- left that reservation behind for good. The reads never
+ asked at all: a remote `up` took its port from a local row, and a remote
+ `reconcile` printed local provenance beside remote environments and called
+ local-only rows environments the remote had lost.
+ """
+
+ repo_root: Path
+ remote: str | None = None
+
+ @property
+ def owned(self) -> bool:
+ """Whether the daemon in question is the one this file describes."""
+ return self.remote is None
+
+ @contextmanager
+ def locked(self, *, dry_run: bool):
+ """Hold the mapping lock across a decision that reads and then writes.
+
+ Taken here rather than by each command, because a lock on this file is a
+ claim about one authority too, and the commands had learned that about
+ the rows without learning it about the lock. `reconcile --remote` held it
+ across two listings of another daemon, where this accessor exposes no
+ rows and writes none: a slow or unreachable remote blocked every local
+ `up` from reserving a port for as long as the listing took, protecting
+ nothing, since nothing of this file's was in the span.
+ """
+ if not self.owned:
+ yield
+ return
+ with worktree_mapping_lock(self.repo_root, dry_run=dry_run):
+ yield
+
+ def rows(self) -> dict:
+ """The recorded rows, or none at all when another daemon is the subject."""
+ if not self.owned:
+ return {}
+ return _load_worktree_mapping(self.repo_root).get("worktrees") or {}
+
+ def mutate(self, mutate: Callable[[dict], None]) -> None:
+ """The only writer of `worktrees.json`: lock, load, apply, save.
+
+ Owning the sequence here is what makes "the mapping is only ever
+ modified under the mapping lock" true by construction instead of true
+ whenever every caller remembers. One caller did not: `up` stamps
+ completion after the command has already released the lock, so that
+ load-modify-save could interleave with reconcile's, and whichever saved
+ last erased the other -- restoring a row that was just pruned, or
+ dropping the stamp that proves a reservation finished and leaving the
+ slug pending forever.
+
+ `mutate` receives the `worktrees` mapping itself, loaded inside the
+ lock, so it cannot act on a copy read before the lock was held.
+ """
+ if not self.owned:
+ return
+ with self.locked(dry_run=False):
+ payload = _load_worktree_mapping(self.repo_root)
+ mutate(payload.setdefault("worktrees", {}))
+ _write_worktree_mapping(self.repo_root, payload)
+
+ def allocated_ports(self) -> set[int]:
+ return {
+ item["host_port"]
+ for item in self.rows().values()
+ if isinstance(item, dict) and isinstance(item.get("host_port"), int)
+ }
+
+ def port_for(self, slug: str) -> int | None:
+ item = self.rows().get(slug)
if isinstance(item, dict) and isinstance(item.get("host_port"), int):
- ports.add(item["host_port"])
- return ports
+ return item["host_port"]
+ return None
+ def reserve(self, target: RegressionTarget, *, dry_run: bool = False) -> WorktreeReservation:
+ """Record the slug and its port before the environment is built.
+
+ The row carries an opaque claim minted here and the reservation handed
+ back carries the same value, so ending the reservation later can compare
+ instead of remember. It has to: `reserve` merges over whatever row it
+ finds, which is exactly how a second `up` on this slug takes a row this
+ run wrote, and the claim is what makes that takeover observable
+ afterwards. `up` now reserves under the slug's update lock, so a takeover
+ while the first run is still building takes a platform without `flock`;
+ the claim is what keeps the property from depending on that.
+
+ A claim is minted only when this run actually wrote a row, which is the
+ one condition the reservation then needs: no claim covers a dry run, a
+ target that owns no row, and a remote accessor that writes nothing --
+ each of which used to be re-derived at every end of the reservation.
+
+ The row binds the slug to a port and a pair of object names; it says
+ nothing about what is built there, because this run has not built it yet,
+ and nothing about whether the run is still alive, because no field can
+ (`target_run_in_flight` is where that is asked). `complete` owns the
+ branch and the commit for the first reason: the merge means anything
+ written here lands beside the previous run's fields, and a reservation
+ that wrote its own branch produced a row reporting the new branch for an
+ environment still built from the old one's commit.
+ """
+ reservation = WorktreeReservation(metadata=self, target=target, dry_run=dry_run)
+ if dry_run or not self.owned or target.target != WORKTREE_TARGET:
+ return reservation
+ reservation.claim = os.urandom(8).hex()
+ row = {
+ "path": str(self.repo_root),
+ "project": target.project,
+ "instance": target.instance,
+ "host_port": target.host_port,
+ "reserved_at": datetime.now(timezone.utc).isoformat(),
+ "claim": reservation.claim,
+ }
+ self.mutate(lambda worktrees: worktrees.setdefault(target.slug, {}).update(row))
+ return reservation
+
+ def apply_claimed(self, target: RegressionTarget, claim: str, row: dict | None) -> None:
+ """Replace or drop a slug's row while it is still the one `claim` wrote.
+
+ Both ends of a reservation write through here, because "this row is still
+ mine" is one property, and a second implementation of it is how the first
+ one gets forgotten. It was: the comparison was added to the release while
+ completion kept writing unconditionally, so an `up` that finished first
+ replaced a newer run's row -- and with it that run's port and its claim,
+ leaving the port allocated to a slug whose row no longer records it while
+ the newer `up` was still building against it.
+
+ The comparison happens inside the write's own load-modify-save, under the
+ lock, because it is a claim about the row as it is now: between reserving
+ and writing, another `up` on this slug may have merged its own row over
+ this one. Read the row first and this becomes the accident it exists to
+ prevent.
+ """
+
+ def guarded(worktrees: dict) -> None:
+ current = worktrees.get(target.slug)
+ if not isinstance(current, dict) or current.get("claim") != claim:
+ return
+ if row is None:
+ del worktrees[target.slug]
+ else:
+ worktrees[target.slug] = row
+
+ self.mutate(guarded)
+
+ def complete(self, target: RegressionTarget, claim: str) -> None:
+ """Stamp the environment as built, replacing the row, its claim and its `reserved_at`."""
+ self.apply_claimed(
+ target,
+ claim,
+ {
+ "path": str(self.repo_root),
+ "project": target.project,
+ "instance": target.instance,
+ "host_port": target.host_port,
+ "updated_at": datetime.now(timezone.utc).isoformat(),
+ "branch": branch_name(self.repo_root),
+ "commit": commit_sha(self.repo_root),
+ },
+ )
+
+ def release(self, target: RegressionTarget, claim: str) -> None:
+ """Drop a reservation row while it is still the one that claim wrote."""
+ self.apply_claimed(target, claim, None)
+
+ def forget(self, slugs: Iterable[str]) -> None:
+ """Drop rows for environments the owning daemon no longer has."""
+ wanted = list(slugs)
+
+ def prune(worktrees: dict) -> None:
+ for slug in wanted:
+ worktrees.pop(slug, None)
+
+ self.mutate(prune)
+
+
+@dataclass
+class WorktreeReservation:
+ """A claim on a slug and its host port, scoped to the run that made it.
+
+ `reserve` and `complete` are the two ends of an `up` that worked. This is the
+ third end: the row a failed run leaves is not wrong, only unwanted, and
+ giving it back here is what frees the host port now rather than at whatever
+ later `reconcile --yes` somebody happens to run. It is no longer the only way
+ back -- a reservation is kept alive by the update lock its run holds, and the
+ kernel drops that lock however the run ends, so an abandoned row is prunable
+ by construction -- but a port reclaimed only by a command nobody ran is a
+ port still allocated, and the next `up` on a fresh slug is what pays for it.
+
+ Giving it back is only ever right while two things are true, and neither can
+ be carried here from an earlier moment -- which is the whole of what an
+ earlier draft of this class got wrong. It remembered "the row did not exist
+ when I looked", and a concurrent `up` on the same slug could take the row
+ over before the failure that consumed it. It also remembered "I am about to
+ create something", set before `ensure_project_and_instance` runs its own
+ listing, so a listing that never answered kept a row for an environment
+ nothing had begun. A remembered fact standing in for an observation is the
+ same defect twice, and every read inserted between the two moments reopens
+ it. So both are read at the moment of deciding, and both live here rather
+ than in `up`, for the reason round 3 named: a question every caller has to
+ remember to ask is how a defect gets in.
+
+ - The row must still be the one this reservation wrote, compared under the
+ mapping lock in the same write that changes it. This is a condition on
+ every end of the reservation, not just this one, so both go through the
+ one writer that enforces it.
+ - The daemon must say the project is absent. Present means something may
+ already bind this port, and a listing that cannot answer is a "cannot
+ tell" resolved the way this runner resolves every other one: keep the row.
+
+ Holding a claim is itself the answer to "is there a row of mine here at all":
+ a dry run, a target that owns no row, and a remote accessor all reserve
+ without one, so neither end has to re-derive that from the run's arguments.
+ """
-def allocate_worktree_port(repo_root: Path, ui_host: str, start: int, end: int, *, dry_run: bool, preflight: bool) -> int:
- used = allocated_worktree_ports(repo_root)
+ metadata: WorktreeMetadata
+ target: RegressionTarget
+ dry_run: bool = False
+ claim: str | None = None
+
+ def complete(self) -> None:
+ """Stamp the environment as built, ending the reservation."""
+ if self.claim is None:
+ return
+ self.metadata.complete(self.target, self.claim)
+
+ def release(self, runner: Runner) -> None:
+ """Give the row back if nothing came of it and nobody else has taken it."""
+ if self.claim is None:
+ return
+ try:
+ stranded = project_exists(runner, self.metadata.remote, self.target.project)
+ except BaseException:
+ # Asked while an `up` is already failing, so a daemon that cannot
+ # answer -- or a second Ctrl-C landing here -- is an ordinary way to
+ # get no answer rather than a new fault. Keeping the row is the
+ # conservative half of "cannot tell", and swallowing this is what
+ # lets the failure that started the unwind be the one that surfaces.
+ return
+ if not stranded:
+ self.metadata.release(self.target, self.claim)
+
+
+def allocate_worktree_port(
+ metadata: WorktreeMetadata, ui_host: str, start: int, end: int, *, dry_run: bool
+) -> int:
+ """Pick a free host port for an environment on the daemon `metadata` describes.
+
+ The candidate is checked against this host because it is this host that will
+ bind it. There used to be an opt-out for the remote case, where the port
+ belongs to another machine and a local check is meaningless -- but allocating
+ from local reservations was equally meaningless there, and that is now
+ refused outright, so only the owning daemon ever reaches this.
+ """
+ used = metadata.allocated_ports()
for port in range(start, end + 1):
if port in used:
continue
- if not dry_run and preflight:
+ if not dry_run:
try:
ensure_host_port_available(ui_host, port)
except RegressionError:
@@ -452,11 +888,252 @@ def allocate_worktree_port(repo_root: Path, ui_host: str, start: int, end: int,
raise RegressionError(f"No available worktree regression port in range {start}-{end}.")
-def mapped_worktree_port(repo_root: Path, slug: str) -> int | None:
- item = (load_worktree_mapping(repo_root).get("worktrees") or {}).get(slug)
- if isinstance(item, dict) and isinstance(item.get("host_port"), int):
- return item["host_port"]
- return None
+@dataclass(frozen=True)
+class ObservedInstance:
+ """One instance Incus reported, named by the project that actually holds it.
+
+ Incus scopes instance names per project, so a name is not an identity on its
+ own; only the pair is. Carrying the project alongside the state is what lets
+ a caller say which instance it means, rather than which name it saw.
+ """
+
+ project: str
+ state: str
+
+
+@dataclass(frozen=True)
+class WorktreeEnvironment:
+ """One worktree regression environment, as Incus has it and as metadata describes it.
+
+ `project` and `instance` are always the names the naming convention derives
+ from the slug, because those are the objects `delete --slug` acts on. What
+ Incus was observed to hold is kept separately, so a partial or misplaced
+ footprint can be reported as what it is rather than averaged into a single
+ "present" flag.
+
+ That observation is a set, not one slot. The same instance name can exist in
+ several projects at once -- exactly what happens when an earlier run left one
+ behind and a later one recreated it under the convention project -- and a
+ single slot silently keeps whichever the listing mentioned last. Losing the
+ other one is not a cosmetic omission: if the survivor is the convention-project
+ instance, `reconcile` reports a footprint it can delete and prints no warning
+ about the one it cannot reach.
+
+ `in_flight` is a field and not a property, because `entry` cannot derive it.
+ Whether a run still holds this slug is a fact about processes, so the caller
+ observes it through `target_run_in_flight` and passes it in; see that function
+ for why no recorded field is allowed to stand in for it.
+ """
+
+ slug: str
+ project: str
+ instance: str
+ has_project: bool
+ instances: tuple[ObservedInstance, ...]
+ entry: dict | None
+ in_flight: bool
+
+ @property
+ def exists(self) -> bool:
+ """Whether Incus still holds any part of this environment.
+
+ Either half is enough. A project whose instance is gone still owns the
+ slug and still has to be reclaimed, and an instance whose project was
+ never recorded still holds a host port.
+ """
+ return self.has_project or bool(self.instances)
+
+ @property
+ def reachable_by_slug(self) -> bool:
+ """Whether `delete --slug` can name this environment at all.
+
+ A slug here is whatever remained after stripping a known prefix off a
+ name the daemon reported, so it is bounded by what Incus accepts, not by
+ what the runner would mint. `delete --slug` validates its argument, so a
+ suffix it rejects -- two characters, over forty, an underscore -- has no
+ runner command at all. This is exactly the environment the report exists
+ for: the runner did not create it, so nothing constrained its name.
+ """
+ return bool(SLUG_RE.match(self.slug))
+
+ @property
+ def deletable_instances(self) -> tuple[ObservedInstance, ...]:
+ """The observed instances `delete --slug` would actually reach."""
+ if not self.reachable_by_slug:
+ return ()
+ return tuple(item for item in self.instances if item.project == self.project)
+
+ @property
+ def stranded_instances(self) -> tuple[ObservedInstance, ...]:
+ """The observed instances `delete --slug` would not reach.
+
+ Either the instance lives outside the project the slug names, or the slug
+ is not one the runner can name -- in which case the command reaches
+ nothing and every observed instance is stranded. The two properties stay
+ complementary by construction, so an instance cannot fall out of both.
+ """
+ if not self.reachable_by_slug:
+ return self.instances
+ return tuple(item for item in self.instances if item.project != self.project)
+
+ @property
+ def deletable_by_slug(self) -> bool:
+ """Whether `delete --slug` reaches any part of this environment."""
+ return self.reachable_by_slug and (self.has_project or bool(self.deletable_instances))
+
+ @property
+ def footprint(self) -> str:
+ """What Incus was observed to hold, every part of it named.
+
+ Reported rather than summarised: `Unknown` used to stand for an instance
+ nobody had looked for, which reads as a daemon that would not answer. Each
+ observed instance appears, and one outside the slug's project says where it
+ is, because that is the part `delete --slug` will not reach.
+ """
+ if not self.instances:
+ observed = ["no instance"]
+ else:
+ observed = [
+ item.state if item.project == self.project else f"{item.state} in {item.project}"
+ for item in self.instances
+ ]
+ return ", ".join(["project" if self.has_project else "no project", *observed])
+
+
+def worktree_instances(runner: Runner, *, remote: str | None) -> dict[str, tuple[ObservedInstance, ...]]:
+ """Group every worktree instance Incus reports by name, keeping each one's project.
+
+ The project is part of the observation, not decoration. An instance living
+ in a project other than the one its name implies is not reachable by
+ `delete --slug`, and reporting it as if it were promises a removal that
+ would silently leave it running.
+
+ A name maps to a tuple because Incus scopes names per project, so one name can
+ legitimately be several instances. Keying a single record by name kept the last
+ one the listing happened to mention and dropped the rest, which is how a
+ stranded instance disappeared from a report that also claimed to have
+ enumerated it.
+ """
+ command = incus("list", *optional_remote_ref(remote), "--all-projects", "--format", "json")
+ instances: dict[str, list[ObservedInstance]] = {}
+ for item in runner.records(command, what="Incus instances"):
+ name = item["name"]
+ if name.startswith(WORKTREE_INSTANCE_PREFIX):
+ instances.setdefault(name, []).append(
+ ObservedInstance(
+ project=str(item.get("project") or "default"),
+ state=str(item.get("status") or "Unknown"),
+ )
+ )
+ return {name: tuple(observed) for name, observed in instances.items()}
+
+
+def worktree_environments(runner: Runner, metadata: WorktreeMetadata) -> list[WorktreeEnvironment]:
+ """Every worktree regression environment, enumerated from Incus and annotated by metadata.
+
+ Incus is the authority on what exists; `worktrees.json` only describes what
+ the runner happened to record. Walking the metadata instead cannot see an
+ environment created outside the runner, so a running instance stays
+ invisible to every command that works from the mapping.
+
+ Both halves of the footprint are enumerated separately. An environment whose
+ project was deleted while its instance survived is neither fully present nor
+ absent, and reading one half as the whole answer reports the other half as
+ something it never observed.
+
+ The daemon is taken from `metadata` rather than passed alongside it, so the
+ inventory and the rows annotating it cannot come from two different
+ authorities. When they did, a remote environment was annotated with the
+ local row that happened to share its slug, and local-only rows were listed
+ as environments the remote had lost.
+
+ Each environment carries the names the daemon reported rather than minting
+ them again from the slug. The slug is that name with a known prefix removed,
+ so re-deriving it can only reproduce what was already observed -- except that
+ minting validates, and a name Incus accepts is not necessarily a name the
+ runner would choose. `project_name_for` therefore raised on a discovered
+ two-character or over-long suffix, and `reconcile` reported nothing at all
+ for the one kind of environment it exists to find. A name that was observed
+ is evidence; deriving it a second time only adds a way to disagree with it.
+ """
+ remote = metadata.remote
+ entries = metadata.rows()
+ projects = {
+ name[len(WORKTREE_PROJECT_PREFIX):]: name
+ for name in runner.names(
+ incus("project", "list", *optional_remote_ref(remote), "--format", "json"),
+ what="Incus projects",
+ )
+ if name.startswith(WORKTREE_PROJECT_PREFIX)
+ }
+ instances = worktree_instances(runner, remote=remote)
+ instance_names = {name[len(WORKTREE_INSTANCE_PREFIX):]: name for name in instances}
+ slugs = set(entries) | set(projects) | set(instance_names)
+ environments = []
+ for slug in sorted(slugs):
+ entry = entries.get(slug)
+ entry = entry if isinstance(entry, dict) else None
+ instance = instance_names.get(slug, f"{WORKTREE_INSTANCE_PREFIX}{slug}")
+ project = projects.get(slug, f"{WORKTREE_PROJECT_PREFIX}{slug}")
+ environments.append(
+ WorktreeEnvironment(
+ slug=slug,
+ project=project,
+ instance=instance,
+ has_project=slug in projects,
+ instances=instances.get(instance, ()),
+ entry=entry,
+ # Asked of this accessor's own daemon, so the lock read is about
+ # the environment being listed and not about one that merely
+ # shares its project name -- the rule the rows follow too.
+ # Locks live on this machine, so they are evidence about runs
+ # started on it: a remote daemon's environment may be built from
+ # a machine this one cannot see, and it has no local row to act
+ # on, so no answer is claimed for it at all.
+ in_flight=metadata.owned
+ and target_run_in_flight(metadata.repo_root, metadata.remote, project),
+ )
+ )
+ return environments
+
+
+def describe_worktree_entry(entry: dict | None) -> str:
+ if entry is None:
+ return "no runner metadata"
+ parts = []
+ if isinstance(entry.get("host_port"), int):
+ parts.append(f"port {entry['host_port']}")
+ branch = str(entry.get("branch") or "").strip()
+ commit = str(entry.get("commit") or "").strip()
+ if branch:
+ parts.append(f"branch {branch}")
+ elif commit:
+ parts.append(f"detached at {commit[:12]}")
+ else:
+ parts.append("no branch or commit recorded")
+ path = str(entry.get("path") or "").strip()
+ if path:
+ # Provenance only. This is the checkout the runner was invoked from, not
+ # the environment's identity: several environments created from one
+ # checkout all record the same path, so its presence on disk says
+ # nothing about whether any of them is still wanted.
+ parts.append(f"created from {path}")
+ return ", ".join(parts)
+
+
+def target_slug(args: argparse.Namespace, repo_root: Path) -> str:
+ """The slug this invocation names, without consulting the mapping.
+
+ Split out because a caller may need the environment's identity before it is
+ allowed to read ports -- `up` names its update lock from this and allocates
+ inside it. Identity is derivable from the arguments alone, so nothing here
+ touches `worktrees.json`.
+ """
+ if args.target not in TARGETS:
+ raise RegressionError(f"target must be one of: {', '.join(sorted(TARGETS))}")
+ if args.target == MASTER_TARGET:
+ return "master"
+ return worktree_slug(repo_root, args.slug)
def resolve_target(
@@ -464,27 +1141,39 @@ def resolve_target(
repo_root: Path,
*,
dry_run: bool,
- preflight_ports: bool = True,
allocate_port: bool = True,
+ slug: str | None = None,
) -> RegressionTarget:
- if args.target not in TARGETS:
- raise RegressionError(f"target must be one of: {', '.join(sorted(TARGETS))}")
+ # An identity already observed is passed in rather than observed again: a
+ # slug derived from the checkout's branch is a question that can be answered
+ # twice differently, and `up` has to lock the same environment it builds.
+ slug = slug or target_slug(args, repo_root)
ui_host = args.ui_host or host_bind_env()
ui_port = args.ui_port
if args.target == MASTER_TARGET:
- slug = "master"
host_port = args.host_port or env_int("REGRESSION_PORT") or DEFAULT_MASTER_HOST_PORT
else:
- slug = worktree_slug(repo_root, args.slug)
- host_port = args.host_port or mapped_worktree_port(repo_root, slug)
+ metadata = WorktreeMetadata(repo_root, args.remote)
+ host_port = args.host_port or metadata.port_for(slug)
if host_port is None and allocate_port:
+ if not metadata.owned:
+ # The port is a "cannot tell", so it is asked for rather than
+ # guessed. Allocation reads this machine's reservations, which
+ # say nothing about which of another daemon's ports are free,
+ # and no one has asked that daemon. Answering anyway is how a
+ # remote environment came to be handed a live local
+ # environment's port.
+ raise RegressionError(
+ f"--host-port is required for a worktree environment on remote {args.remote}.\n"
+ "Worktree ports are allocated from this machine's metadata, which is no evidence "
+ "about another daemon's ports."
+ )
host_port = allocate_worktree_port(
- repo_root,
+ metadata,
ui_host,
args.worktree_port_start,
args.worktree_port_end,
dry_run=dry_run,
- preflight=preflight_ports,
)
if host_port is None:
host_port = 0
@@ -635,7 +1324,20 @@ def yaml_block(value: str, indent: int = 6) -> str:
return "\n".join(prefix + line if line else prefix for line in value.splitlines())
+def ui_device_endpoints(target: RegressionTarget) -> dict[str, str]:
+ """The `listen`/`connect` pair the `ui` proxy device must forward.
+
+ One owner for these strings, so the create, update, and compare paths cannot
+ drift into disagreeing about what "already correct" means.
+ """
+ return {
+ "listen": tcp_endpoint(target.ui_host, target.host_port),
+ "connect": f"tcp:127.0.0.1:{target.ui_port}",
+ }
+
+
def proxy_device_args(target: RegressionTarget, *, remote: str | None = None) -> list[str]:
+ endpoints = ui_device_endpoints(target)
return [
"config",
"device",
@@ -643,15 +1345,98 @@ def proxy_device_args(target: RegressionTarget, *, remote: str | None = None) ->
remote_ref(remote, target.instance),
"ui",
"proxy",
- f"listen={tcp_endpoint(target.ui_host, target.host_port)}",
- f"connect=tcp:127.0.0.1:{target.ui_port}",
+ f"listen={endpoints['listen']}",
+ f"connect={endpoints['connect']}",
]
+def ui_device_present(runner: Runner, target: RegressionTarget, *, remote: str | None) -> bool:
+ """Whether the instance has a `ui` device, from a listing the daemon completed.
+
+ `config device get` cannot answer this: it exits non-zero both for a device
+ that is genuinely absent and for a daemon it could not reach. `config device
+ list` can, because it exits zero only after the daemon enumerated the
+ instance's devices -- so a failure here means "cannot tell" and is raised
+ rather than being read as "there is nothing there".
+ """
+ result = runner.run(
+ incus("config", "device", "list", remote_ref(remote, target.instance), project=target.project),
+ check=False,
+ capture=True,
+ )
+ if result.returncode != 0:
+ raise RegressionError(
+ f"Could not list the devices of {target.instance}: {daemon_failure_detail(result)}\n"
+ f"{DAEMON_UNREACHABLE_HINT}"
+ )
+ return "ui" in (result.stdout or "").split()
+
+
+def observed_ui_endpoints(runner: Runner, target: RegressionTarget, *, remote: str | None) -> dict[str, str] | None:
+ """The endpoints the instance's `ui` device forwards, or None when it has none.
+
+ None is a confirmed absence, never an unanswered question: a daemon that
+ will not say raises instead. The caller is about to change this device, and
+ silence is not evidence that there is nothing there to lose.
+ """
+ if not ui_device_present(runner, target, remote=remote):
+ return None
+ observed: dict[str, str] = {}
+ for key in ("listen", "connect"):
+ result = runner.run(
+ incus(
+ "config",
+ "device",
+ "get",
+ remote_ref(remote, target.instance),
+ "ui",
+ key,
+ project=target.project,
+ ),
+ check=False,
+ capture=True,
+ )
+ value = (result.stdout or "").strip()
+ if result.returncode != 0 or not value:
+ raise RegressionError(
+ f"Incus lists a `ui` device on {target.instance} but would not report its {key}: "
+ f"{daemon_failure_detail(result)}\n{DAEMON_UNREACHABLE_HINT}"
+ )
+ observed[key] = value
+ return observed
+
+
def ensure_proxy_device(runner: Runner, target: RegressionTarget, *, remote: str | None) -> None:
- instance_ref = remote_ref(remote, target.instance)
- runner.run(incus("config", "device", "remove", instance_ref, "ui", project=target.project), check=False)
- runner.run(incus(*proxy_device_args(target, remote=remote), project=target.project))
+ """Make the instance's `ui` proxy device forward the target's endpoints.
+
+ The device is added only when the daemon reported it missing and updated in
+ place only when the daemon reported what it currently forwards. Removing it
+ first was the destructive way to do this: a failed `add` aborted the run
+ with the instance left holding no `ui` device at all, so a routine re-run of
+ `up` could take the Web UI away -- and it ran precisely when the daemon was
+ already misbehaving, because an unreadable device was treated as an absent
+ one. An unreadable device now aborts before anything is mutated.
+ """
+ desired = ui_device_endpoints(target)
+ observed = observed_ui_endpoints(runner, target, remote=remote)
+ if observed is None:
+ runner.run(incus(*proxy_device_args(target, remote=remote), project=target.project))
+ return
+ if observed == desired:
+ print(f"ui proxy device already forwards {desired['listen']} -> {desired['connect']}")
+ return
+ runner.run(
+ incus(
+ "config",
+ "device",
+ "set",
+ remote_ref(remote, target.instance),
+ "ui",
+ f"listen={desired['listen']}",
+ f"connect={desired['connect']}",
+ project=target.project,
+ )
+ )
def ensure_office_converter(
@@ -1543,40 +2328,6 @@ def prepare_show_runtime(runner: Runner, target: RegressionTarget, *, remote: st
runner.run(tenant_exec(target, f"{VENV_DIR}/bin/vibe runtime status --json", remote=remote))
-def update_worktree_mapping(repo_root: Path, target: RegressionTarget) -> None:
- if target.target != WORKTREE_TARGET:
- return
- payload = load_worktree_mapping(repo_root)
- payload.setdefault("worktrees", {})[target.slug] = {
- "path": str(repo_root),
- "project": target.project,
- "instance": target.instance,
- "host_port": target.host_port,
- "updated_at": datetime.now(timezone.utc).isoformat(),
- "branch": branch_name(repo_root),
- "commit": commit_sha(repo_root),
- }
- save_worktree_mapping(repo_root, payload)
-
-
-def reserve_worktree_mapping(repo_root: Path, target: RegressionTarget) -> None:
- if target.target != WORKTREE_TARGET:
- return
- payload = load_worktree_mapping(repo_root)
- payload.setdefault("worktrees", {}).setdefault(target.slug, {})
- payload["worktrees"][target.slug].update(
- {
- "path": str(repo_root),
- "project": target.project,
- "instance": target.instance,
- "host_port": target.host_port,
- "reserved_at": datetime.now(timezone.utc).isoformat(),
- "branch": branch_name(repo_root),
- }
- )
- save_worktree_mapping(repo_root, payload)
-
-
def cmd_doctor(args: argparse.Namespace) -> int:
if not args.dry_run:
require_incus()
@@ -1704,87 +2455,103 @@ def cmd_up(args: argparse.Namespace) -> int:
loaded_env_file = load_env_file(repo_root, args.env_file)
if not args.dry_run:
require_incus()
- preflight_during_target_resolution = args.remote is None and args.target != MASTER_TARGET
- with worktree_mapping_lock(repo_root, dry_run=args.dry_run):
- target = resolve_target(
- args,
- repo_root,
- dry_run=args.dry_run,
- preflight_ports=preflight_during_target_resolution,
- )
- if not args.dry_run:
- reserve_worktree_mapping(repo_root, target)
- with target_update_lock(repo_root, target, dry_run=args.dry_run):
- runner = Runner(dry_run=args.dry_run)
- target_exists = instance_exists(runner, args.remote, target.project, target.instance)
- if not args.dry_run and not target_exists and args.remote is None:
- # Reached only once the daemon has enumerated its instances and this one
- # was absent, so an occupied port is a real conflict with something else
- # rather than this environment's own proxy device.
- ensure_host_port_available(target.ui_host, target.host_port)
- seed_requires_env = not args.dry_run and (args.reset_mode != "none" or not target_exists)
- if seed_requires_env:
- require_runtime_seed_env()
- if target_exists:
- guard_paired_master_reset(
+ metadata = WorktreeMetadata(repo_root, args.remote)
+ # The lock comes before the row, because the lock is what says a run holds
+ # this slug: `reconcile` prunes a reservation whose lock nobody holds, so a
+ # row written outside it is a row that can be dropped while this run is still
+ # building against it. Naming the lock needs only the environment's identity
+ # -- the daemon that holds it and the project on it -- so the port is asked
+ # for and recorded inside the lock that protects it --
+ # picking a free port and reserving it stay one step under the mapping lock,
+ # which is why the identity is observed here and not derived from a target.
+ slug = target_slug(args, repo_root)
+ lock_project = project_name_for(args.target, slug)
+ # Built before the attempt, not inside it: releasing the reservation asks the
+ # daemon what it holds, and a failure while acquiring the update lock would
+ # otherwise reach that handler with no runner to ask through.
+ runner = Runner(dry_run=args.dry_run)
+ reservation: WorktreeReservation | None = None
+ try:
+ with target_update_lock(repo_root, args.remote, lock_project, dry_run=args.dry_run):
+ with metadata.locked(dry_run=args.dry_run):
+ target = resolve_target(args, repo_root, dry_run=args.dry_run, slug=slug)
+ reservation = metadata.reserve(target, dry_run=args.dry_run)
+ target_exists = instance_exists(runner, args.remote, target.project, target.instance)
+ if not args.dry_run and not target_exists and args.remote is None:
+ # Reached only once the daemon has enumerated its instances and this one
+ # was absent, so an occupied port is a real conflict with something else
+ # rather than this environment's own proxy device.
+ ensure_host_port_available(target.ui_host, target.host_port)
+ seed_requires_env = not args.dry_run and (args.reset_mode != "none" or not target_exists)
+ if seed_requires_env:
+ require_runtime_seed_env()
+ if target_exists:
+ guard_paired_master_reset(
+ runner,
+ target,
+ reset_mode=args.reset_mode,
+ allow_reset_paired_master=getattr(args, "allow_reset_paired_master", False),
+ remote=args.remote,
+ )
+ ensure_project_and_instance(
runner,
target,
- reset_mode=args.reset_mode,
- allow_reset_paired_master=getattr(args, "allow_reset_paired_master", False),
+ image=args.image,
+ storage_pool=args.storage_pool,
+ network=args.network,
+ cpus=args.cpus,
+ memory=args.memory,
+ disk=args.disk,
+ processes=args.processes,
remote=args.remote,
)
- ensure_project_and_instance(
- runner,
- target,
- image=args.image,
- storage_pool=args.storage_pool,
- network=args.network,
- cpus=args.cpus,
- memory=args.memory,
- disk=args.disk,
- processes=args.processes,
- remote=args.remote,
- )
- if not args.dry_run and not seed_requires_env and should_seed_state(runner, target, reset_mode=args.reset_mode, remote=args.remote):
- require_runtime_seed_env()
- stop_service_for_update(runner, target, remote=args.remote)
- if seed_requires_env or loaded_env_file is not None or args.dry_run:
- write_runtime_env(runner, target, repo_root=repo_root, remote=args.remote)
- else:
- print("No regression env file loaded; preserving existing runtime env file.")
- migrate_legacy_backend_runtimes(runner, target, remote=args.remote)
- sync_source(runner, target, repo_root, remote=args.remote, clean=args.clean, include_ui_dist=args.no_build_ui)
- fingerprints = compute_fingerprints(repo_root)
- previous_fingerprints = read_existing_fingerprints(runner, target, remote=args.remote)
- invalidate_fingerprints(runner, target, remote=args.remote)
- reconciled = update_dependencies_and_build(
- runner,
- target,
- previous_fingerprints=previous_fingerprints,
- next_fingerprints=fingerprints,
- force_deps=args.force_deps,
- build_ui=not args.no_build_ui,
- force_ui=args.force_ui,
- remote=args.remote,
- )
- # ``prepare_show_runtime`` below is unconditional, so the run either
- # reconciles the show runtime or fails outright.
- reconciled = reconciled | {"show_runtime"}
- run_prepare_state(runner, target, reset_mode=args.reset_mode, remote=args.remote)
- normalize_runtime_config(runner, target, remote=args.remote)
- write_metadata(
- runner,
- target,
- repo_root,
- reconciled_fingerprints(previous_fingerprints, fingerprints, reconciled),
- remote=args.remote,
- )
- # Install updated runtime sources while the service is stopped so the
- # restarted process cannot keep serving code loaded before preparation.
- prepare_show_runtime(runner, target, remote=args.remote)
- restart_and_verify(runner, target, remote=args.remote)
- if not args.dry_run:
- update_worktree_mapping(repo_root, target)
+ if not args.dry_run and not seed_requires_env and should_seed_state(runner, target, reset_mode=args.reset_mode, remote=args.remote):
+ require_runtime_seed_env()
+ stop_service_for_update(runner, target, remote=args.remote)
+ if seed_requires_env or loaded_env_file is not None or args.dry_run:
+ write_runtime_env(runner, target, repo_root=repo_root, remote=args.remote)
+ else:
+ print("No regression env file loaded; preserving existing runtime env file.")
+ migrate_legacy_backend_runtimes(runner, target, remote=args.remote)
+ sync_source(runner, target, repo_root, remote=args.remote, clean=args.clean, include_ui_dist=args.no_build_ui)
+ fingerprints = compute_fingerprints(repo_root)
+ previous_fingerprints = read_existing_fingerprints(runner, target, remote=args.remote)
+ invalidate_fingerprints(runner, target, remote=args.remote)
+ reconciled = update_dependencies_and_build(
+ runner,
+ target,
+ previous_fingerprints=previous_fingerprints,
+ next_fingerprints=fingerprints,
+ force_deps=args.force_deps,
+ build_ui=not args.no_build_ui,
+ force_ui=args.force_ui,
+ remote=args.remote,
+ )
+ # ``prepare_show_runtime`` below is unconditional, so the run either
+ # reconciles the show runtime or fails outright.
+ reconciled = reconciled | {"show_runtime"}
+ run_prepare_state(runner, target, reset_mode=args.reset_mode, remote=args.remote)
+ normalize_runtime_config(runner, target, remote=args.remote)
+ write_metadata(
+ runner,
+ target,
+ repo_root,
+ reconciled_fingerprints(previous_fingerprints, fingerprints, reconciled),
+ remote=args.remote,
+ )
+ # Install updated runtime sources while the service is stopped so the
+ # restarted process cannot keep serving code loaded before preparation.
+ prepare_show_runtime(runner, target, remote=args.remote)
+ restart_and_verify(runner, target, remote=args.remote)
+ reservation.complete()
+ except BaseException:
+ # Not `Exception`: Ctrl-C is how an `up` is abandoned in practice, and a
+ # KeyboardInterrupt would otherwise leave exactly the row this exists for.
+ # `None` covers failing before the row was written -- resolving a target,
+ # or waiting on the update lock -- where there is nothing to give back.
+ if reservation is not None:
+ reservation.release(runner)
+ raise
print_summary(target)
return 0
@@ -1802,7 +2569,7 @@ def print_summary(target: RegressionTarget) -> None:
def cmd_status(args: argparse.Namespace) -> int:
repo_root = current_repo_root()
load_env_file(repo_root, args.env_file)
- target = resolve_target(args, repo_root, dry_run=args.dry_run, allocate_port=False, preflight_ports=False)
+ target = resolve_target(args, repo_root, dry_run=args.dry_run, allocate_port=False)
if not args.dry_run:
require_incus()
runner = Runner(dry_run=args.dry_run)
@@ -1820,7 +2587,7 @@ def cmd_status(args: argparse.Namespace) -> int:
def cmd_logs(args: argparse.Namespace) -> int:
repo_root = current_repo_root()
load_env_file(repo_root, args.env_file)
- target = resolve_target(args, repo_root, dry_run=args.dry_run, allocate_port=False, preflight_ports=False)
+ target = resolve_target(args, repo_root, dry_run=args.dry_run, allocate_port=False)
if not args.dry_run:
require_incus()
Runner(dry_run=args.dry_run).run(
@@ -1833,7 +2600,7 @@ def cmd_logs(args: argparse.Namespace) -> int:
def cmd_shell(args: argparse.Namespace) -> int:
repo_root = current_repo_root()
load_env_file(repo_root, args.env_file)
- target = resolve_target(args, repo_root, dry_run=args.dry_run, allocate_port=False, preflight_ports=False)
+ target = resolve_target(args, repo_root, dry_run=args.dry_run, allocate_port=False)
if not args.dry_run:
require_incus()
Runner(dry_run=args.dry_run).run(tenant_exec(target, "exec bash -l", remote=args.remote))
@@ -1843,7 +2610,7 @@ def cmd_shell(args: argparse.Namespace) -> int:
def cmd_down(args: argparse.Namespace) -> int:
repo_root = current_repo_root()
load_env_file(repo_root, args.env_file)
- target = resolve_target(args, repo_root, dry_run=args.dry_run, allocate_port=False, preflight_ports=False)
+ target = resolve_target(args, repo_root, dry_run=args.dry_run, allocate_port=False)
if not args.dry_run:
require_incus()
Runner(dry_run=args.dry_run).run(incus("stop", remote_ref(args.remote, target.instance), project=target.project), check=False)
@@ -1853,54 +2620,195 @@ def cmd_down(args: argparse.Namespace) -> int:
def cmd_delete(args: argparse.Namespace) -> int:
repo_root = current_repo_root()
load_env_file(repo_root, args.env_file)
- target = resolve_target(args, repo_root, dry_run=args.dry_run, allocate_port=False, preflight_ports=False)
- if target.target == MASTER_TARGET and not args.yes:
+ if args.target == MASTER_TARGET and not args.yes:
raise RegressionError("Deleting the master regression environment requires --yes.")
if not args.dry_run:
require_incus()
- runner = Runner(dry_run=args.dry_run)
- runner.run(incus("delete", remote_ref(args.remote, target.instance), "--force", project=target.project), check=False)
- runner.run(incus("project", "delete", remote_ref(args.remote, target.project)), check=False)
- if target.target == WORKTREE_TARGET and not args.dry_run:
- payload = load_worktree_mapping(repo_root)
- (payload.get("worktrees") or {}).pop(target.slug, None)
- save_worktree_mapping(repo_root, payload)
+ # Removing the objects and forgetting the row are one change to what this
+ # slug names, so both happen under the environment's update lock -- the same
+ # one `up` holds from before it writes its row until after it stamps it.
+ # Without it, a delete landing while an `up` builds deletes nothing, because
+ # the objects do not exist yet, drops that run's reservation anyway, and
+ # leaves the finished environment with no row and its host port free for the
+ # next slug: `complete` will not restore a row that is no longer the one its
+ # run reserved. Naming the lock needs only the identity, as in `up`, so the
+ # target is resolved inside it and nothing about this slug is read outside.
+ slug = target_slug(args, repo_root)
+ lock_project = project_name_for(args.target, slug)
+ with target_update_lock(repo_root, args.remote, lock_project, dry_run=args.dry_run, blocking=False):
+ target = resolve_target(args, repo_root, dry_run=args.dry_run, allocate_port=False, slug=slug)
+ runner = Runner(dry_run=args.dry_run)
+ runner.run(incus("delete", remote_ref(args.remote, target.instance), "--force", project=target.project), check=False)
+ runner.run(incus("project", "delete", remote_ref(args.remote, target.project)), check=False)
+ if target.target == WORKTREE_TARGET and not args.dry_run:
+ metadata = WorktreeMetadata(repo_root, args.remote)
+ metadata.forget([target.slug])
+ if not metadata.owned:
+ # The row describes a slug and host port on this machine, and this
+ # deletion happened somewhere else, so `forget` above did nothing.
+ # Saying so is all that is left to the caller: a slug used on both
+ # daemons would otherwise lose its local port reservation the moment
+ # the remote copy was removed, and lose it silently.
+ print(f"Kept the local metadata for {target.slug}: it describes the local Incus daemon, not remote {args.remote}.")
return 0
-def cmd_cleanup_stale(args: argparse.Namespace) -> int:
+def cmd_reconcile(args: argparse.Namespace) -> int:
+ """Report what Incus holds, and drop metadata for environments it no longer has.
+
+ This replaces the old `cleanup-stale`, which deleted an environment whose
+ recorded worktree path had disappeared. That criterion could not work: the
+ path records the checkout the runner was invoked from, so several
+ environments created from one checkout share it, and it keeps existing after
+ the worktree they were built for is gone. It therefore deleted running
+ environments that were still wanted and kept ones nobody wanted.
+
+ Nothing else about a regression environment says whether it is still wanted
+ either -- a slug is chosen by the caller and an environment may sit on a
+ detached HEAD with no branch to check for a merge -- so this command does not
+ guess. It shows every environment with its state and provenance, leaves
+ container deletion to an explicit `delete --slug`, and only ever removes
+ metadata rows Incus has already outlived.
+
+ "Already outlived" is deliberately strict: a row is dropped only when the
+ daemon that owns it completed a listing, that listing held neither half of
+ the environment, and no live run holds that slug -- the last of which is
+ asked of the kernel rather than of the row, because a row cannot answer it
+ (see `target_run_in_flight`). Every weaker reading of the same evidence would
+ release a host port somebody else is using.
+ """
repo_root = current_repo_root()
- payload = load_worktree_mapping(repo_root)
- stale = []
- for slug, item in (payload.get("worktrees") or {}).items():
- path = Path(str(item.get("path", "")))
- if not path.exists():
- stale.append((slug, item))
- if not stale:
- print("No stale worktree regression environments found.")
+ require_incus()
+ # Enumeration must be a real listing even under --dry-run: `Runner.names`
+ # answers [] for a dry run by contract, which would report every existing
+ # environment as untracked metadata and offer to forget all of it. --dry-run
+ # withholds the mapping write instead, which is this command's only change.
+ runner = Runner(dry_run=False)
+ metadata = WorktreeMetadata(repo_root, args.remote)
+ authority = f"remote {args.remote}" if args.remote else "the local Incus daemon"
+ remote_suffix = f" --remote {shlex.quote(args.remote)}" if args.remote else ""
+ # The mapping is read, classified, and written under one lock -- taken through
+ # the accessor, so it is held only when this file is what the decision is
+ # about -- and no row can be added or completed midway through. That lock is
+ # not what makes a reservation safe, though: `up` releases it as soon as the
+ # row is written and keeps building for minutes afterwards, so a reconcile in
+ # that window legitimately sees a row with no footprint yet. What protects
+ # such a row is the target update lock its run holds across the whole window,
+ # which is a live process rather than a record -- see `target_run_in_flight`.
+ with metadata.locked(dry_run=False):
+ environments = worktree_environments(runner, metadata)
+ if not environments:
+ print(f"No worktree regression environments exist in {authority}.")
+ return 0
+
+ live = [env for env in environments if env.exists]
+ in_flight = [env for env in environments if not env.exists and env.in_flight]
+ forgotten = [env for env in environments if not env.exists and not env.in_flight]
+
+ if live:
+ print(f"{len(live)} worktree regression environment(s) exist in {authority}:")
+ for env in live:
+ print(f" {env.slug} [{env.footprint}] {describe_worktree_entry(env.entry)}")
+ print()
+ # Deletion stays explicit and per-environment. `delete` derives the
+ # project and instance from the slug by naming convention, so it
+ # reaches an environment with no metadata just as well as a tracked
+ # one -- but only where that convention matches what Incus holds.
+ #
+ # The two lists overlap on purpose. An environment can hold a
+ # convention-project instance and a stranded one at the same time, so
+ # partitioning it into one bucket or the other has to be wrong about
+ # something: either it offers a delete command that leaves an instance
+ # running, or it withholds one that would reclaim most of the disk.
+ # Saying both is the only honest report.
+ deletable = [env for env in live if env.deletable_by_slug]
+ if deletable:
+ print("Delete any of them with:")
+ for env in deletable:
+ print(
+ " python3 scripts/incus_regression.py delete --target worktree "
+ f"--slug {shlex.quote(env.slug)} --yes{remote_suffix}"
+ )
+ for env in live:
+ if not env.reachable_by_slug:
+ # `delete --slug` validates its argument, so for this name it
+ # reaches nothing at all -- and the whole point of enumerating
+ # from Incus is to find environments the runner did not create,
+ # whose names nothing constrained. Printing the command anyway
+ # would advertise a reclamation that exits on its own argument,
+ # so the objects are named for a manual one instead.
+ observed = [env.project] if env.has_project else []
+ observed += sorted(f"{item.project}/{env.instance}" for item in env.instances)
+ print(
+ f" {env.slug}: not a slug this runner accepts, so `delete --slug` would "
+ f"reject it. Reclaim by hand: {', '.join(observed)}."
+ )
+ continue
+ for item in env.stranded_instances:
+ print(
+ f" {env.slug}: instance lives in project {item.project}, not {env.project}. "
+ "Delete by slug would not reach it; reclaim it by hand."
+ )
+ if not metadata.owned:
+ # Said once rather than implied by every environment reading
+ # "no runner metadata". `worktrees.json` records what this
+ # machine's daemon holds, so annotating another daemon's
+ # environments from it would attribute a local row's port,
+ # branch, and commit to an environment that merely shares its
+ # slug. One report, one authority; run `reconcile` with no
+ # --remote for the local rows.
+ print()
+ print(f"Runner metadata is not shown: it describes the local Incus daemon, not {authority}.")
+
+ if in_flight:
+ if live:
+ print()
+ print(f"{len(in_flight)} metadata entr(ies) reserve a slug an `up` is still holding:")
+ for env in in_flight:
+ print(f" {env.slug} {describe_worktree_entry(env.entry)}")
+ # No recovery to name here any more. This section is a live process
+ # holding a lock, so an `up` that was killed is not in it: the kernel
+ # dropped its lock as it died, and its row is reported below as an
+ # environment this daemon no longer has, which `--yes` prunes.
+ print("Left alone: that run holds this slug's update lock right now, and its port stays reserved.")
+
+ if not forgotten:
+ return 0
+ if live or in_flight:
+ print()
+ # Only rows this daemon owns can reach here at all: a report about
+ # another daemon annotates nothing from this file, so every slug it
+ # lists came from that daemon's own projects and instances and is
+ # therefore present. The "a remote never prunes" rule needs no branch
+ # here any more; it is a consequence of who the rows belong to.
+ print(f"{len(forgotten)} metadata entr(ies) describe environments {authority} no longer has:")
+ for env in forgotten:
+ print(f" {env.slug} {describe_worktree_entry(env.entry)}")
+ # Reporting is what this command is for, so having found something to
+ # report is not a failure: it exits 0 whether or not any row was stale.
+ # Raising here made the documented plain `reconcile` exit non-zero for
+ # exactly the case it exists to show, which reads as a broken command to
+ # a `&&` chain, a CI step, or anyone who checks `$?` -- while the report
+ # it just printed says the run went fine. `--yes` is what asks for the
+ # write, and `--dry-run` withholds it even then.
+ if args.dry_run or not args.yes:
+ print("Nothing was changed. Dropping them and releasing their reserved host ports needs --yes and no --dry-run.")
+ return 0
+ metadata.forget(env.slug for env in forgotten)
+ print(f"Dropped {len(forgotten)} stale metadata entr(ies). No instance was deleted.")
return 0
- if not args.yes and not args.dry_run:
- raise RegressionError("Stale worktree cleanup requires --yes.")
- runner = Runner(dry_run=args.dry_run)
- for slug, item in stale:
- project = str(item.get("project") or project_name_for(WORKTREE_TARGET, slug))
- instance = str(item.get("instance") or instance_name_for(WORKTREE_TARGET, slug))
- runner.run(incus("delete", remote_ref(args.remote, instance), "--force", project=project), check=False)
- runner.run(incus("project", "delete", remote_ref(args.remote, project)), check=False)
- if not args.dry_run:
- payload["worktrees"].pop(slug, None)
- if not args.dry_run:
- save_worktree_mapping(repo_root, payload)
- return 0
def add_common(parser: argparse.ArgumentParser) -> None:
parser.add_argument("--dry-run", action="store_true", help="Print commands without changing Incus.")
# Keep --remote as an explicit escape hatch for the rare remote-ops case the
- # docs call out. Local dev defaults to None (no remote); the remote_ref /
- # preflight-skip machinery still keys off it, so deleting the flag would force
- # args.remote=None always and run the host-port preflight on the wrong host.
- parser.add_argument("--remote", help="Optional Incus remote name.")
+ # docs call out. Local dev defaults to None (no remote), and it is what names
+ # the daemon every command acts on: `remote_ref` addresses it, and
+ # `WorktreeMetadata` uses it to decide whether this machine's metadata is
+ # evidence about that daemon at all. Both read the same value, which is why
+ # it is normalized here -- the one place every command's --remote is defined
+ # -- rather than at each reader.
+ parser.add_argument("--remote", type=normalized_remote, help="Optional Incus remote name.")
def add_target_args(parser: argparse.ArgumentParser) -> None:
@@ -1972,10 +2880,13 @@ def build_parser() -> argparse.ArgumentParser:
sub.add_argument("--yes", action="store_true")
sub.set_defaults(func=func)
- cleanup = subparsers.add_parser("cleanup-stale", help="Delete environments for missing worktree paths.")
- add_common(cleanup)
- cleanup.add_argument("--yes", action="store_true")
- cleanup.set_defaults(func=cmd_cleanup_stale)
+ reconcile = subparsers.add_parser(
+ "reconcile",
+ help="List worktree environments Incus holds, and forget metadata for ones it no longer has.",
+ )
+ add_common(reconcile)
+ reconcile.add_argument("--yes", action="store_true")
+ reconcile.set_defaults(func=cmd_reconcile)
return parser
@@ -1987,6 +2898,12 @@ def main(argv: Sequence[str] | None = None) -> int:
except RegressionError as exc:
print(str(exc), file=sys.stderr)
return 1
+ except subprocess.CalledProcessError as exc:
+ # A failing `check=True` step is an expected outcome here -- a busy host
+ # port, a device Incus refuses, a daemon that went away mid-run. Report
+ # which command failed instead of unwinding a traceback over it.
+ print(f"Command failed with exit code {exc.returncode}: {shlex.join(exc.cmd)}", file=sys.stderr)
+ return 1
if __name__ == "__main__":
diff --git a/tests/test_incus_regression.py b/tests/test_incus_regression.py
index 050ef0799..53470fc7c 100644
--- a/tests/test_incus_regression.py
+++ b/tests/test_incus_regression.py
@@ -1,10 +1,12 @@
from __future__ import annotations
import argparse
+import contextlib
import io
import importlib.util
import json
import os
+import shlex
import subprocess
import sys
import tarfile
@@ -180,6 +182,7 @@ def test_worktree_target_slug_includes_path_hash(monkeypatch: pytest.MonkeyPatch
host_port=15234,
ui_host="127.0.0.1",
ui_port=5123,
+ remote=None,
worktree_port_start=15200,
worktree_port_end=15399,
),
@@ -202,26 +205,90 @@ def test_explicit_worktree_slug_round_trips_generated_slug(monkeypatch: pytest.M
assert incus_regression.worktree_slug(repo_root, generated) == generated
-def test_remote_worktree_target_skips_local_port_preflight(monkeypatch: pytest.MonkeyPatch) -> None:
+def test_remote_worktree_target_requires_an_explicit_host_port(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(incus_regression, "branch_name", lambda repo_root: "feature/demo")
- monkeypatch.setattr(incus_regression, "ensure_host_port_available", lambda host, port: (_ for _ in ()).throw(AssertionError("should not preflight remote ports")))
+ monkeypatch.setattr(
+ incus_regression,
+ "ensure_host_port_available",
+ lambda host, port: (_ for _ in ()).throw(AssertionError("should not preflight remote ports")),
+ )
+
+ with pytest.raises(incus_regression.RegressionError) as excinfo:
+ incus_regression.resolve_target(
+ argparse.Namespace(
+ target="worktree",
+ slug=None,
+ host_port=None,
+ ui_host="127.0.0.1",
+ ui_port=5123,
+ remote="lab",
+ worktree_port_start=15200,
+ worktree_port_end=15200,
+ ),
+ Path("/tmp/repo-a"),
+ dry_run=False,
+ )
+
+ assert "--host-port is required" in str(excinfo.value)
+
+
+def test_remote_worktree_target_uses_the_explicit_host_port(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ """An explicit port is the only port a remote worktree gets, local row or not."""
+ runtime = tmp_path / ".runtime" / "incus-regression"
+ runtime.mkdir(parents=True)
+ (runtime / "worktrees.json").write_text(
+ json.dumps({"schema_version": 1, "worktrees": {"demo-branch": {"host_port": 15234}}}),
+ encoding="utf-8",
+ )
+ monkeypatch.setattr(incus_regression, "git_common_root", lambda repo_root: repo_root)
target = incus_regression.resolve_target(
argparse.Namespace(
target="worktree",
- slug=None,
+ slug="demo-branch",
+ host_port=15300,
+ ui_host="127.0.0.1",
+ ui_port=5123,
+ remote="lab",
+ worktree_port_start=15200,
+ worktree_port_end=15399,
+ ),
+ tmp_path,
+ dry_run=False,
+ )
+
+ assert target.host_port == 15300
+
+
+def test_remote_worktree_maintenance_target_does_not_inherit_a_local_port(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """`status --remote` on a slug this machine also uses reports no port, not the local one."""
+ runtime = tmp_path / ".runtime" / "incus-regression"
+ runtime.mkdir(parents=True)
+ (runtime / "worktrees.json").write_text(
+ json.dumps({"schema_version": 1, "worktrees": {"demo-branch": {"host_port": 15234}}}),
+ encoding="utf-8",
+ )
+ monkeypatch.setattr(incus_regression, "git_common_root", lambda repo_root: repo_root)
+
+ target = incus_regression.resolve_target(
+ argparse.Namespace(
+ target="worktree",
+ slug="demo-branch",
host_port=None,
ui_host="127.0.0.1",
ui_port=5123,
+ remote="lab",
worktree_port_start=15200,
- worktree_port_end=15200,
+ worktree_port_end=15399,
),
- Path("/tmp/repo-a"),
+ tmp_path,
dry_run=False,
- preflight_ports=False,
+ allocate_port=False,
)
- assert target.host_port == 15200
+ assert target.host_port == 0
def test_worktree_target_reuses_mapped_port_without_allocation(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
@@ -241,6 +308,7 @@ def test_worktree_target_reuses_mapped_port_without_allocation(tmp_path: Path, m
host_port=None,
ui_host="127.0.0.1",
ui_port=5123,
+ remote=None,
worktree_port_start=15200,
worktree_port_end=15399,
),
@@ -261,13 +329,13 @@ def test_worktree_maintenance_target_does_not_allocate_port(tmp_path: Path, monk
host_port=None,
ui_host="127.0.0.1",
ui_port=5123,
+ remote=None,
worktree_port_start=15200,
worktree_port_end=15399,
),
tmp_path,
dry_run=False,
allocate_port=False,
- preflight_ports=False,
)
assert target.host_port == 0
@@ -359,7 +427,7 @@ def test_require_incus_reports_missing_override(monkeypatch: pytest.MonkeyPatch)
def test_existence_comes_from_the_names_the_daemon_listed(monkeypatch: pytest.MonkeyPatch) -> None:
- listing = json.dumps([{"name": "avr-master"}, {"name": "avr-wt-demo-branch"}, {"other": "ignored"}])
+ listing = json.dumps([{"name": "avr-master"}, {"name": "avr-wt-demo-branch"}])
monkeypatch.setattr(incus_regression.subprocess, "run", stub_incus_result(0, stdout=listing))
names = incus_regression.Runner().names(incus_regression.incus("project", "list"), what="Incus projects")
@@ -367,6 +435,32 @@ def test_existence_comes_from_the_names_the_daemon_listed(monkeypatch: pytest.Mo
assert names == ["avr-master", "avr-wt-demo-branch"]
+ "entry",
+ [
+ pytest.param({"other": "ignored"}, id="no-name"),
+ pytest.param({"name": None}, id="null-name"),
+ pytest.param({"name": 7}, id="non-string-name"),
+ pytest.param("avr-master", id="not-an-object"),
+ ],
+)
+def test_an_entry_the_runner_cannot_read_makes_the_whole_listing_unanswerable(
+ monkeypatch: pytest.MonkeyPatch, entry
+) -> None:
+ """An unparseable entry is a listing nobody enumerated, not one entry fewer.
+
+ Dropping it leaves an inventory that looks complete and happens to be
+ missing whatever the runner could not read -- which reads as a confirmed
+ absence, and `reconcile --yes` acts on a confirmed absence by releasing host
+ ports that are still in use.
+ """
+ listing = json.dumps([{"name": "avr-master"}, entry])
+ monkeypatch.setattr(incus_regression.subprocess, "run", stub_incus_result(0, stdout=listing))
+
+ with pytest.raises(incus_regression.RegressionError, match="Unreadable entry"):
+ incus_regression.Runner().names(incus_regression.incus("project", "list"), what="Incus projects")
+
+
@pytest.mark.parametrize(
"result",
[
@@ -453,7 +547,154 @@ def test_proxy_device_uses_remote_instance_ref() -> None:
assert "connect=tcp:127.0.0.1:5123" in args
-def test_existing_instance_proxy_device_is_refreshed() -> None:
+def proxy_device_runner(observed: dict[str, str] | None, *, listable: bool = True):
+ """A runner that answers device queries the way Incus does.
+
+ `config device list` is the observation that can distinguish an absent
+ device from an unreachable daemon: `listable=False` fails it the way a
+ daemon that cannot be reached does, while `observed=None` is a listing the
+ daemon completed which simply has no `ui` device in it. `config device get`
+ answers from `observed`.
+ """
+
+ commands = []
+
+ class RecordingRunner:
+ names = daemon_listing(*MASTER_NAMES)
+
+ def run(self, command, *, check=True, capture=False, **kwargs):
+ commands.append((command, check))
+ if "list" in command and "device" in command:
+ if not listable:
+ return subprocess.CompletedProcess(
+ command, 1, stdout="", stderr="Error: Failed to fetch instance: Instance not found"
+ )
+ return subprocess.CompletedProcess(command, 0, stdout="root\n" if observed is None else "root\nui\n")
+ if "get" in command and "ui" in command:
+ if observed is None or command[-1] not in observed:
+ return subprocess.CompletedProcess(command, 1, stdout="", stderr="Error: Device doesn't exist")
+ return subprocess.CompletedProcess(command, 0, stdout=f"{observed[command[-1]]}\n")
+ return subprocess.CompletedProcess(command, 0, stdout="")
+
+ return RecordingRunner(), commands
+
+
+def test_matching_proxy_device_is_left_alone() -> None:
+ target = incus_regression.RegressionTarget(
+ target="master",
+ slug="master",
+ project="avr-master",
+ instance="avibe-master",
+ host_port=15130,
+ ui_host="127.0.0.1",
+ ui_port=5123,
+ )
+ runner, commands = proxy_device_runner(
+ {"listen": "tcp:127.0.0.1:15130", "connect": "tcp:127.0.0.1:5123"}
+ )
+
+ incus_regression.ensure_proxy_device(runner, target, remote=None)
+
+ # A device that already forwards the wanted endpoints must not be touched:
+ # removing it drops the port forward, and every `up` used to do exactly that.
+ mutations = [command for command, _ in commands if {"add", "remove", "set"} & set(command)]
+ assert mutations == []
+
+
+def test_mismatched_proxy_device_is_updated_in_place() -> None:
+ target = incus_regression.RegressionTarget(
+ target="master",
+ slug="master",
+ project="avr-master",
+ instance="avibe-master",
+ host_port=15131,
+ ui_host="127.0.0.1",
+ ui_port=5123,
+ )
+ runner, commands = proxy_device_runner(
+ {"listen": "tcp:127.0.0.1:15130", "connect": "tcp:127.0.0.1:5123"}
+ )
+
+ incus_regression.ensure_proxy_device(runner, target, remote=None)
+
+ rendered = [" ".join(command) for command, _ in commands]
+ assert (
+ "incus --project avr-master config device set avibe-master ui"
+ " listen=tcp:127.0.0.1:15131 connect=tcp:127.0.0.1:5123" in rendered
+ )
+ # An in-place set leaves no window in which the instance has no ui device,
+ # so a repointed port never needs the device removed first.
+ assert not any("remove" in command for command, _ in commands)
+
+
+def test_absent_proxy_device_is_added_without_a_removal() -> None:
+ target = incus_regression.RegressionTarget(
+ target="master",
+ slug="master",
+ project="avr-master",
+ instance="avibe-master",
+ host_port=15131,
+ ui_host="127.0.0.1",
+ ui_port=5123,
+ )
+ runner, commands = proxy_device_runner(None)
+
+ incus_regression.ensure_proxy_device(runner, target, remote=None)
+
+ rendered = [" ".join(command) for command, _ in commands]
+ assert any(
+ "incus --project avr-master config device add avibe-master ui proxy"
+ " listen=tcp:127.0.0.1:15131" in command
+ for command in rendered
+ )
+ # There is nothing to remove: the daemon listed this instance's devices and
+ # `ui` was not among them.
+ assert not any("remove" in command for command, _ in commands)
+
+
+def test_unlistable_devices_abort_before_anything_is_mutated() -> None:
+ target = incus_regression.RegressionTarget(
+ target="master",
+ slug="master",
+ project="avr-master",
+ instance="avibe-master",
+ host_port=15131,
+ ui_host="127.0.0.1",
+ ui_port=5123,
+ )
+ runner, commands = proxy_device_runner(
+ {"listen": "tcp:127.0.0.1:15130", "connect": "tcp:127.0.0.1:5123"}, listable=False
+ )
+
+ with pytest.raises(incus_regression.RegressionError) as excinfo:
+ incus_regression.ensure_proxy_device(runner, target, remote=None)
+
+ # A daemon that will not answer is the one case where acting is worst: the
+ # instance may well have a working `ui` device that nobody can see.
+ assert "Instance not found" in str(excinfo.value)
+ assert [command for command, _ in commands if {"add", "remove", "set"} & set(command)] == []
+
+
+def test_listed_device_with_unreadable_endpoints_aborts() -> None:
+ target = incus_regression.RegressionTarget(
+ target="master",
+ slug="master",
+ project="avr-master",
+ instance="avibe-master",
+ host_port=15131,
+ ui_host="127.0.0.1",
+ ui_port=5123,
+ )
+ runner, commands = proxy_device_runner({"listen": "tcp:127.0.0.1:15130"})
+
+ with pytest.raises(incus_regression.RegressionError) as excinfo:
+ incus_regression.ensure_proxy_device(runner, target, remote=None)
+
+ assert "would not report its connect" in str(excinfo.value)
+ assert [command for command, _ in commands if {"add", "remove", "set"} & set(command)] == []
+
+
+def test_existing_instance_is_not_reinitialised() -> None:
commands = []
class RecordingRunner:
@@ -487,8 +728,6 @@ def test_existing_instance_proxy_device_is_refreshed() -> None:
)
rendered = [" ".join(command) for command, _ in commands]
- assert "incus --project avr-master config device remove avibe-master ui" in rendered
- assert any("incus --project avr-master config device add avibe-master ui proxy listen=tcp:127.0.0.1:15131" in command for command in rendered)
assert not any(" init " in f" {command} " for command in rendered)
assert any(
"PATH=/usr/bin:/bin command -v soffice" in command
@@ -1395,25 +1634,29 @@ def test_write_runtime_env_uses_stdin_not_command_line() -> None:
assert "OPENAI_API_KEY" not in joined_command
-def test_cleanup_stale_deletes_missing_worktree_mapping(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+def reconcile_fixture(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ *,
+ entries: dict,
+ projects: tuple[str, ...],
+ instances: tuple[dict, ...],
+) -> tuple[Path, list]:
+ """Point `reconcile` at a repo with `entries` recorded and `projects` in Incus.
+
+ A record in `instances` may omit `project`, in which case it is placed in the
+ project its name implies -- `incus list` always reports one, and only a test
+ about misplacement needs to say which. That default substitutes one prefix
+ for the other rather than minting a name, so a fixture is free to describe an
+ environment whose name the runner would have refused to create: that is
+ precisely the environment enumerating from Incus exists to find.
+ """
+
repo = tmp_path / "repo"
- repo.mkdir()
runtime = repo / ".runtime" / "incus-regression"
runtime.mkdir(parents=True)
(runtime / "worktrees.json").write_text(
- json.dumps(
- {
- "schema_version": 1,
- "worktrees": {
- "old": {
- "path": str(tmp_path / "missing"),
- "project": "avr-wt-old",
- "instance": "avibe-wt-old",
- }
- },
- }
- ),
- encoding="utf-8",
+ json.dumps({"schema_version": 1, "worktrees": entries}), encoding="utf-8"
)
commands = []
@@ -1426,90 +1669,1019 @@ def test_cleanup_stale_deletes_missing_worktree_mapping(tmp_path: Path, monkeypa
commands.append(command)
return subprocess.CompletedProcess(command, 0)
+ def names(self, command, *, what):
+ commands.append(command)
+ return list(projects)
+
+ def records(self, command, *, what):
+ commands.append(command)
+ return [
+ {
+ "project": incus_regression.WORKTREE_PROJECT_PREFIX
+ + str(item["name"]).removeprefix(incus_regression.WORKTREE_INSTANCE_PREFIX),
+ **dict(item),
+ }
+ for item in instances
+ ]
+
monkeypatch.setattr(incus_regression, "current_repo_root", lambda: repo)
monkeypatch.setattr(incus_regression, "git_common_root", lambda repo_root: repo_root)
+ monkeypatch.setattr(incus_regression, "require_incus", lambda: None)
monkeypatch.setattr(incus_regression, "Runner", RecordingRunner)
+ return runtime / "worktrees.json", commands
- exit_code = incus_regression.cmd_cleanup_stale(argparse.Namespace(yes=True, dry_run=False, remote=None))
+
+def test_reconcile_reports_environments_incus_holds_without_metadata(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
+) -> None:
+ mapping_path, commands = reconcile_fixture(
+ tmp_path,
+ monkeypatch,
+ entries={"tracked": {"path": str(tmp_path / "checkout"), "host_port": 52900, "branch": "fix/one"}},
+ projects=("default", "avr-master", "avr-wt-tracked", "avr-wt-orphan"),
+ instances=(
+ {"name": "avibe-master", "status": "Running"},
+ {"name": "avibe-wt-orphan", "status": "Running"},
+ {"name": "avibe-wt-tracked", "status": "Stopped"},
+ ),
+ )
+
+ exit_code = incus_regression.cmd_reconcile(
+ argparse.Namespace(yes=False, dry_run=False, remote=None)
+ )
+ out = capsys.readouterr().out
assert exit_code == 0
- assert ["incus", "--project", "avr-wt-old", "delete", "avibe-wt-old", "--force"] in commands
- payload = json.loads((runtime / "worktrees.json").read_text(encoding="utf-8"))
- assert payload["worktrees"] == {}
+ # Enumerating from Incus is the point: an environment created outside the
+ # runner has no metadata row, so walking the mapping cannot see it at all.
+ assert "orphan [project, Running] no runner metadata" in out
+ assert "delete --target worktree --slug orphan --yes" in out
+ assert "tracked [project, Stopped]" in out
+ assert "delete --target worktree --slug tracked --yes" in out
+ # The master environment is not a worktree environment and is never listed.
+ assert "2 worktree regression environment(s)" in out
+ assert not any(line.startswith(" master ") for line in out.splitlines())
+ # Reporting must never delete an environment.
+ assert not any("delete" in command for command in commands)
+ payload = json.loads(mapping_path.read_text(encoding="utf-8"))
+ assert set(payload["worktrees"]) == {"tracked"}
-def test_delete_round_trips_generated_worktree_slug(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
- repo = tmp_path / "repo"
- repo.mkdir()
- runtime = repo / ".runtime" / "incus-regression"
- runtime.mkdir(parents=True)
- slug = "fix-regression-source-id-3200ccd6"
- project = f"avr-wt-{slug}"
- instance = f"avibe-wt-{slug}"
- mapping_path = runtime / "worktrees.json"
- mapping_path.write_text(
- json.dumps(
- {
- "schema_version": 1,
- "worktrees": {
- slug: {
- "path": str(tmp_path / "missing"),
- "project": project,
- "instance": instance,
- "host_port": 15205,
- }
- },
- }
- ),
- encoding="utf-8",
+def test_reconcile_forgets_metadata_for_environments_incus_no_longer_has(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
+) -> None:
+ # `gone` records a path that still exists, which is exactly the case the old
+ # staleness criterion could not see: the path is the checkout the runner was
+ # invoked from, not the environment. Incus is what settles it.
+ checkout = tmp_path / "checkout"
+ checkout.mkdir()
+ mapping_path, commands = reconcile_fixture(
+ tmp_path,
+ monkeypatch,
+ entries={
+ "gone": {"path": str(checkout), "host_port": 52901, "commit": "b69d287d32f6aaaa"},
+ "kept": {"path": str(checkout), "host_port": 52902, "branch": "fix/two"},
+ },
+ projects=("avr-wt-kept",),
+ instances=({"name": "avibe-wt-kept", "status": "Running"},),
)
- commands = []
- class RecordingRunner:
- def __init__(self, *, dry_run=False):
- self.dry_run = dry_run
+ exit_code = incus_regression.cmd_reconcile(
+ argparse.Namespace(yes=True, dry_run=False, remote=None)
+ )
+ out = capsys.readouterr().out
- def run(self, command, *, check=True, **kwargs):
- commands.append(command)
- return subprocess.CompletedProcess(command, 0)
+ assert exit_code == 0
+ assert "gone port 52901, detached at b69d287d32f6" in out
+ payload = json.loads(mapping_path.read_text(encoding="utf-8"))
+ assert set(payload["worktrees"]) == {"kept"}
+ # Only metadata changes. The environment Incus still holds keeps running.
+ assert not any("delete" in command for command in commands)
- monkeypatch.setattr(incus_regression, "current_repo_root", lambda: repo)
- monkeypatch.setattr(incus_regression, "git_common_root", lambda _repo_root: repo)
- monkeypatch.setattr(incus_regression, "load_env_file", lambda _repo_root, _env_file: None)
- monkeypatch.setattr(incus_regression, "require_incus", lambda: None)
- monkeypatch.setattr(incus_regression, "Runner", RecordingRunner)
- exit_code = incus_regression.cmd_delete(
- argparse.Namespace(
- target="worktree",
- slug=slug,
- env_file=None,
- host_port=None,
- ui_host="127.0.0.1",
- ui_port=5123,
- worktree_port_start=15200,
- worktree_port_end=15399,
- dry_run=False,
- remote=None,
- yes=True,
- )
+def test_reconcile_dry_run_keeps_metadata(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
+) -> None:
+ mapping_path, _ = reconcile_fixture(
+ tmp_path,
+ monkeypatch,
+ entries={"gone": {"path": str(tmp_path / "checkout"), "host_port": 52903}},
+ projects=(),
+ instances=(),
+ )
+
+ exit_code = incus_regression.cmd_reconcile(
+ argparse.Namespace(yes=False, dry_run=True, remote=None)
)
+ out = capsys.readouterr().out
assert exit_code == 0
- assert commands == [
- ["incus", "--project", project, "delete", instance, "--force"],
- ["incus", "project", "delete", project],
- ]
+ assert "needs --yes" in out
payload = json.loads(mapping_path.read_text(encoding="utf-8"))
- assert payload["worktrees"] == {}
+ assert set(payload["worktrees"]) == {"gone"}
-def test_up_skips_host_port_preflight_for_existing_instance(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
- write_ui_builder_stage(tmp_path)
- (tmp_path / "pyproject.toml").write_text("[project]\nname='x'\n", encoding="utf-8")
- (tmp_path / "uv.lock").write_text("", encoding="utf-8")
- (tmp_path / "ui").mkdir()
- (tmp_path / "ui" / "package.json").write_text("{}", encoding="utf-8")
+ ("yes", "dry_run"),
+ [(yes, dry_run) for yes in (False, True) for dry_run in (False, True) if not (yes and not dry_run)],
+ ids=lambda value: f"{value}",
+)
+def test_reconcile_reports_stale_metadata_without_writing_or_failing(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], yes: bool, dry_run: bool
+) -> None:
+ """Having something to report is what this command is for, not a failure.
+
+ Asserted over every combination that withholds the write -- the whole product
+ of the two flags minus the one that asks for it, so a mode cannot be left out
+ of the enumeration. `reconcile` used to raise here, which made the documented
+ plain command exit non-zero for exactly the case it exists to show: a `&&`
+ chain, a CI step, or anyone reading `$?` cannot tell that from the command
+ breaking, while the report it just printed says the run went fine. The one
+ writing combination is `test_reconcile_forgets_metadata_for_environments…`.
+ """
+ mapping_path, _ = reconcile_fixture(
+ tmp_path,
+ monkeypatch,
+ entries={"gone": {"path": str(tmp_path / "checkout"), "host_port": 52904}},
+ projects=(),
+ instances=(),
+ )
+ before = mapping_path.read_bytes()
+
+ exit_code = incus_regression.cmd_reconcile(
+ argparse.Namespace(yes=yes, dry_run=dry_run, remote=None)
+ )
+
+ assert exit_code == 0
+ assert "gone port 52904" in capsys.readouterr().out
+ assert mapping_path.read_bytes() == before
+
+
+def test_reconcile_enumerates_through_a_real_listing_under_dry_run(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
+) -> None:
+ # `Runner.names` answers [] for a dry run by contract. If reconcile enumerated
+ # through a dry-run runner it would read every recorded environment as gone
+ # and offer to forget all of it, so it must build its own real runner.
+ seen = []
+
+ class RecordingRunner:
+ def __init__(self, *, dry_run=False):
+ seen.append(dry_run)
+ self.dry_run = dry_run
+
+ def names(self, command, *, what):
+ return ["avr-wt-kept"]
+
+ def records(self, command, *, what):
+ return [{"name": "avibe-wt-kept", "status": "Running", "project": "avr-wt-kept"}]
+
+ repo = tmp_path / "repo"
+ (repo / ".runtime" / "incus-regression").mkdir(parents=True)
+ (repo / ".runtime" / "incus-regression" / "worktrees.json").write_text(
+ json.dumps({"schema_version": 1, "worktrees": {}}), encoding="utf-8"
+ )
+ monkeypatch.setattr(incus_regression, "current_repo_root", lambda: repo)
+ monkeypatch.setattr(incus_regression, "git_common_root", lambda repo_root: repo_root)
+ monkeypatch.setattr(incus_regression, "require_incus", lambda: None)
+ monkeypatch.setattr(incus_regression, "Runner", RecordingRunner)
+
+ exit_code = incus_regression.cmd_reconcile(
+ argparse.Namespace(yes=False, dry_run=True, remote=None)
+ )
+
+ assert exit_code == 0
+ assert seen == [False]
+ assert "kept [project, Running]" in capsys.readouterr().out
+
+
+def test_reconcile_keeps_a_project_whose_instance_is_already_gone(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
+) -> None:
+ # Half a footprint is still a footprint. The project owns the slug and has to
+ # be reclaimed, and its row still holds the host port, so neither the listing
+ # nor the metadata may treat this as an environment Incus no longer has.
+ mapping_path, _ = reconcile_fixture(
+ tmp_path,
+ monkeypatch,
+ entries={"half": {"path": str(tmp_path / "checkout"), "host_port": 52905, "branch": "fix/half"}},
+ projects=("avr-wt-half",),
+ instances=(),
+ )
+
+ exit_code = incus_regression.cmd_reconcile(
+ argparse.Namespace(yes=True, dry_run=False, remote=None)
+ )
+ out = capsys.readouterr().out
+
+ assert exit_code == 0
+ assert "half [project, no instance]" in out
+ assert "delete --target worktree --slug half --yes" in out
+ payload = json.loads(mapping_path.read_text(encoding="utf-8"))
+ assert set(payload["worktrees"]) == {"half"}
+
+
+def test_reconcile_does_not_offer_to_delete_a_misplaced_instance_by_slug(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
+) -> None:
+ # `delete --slug` derives the project from the slug, so an instance living
+ # somewhere else is not reachable by it. Printing the command anyway promises
+ # a removal that would report success and leave the instance running.
+ mapping_path, _ = reconcile_fixture(
+ tmp_path,
+ monkeypatch,
+ entries={},
+ projects=(),
+ instances=({"name": "avibe-wt-misplaced", "status": "Running", "project": "default"},),
+ )
+
+ exit_code = incus_regression.cmd_reconcile(
+ argparse.Namespace(yes=True, dry_run=False, remote=None)
+ )
+ out = capsys.readouterr().out
+
+ assert exit_code == 0
+ assert "misplaced [no project, Running in default]" in out
+ assert "delete --target worktree --slug misplaced" not in out
+ assert "reclaim it by hand" in out
+ payload = json.loads(mapping_path.read_text(encoding="utf-8"))
+ assert payload["worktrees"] == {}
+
+
+def test_reconcile_reports_every_instance_sharing_one_name(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
+) -> None:
+ """Incus scopes instance names per project, so one name can be two instances.
+
+ A single observation slot keeps whichever the listing mentioned last. If that
+ is the convention-project one, the report offers a delete command and says
+ nothing about the instance it cannot reach -- the disk stays occupied by
+ something the operator was told had been enumerated.
+ """
+ mapping_path, _ = reconcile_fixture(
+ tmp_path,
+ monkeypatch,
+ entries={},
+ projects=("avr-wt-doubled",),
+ instances=(
+ {"name": "avibe-wt-doubled", "status": "Stopped", "project": "default"},
+ {"name": "avibe-wt-doubled", "status": "Running", "project": "avr-wt-doubled"},
+ ),
+ )
+
+ exit_code = incus_regression.cmd_reconcile(argparse.Namespace(yes=True, dry_run=False, remote=None))
+ out = capsys.readouterr().out
+
+ assert exit_code == 0
+ assert "doubled [project, Stopped in default, Running]" in out
+ # Both statements are true of this environment at once, so it earns both: the
+ # command that reclaims what the convention covers, and the warning about what
+ # it does not.
+ assert "delete --target worktree --slug doubled" in out
+ assert "instance lives in project default, not avr-wt-doubled" in out
+ payload = json.loads(mapping_path.read_text(encoding="utf-8"))
+ assert payload["worktrees"] == {}
+
+
+def test_reconcile_lists_names_the_runner_would_not_mint_and_offers_only_runnable_deletes(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
+) -> None:
+ """Every command the report prints is one the runner accepts, whatever Incus holds.
+
+ An environment the runner did not create had nothing constraining its name,
+ so the names below are ones Incus accepts and `--slug` does not. Deriving
+ those names from the slug a second time ran them back through the validating
+ minter, and `reconcile` raised before printing anything at all -- blinding the
+ one command whose purpose is finding environments nobody tracked.
+
+ The command assertion is a property over the whole report rather than a list
+ of rejected shapes: too short, too long, a trailing hyphen, and whatever else
+ Incus permits form an open set, and the member a list omits is the one that
+ ships. Parsing the commands back out of the output also covers report lines
+ that do not exist yet.
+ """
+ too_long = "l" * 41
+ mapping_path, _ = reconcile_fixture(
+ tmp_path,
+ monkeypatch,
+ entries={},
+ projects=("avr-wt-ab", f"avr-wt-{too_long}", "avr-wt-fine"),
+ instances=(
+ {"name": "avibe-wt-ab", "status": "Running"},
+ {"name": "avibe-wt-fine", "status": "Stopped"},
+ ),
+ )
+
+ exit_code = incus_regression.cmd_reconcile(argparse.Namespace(yes=True, dry_run=False, remote=None))
+ out = capsys.readouterr().out
+
+ assert exit_code == 0
+ # Reported at all, which is the regression: three environments exist and the
+ # command used to raise on the first one it could not have created.
+ assert "3 worktree regression environment(s)" in out
+ for slug in ("ab", too_long, "fine"):
+ assert f" {slug} [" in out
+
+ offered = []
+ for line in out.splitlines():
+ printed = line.strip()
+ if not printed.startswith("python3 scripts/incus_regression.py"):
+ continue
+ argv = shlex.split(printed)
+ if "--slug" in argv:
+ offered.append(argv[argv.index("--slug") + 1])
+ assert offered == ["fine"]
+ for slug in offered:
+ # Raises if the report offered a command `delete` would reject.
+ incus_regression.validate_slug(slug)
+
+ # What the runner cannot name, it names the objects for instead. A command
+ # that exits on its own argument is not a reclamation path.
+ assert " ab: not a slug this runner accepts" in out
+ assert "Reclaim by hand: avr-wt-ab, avr-wt-ab/avibe-wt-ab." in out
+ assert f"Reclaim by hand: avr-wt-{too_long}." in out
+ payload = json.loads(mapping_path.read_text(encoding="utf-8"))
+ assert payload["worktrees"] == {}
+
+
+def test_a_prune_keeps_a_row_exactly_while_a_run_holds_its_slug(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
+) -> None:
+ """A row survives a `--yes` prune exactly while its slug's lock is held.
+
+ `up` records the slug and its port before it creates the project and the
+ instance, so a row in that state has no footprint yet and never had one:
+ reading "no footprint" as "stale" releases a port a live `up` is about to
+ bind. What identifies such a row is not in the row. It is the update lock the
+ run holds from before it writes the row until the environment is built, which
+ the kernel drops however that run ends.
+
+ So every recorded shape is seeded against both answers, and only the lock is
+ allowed to move the outcome. Seeding rather than listing the exempt shapes is
+ the point: each rule that read the row was wrong about a shape its author had
+ not thought of. Comparing the two stamps was wrong for a re-reserved slug,
+ because `reserve` merges and the previous run's `updated_at` survives, so any
+ clock that put it after the new `reserved_at` read a live reservation as
+ finished. Requiring a claim was wrong for the reservation v3.0.12 writes,
+ which has no claim at all -- seeded here, since a released runner's rows are
+ a shipped shape this code has to live with.
+ """
+ shapes = {
+ "no stamps at all": {},
+ "reserved, never completed": {"reserved_at": "2026-08-20T05:32:29.994595+00:00"},
+ "reserved by a released runner": {
+ "reserved_at": "2026-08-20T05:32:29.994595+00:00",
+ "branch": "fix/built-by-v3-0-12",
+ },
+ "completed after reserving": {
+ "reserved_at": "2026-08-20T05:32:29.994595+00:00",
+ "updated_at": "2026-08-20T05:41:11.000000+00:00",
+ },
+ "completion older than the reservation over it": {
+ "reserved_at": "2026-08-20T05:41:11.000000+00:00",
+ "updated_at": "2026-08-20T05:32:29.994595+00:00",
+ },
+ "completion dated in the future": {
+ "reserved_at": "2026-08-20T05:32:29.994595+00:00",
+ "updated_at": "2099-01-01T00:00:00.000000+00:00",
+ },
+ "stamps nothing can parse": {"reserved_at": "yesterday", "updated_at": "soon"},
+ "completed, no reservation left": {"updated_at": "2026-08-20T05:41:11.000000+00:00"},
+ }
+
+ entries: dict[str, dict] = {}
+ building: set[str] = set()
+ port = 53000
+ for index, (_shape, recorded) in enumerate(sorted(shapes.items())):
+ for claimed in (True, False):
+ for locked in (True, False):
+ slug = f"{'busy' if locked else 'idle'}-{index}-{'claimed' if claimed else 'bare'}"
+ entries[slug] = {"path": str(tmp_path / "checkout"), "host_port": port, **recorded}
+ port += 1
+ if claimed:
+ entries[slug]["claim"] = f"claim-of-{slug}"
+ if locked:
+ building.add(slug)
+ assert len(entries) == 4 * len(shapes) and len(building) == 2 * len(shapes)
+
+ mapping_path, _ = reconcile_fixture(
+ tmp_path, monkeypatch, entries=entries, projects=(), instances=()
+ )
+
+ with contextlib.ExitStack() as stack:
+ for slug in sorted(building):
+ # Held from this process on purpose: `flock` belongs to the open file
+ # description, not the process, so the probe's own descriptor
+ # conflicts with these exactly as another run's would. A test that
+ # had to fork to hold a lock would be testing the fork.
+ lock_path = incus_regression.target_lock_path(
+ tmp_path / "repo", None, f"{incus_regression.WORKTREE_PROJECT_PREFIX}{slug}"
+ )
+ lock_path.parent.mkdir(parents=True, exist_ok=True)
+ handle = stack.enter_context(lock_path.open("w", encoding="utf-8"))
+ incus_regression.fcntl.flock(handle.fileno(), incus_regression.fcntl.LOCK_EX)
+ exit_code = incus_regression.cmd_reconcile(argparse.Namespace(yes=True, dry_run=False, remote=None))
+ out = capsys.readouterr().out
+ payload = json.loads(mapping_path.read_text(encoding="utf-8"))
+
+ assert exit_code == 0
+ assert set(payload["worktrees"]) == building
+ # And each row is reported under what happened to it, so a kept one is not
+ # silence and a dropped one is not a surprise. Read out of the report by
+ # section rather than asserted line by line: the sections are what the
+ # operator acts on, and every seeded row has to appear in exactly one.
+ reported: dict[str, set[str]] = {"kept": set(), "dropped": set()}
+ section = None
+ for line in out.splitlines():
+ if line.endswith("is still holding:"):
+ section = "kept"
+ elif line.endswith("no longer has:"):
+ section = "dropped"
+ elif not line.strip():
+ section = None
+ elif section and line.startswith(" "):
+ slug = line.strip().split()[0]
+ if slug in entries:
+ reported[section].add(slug)
+ assert reported == {"kept": building, "dropped": set(entries) - building}
+
+
+def test_a_slug_is_in_flight_whenever_the_kernel_cannot_say_it_is_free(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Only a lock this probe took itself answers "nobody holds this slug".
+
+ A missing lock file is the one real absence: nothing has ever locked that
+ slug. Reading it must not create it, or the absence would be spent by the act
+ of asking. Everything else -- a lock somebody holds, a file this user cannot
+ open, a platform with no `flock` -- is a question left unanswered, and those
+ answer "held" for the same reason every unanswered question in `reconcile`
+ keeps the row.
+ """
+ repo = tmp_path / "repo"
+ monkeypatch.setattr(incus_regression, "git_common_root", lambda repo_root: repo_root)
+ lock_path = incus_regression.target_lock_path(repo, None, "avr-wt-demo")
+
+ assert incus_regression.target_run_in_flight(repo, None, "avr-wt-demo") is False
+ assert not lock_path.exists()
+
+ lock_path.parent.mkdir(parents=True)
+ with lock_path.open("w", encoding="utf-8") as handle:
+ # An `up` that ended left its lock file behind; the file is not the claim.
+ assert incus_regression.target_run_in_flight(repo, None, "avr-wt-demo") is False
+ incus_regression.fcntl.flock(handle.fileno(), incus_regression.fcntl.LOCK_EX)
+ assert incus_regression.target_run_in_flight(repo, None, "avr-wt-demo") is True
+ assert incus_regression.target_run_in_flight(repo, None, "avr-wt-demo") is False
+
+ real_open = os.open
+
+ def refuse(path, flags, *rest):
+ if str(path) == str(lock_path):
+ raise PermissionError(13, "Permission denied")
+ return real_open(path, flags, *rest)
+
+ with monkeypatch.context() as unreadable:
+ unreadable.setattr(incus_regression.os, "open", refuse)
+ assert incus_regression.target_run_in_flight(repo, None, "avr-wt-demo") is True
+
+ monkeypatch.setattr(incus_regression, "fcntl", None)
+ assert incus_regression.target_run_in_flight(repo, None, "avr-wt-demo") is True
+
+
+def test_a_lock_answers_for_one_daemon_and_local_runs_keep_the_released_path(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """An environment is a daemon and a project -- for locks as much as for rows.
+
+ Project names are per-daemon and every remote has the same ones, so a lock
+ keyed on the project alone leaves a `--remote` run indistinguishable from a
+ local one holding that slug, and a local `reconcile` reads it as a reason to
+ keep a stale row and its port. Asserted over every ordered pair of
+ authorities rather than over the one crossing that was reported: a lock held
+ under one authority is never evidence under another, and a lock held under
+ the same one always is.
+
+ The local path is a cross-version contract on top of that. Every released
+ runner locks at `locks/<project>.lock`, and sharing that exact file is the
+ whole reason a lock can answer for a run this code did not start, so no
+ authority may be spelled into it.
+ """
+ repo = tmp_path / "repo"
+ monkeypatch.setattr(incus_regression, "git_common_root", lambda repo_root: repo_root)
+
+ assert incus_regression.target_lock_path(repo, None, "avr-wt-demo") == (
+ incus_regression.runtime_root(repo) / "locks" / "avr-wt-demo.lock"
+ )
+
+ authorities = (None, "lab", "other")
+ for holder in authorities:
+ # Held from this process: `flock` belongs to the open file description, so
+ # the probe's own descriptor conflicts exactly as another run's would.
+ with incus_regression.target_update_lock(repo, holder, "avr-wt-demo", dry_run=False):
+ for asker in authorities:
+ assert incus_regression.target_run_in_flight(repo, asker, "avr-wt-demo") is (
+ asker == holder
+ )
+
+
+def test_a_remote_that_is_not_one_name_cannot_leave_the_locks_directory(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """`--remote` is spelled into a daemon reference and into a lock filename.
+
+ Each holds exactly one name, so the invariant is about what survives the
+ parser rather than about which spellings are listed here: whatever it accepts
+ puts its lock inside the locks directory. Refused at the normalizer because
+ that is the one point both readers are downstream of, and refused as an
+ argparse error because `main` catches `RegressionError` only after the parser
+ has already run.
+ """
+ repo = tmp_path / "repo"
+ monkeypatch.setattr(incus_regression, "git_common_root", lambda repo_root: repo_root)
+ locks = incus_regression.runtime_root(repo) / "locks"
+
+ # Not vacuous: an ordinary name still gets through, whitespace and all.
+ assert incus_regression.normalized_remote(" lab ") == "lab"
+ assert incus_regression.normalized_remote(" ") is None
+
+ for value in ("lab", "lab-2", "lab.local", "a/b", "../evil", "a\\b", "lab:extra", ".", ".."):
+ try:
+ name = incus_regression.normalized_remote(value)
+ except argparse.ArgumentTypeError:
+ continue
+ assert incus_regression.target_lock_path(repo, name, "avr-wt-demo").parent == locks
+
+
+def test_reconcile_decides_under_the_mapping_lock_even_when_writing_nothing(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ # The listing, the classification and the write are one decision. A dry run
+ # still takes the real lock: every read it makes is real, and its report is
+ # what the next `--yes` acts on.
+ held = []
+ mapping_path, _ = reconcile_fixture(
+ tmp_path,
+ monkeypatch,
+ entries={"gone": {"path": str(tmp_path / "checkout"), "host_port": 52908}},
+ projects=(),
+ instances=(),
+ )
+
+ @contextlib.contextmanager
+ def recording_lock(repo_root, *, dry_run):
+ held.append(dry_run)
+ yield
+
+ monkeypatch.setattr(incus_regression, "worktree_mapping_lock", recording_lock)
+ incus_regression.cmd_reconcile(argparse.Namespace(yes=False, dry_run=True, remote=None))
+
+ assert held == [False]
+ assert set(json.loads(mapping_path.read_text(encoding="utf-8"))["worktrees"]) == {"gone"}
+
+
+def test_a_command_takes_the_mapping_lock_only_for_the_daemon_it_describes(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A lock on `worktrees.json` is a claim about one authority, like its rows.
+
+ The commands had learned that about the rows without learning it about the
+ lock. `reconcile --remote` held it across two listings of another daemon,
+ where this file exposes no rows and writes none, so a slow or unreachable
+ remote blocked every local `up` from reserving a port for as long as the
+ listing took -- protecting nothing, since nothing of this file's was in the
+ span. `up --remote` holds the same span for the same reason.
+
+ Asserted for both commands, in both authorities, and from inside the span
+ rather than at the call that opens it: what matters is whether the lock is
+ really held while the command is waiting on a daemon.
+ """
+ held: list[bool] = []
+ reconcile_fixture(tmp_path, monkeypatch, entries={}, projects=(), instances=())
+
+ def record_and_report_nothing(runner, metadata):
+ held.append(bool(incus_regression._held_mapping_locks))
+ return []
+
+ def record_and_stop(*call_args, **kwargs):
+ held.append(bool(incus_regression._held_mapping_locks))
+ raise RuntimeError("far enough")
+
+ monkeypatch.setattr(incus_regression, "worktree_environments", record_and_report_nothing)
+ monkeypatch.setattr(incus_regression, "load_env_file", lambda repo_root, env_file: None)
+ monkeypatch.setattr(incus_regression, "resolve_target", record_and_stop)
+
+ for remote in (None, "lab"):
+ incus_regression.cmd_reconcile(argparse.Namespace(yes=False, dry_run=False, remote=remote))
+ with pytest.raises(RuntimeError):
+ # `up` names its update lock from the arguments alone, so the stub
+ # carries the identity even though the mapping is never reached.
+ incus_regression.cmd_up(
+ argparse.Namespace(env_file=None, dry_run=False, remote=remote, target="worktree", slug="demo")
+ )
+
+ assert held == [True, True, False, False]
+
+
+def test_reconcile_against_a_remote_reports_one_authority(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
+) -> None:
+ """A report about one daemon annotates nothing from a file about another.
+
+ `worktrees.json` reserves ports on this machine and records what this
+ machine's daemon holds, so a remote inventory and these rows are two
+ authorities. Reading them into one report attributes a local row's port,
+ branch, and commit to whatever remote environment happens to share its slug,
+ and lists local-only rows as environments the remote has lost. So the rows
+ are absent from a remote report entirely -- said once, rather than implied by
+ every line reading "no runner metadata" -- and `--yes` has nothing to drop.
+
+ The `delete` commands it prints carry `--remote`, or they would name the same
+ slug on the wrong daemon.
+ """
+ mapping_path, _ = reconcile_fixture(
+ tmp_path,
+ monkeypatch,
+ entries={
+ # Same slug on both daemons: the case where lending provenance across
+ # authorities produces a plausible, wrong line rather than a visible
+ # mismatch.
+ "elsewhere": {"path": str(tmp_path / "checkout"), "host_port": 52909, "branch": "local/work"},
+ "local-only": {"path": str(tmp_path / "checkout"), "host_port": 52910},
+ },
+ projects=("avr-wt-elsewhere",),
+ instances=({"name": "avibe-wt-elsewhere", "status": "Running"},),
+ )
+
+ exit_code = incus_regression.cmd_reconcile(
+ argparse.Namespace(yes=True, dry_run=False, remote="lab")
+ )
+ out = capsys.readouterr().out
+
+ assert exit_code == 0
+ assert "--slug elsewhere --yes --remote lab" in out
+ assert "Runner metadata is not shown: it describes the local Incus daemon, not remote lab." in out
+ assert "52909" not in out
+ assert "local/work" not in out
+ assert "local-only" not in out
+ payload = json.loads(mapping_path.read_text(encoding="utf-8"))
+ assert set(payload["worktrees"]) == {"elsewhere", "local-only"}
+
+
+def test_delete_round_trips_generated_worktree_slug(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ runtime = repo / ".runtime" / "incus-regression"
+ runtime.mkdir(parents=True)
+ slug = "fix-regression-source-id-3200ccd6"
+ project = f"avr-wt-{slug}"
+ instance = f"avibe-wt-{slug}"
+ mapping_path = runtime / "worktrees.json"
+ mapping_path.write_text(
+ json.dumps(
+ {
+ "schema_version": 1,
+ "worktrees": {
+ slug: {
+ "path": str(tmp_path / "missing"),
+ "project": project,
+ "instance": instance,
+ "host_port": 15205,
+ }
+ },
+ }
+ ),
+ encoding="utf-8",
+ )
+ commands = []
+
+ class RecordingRunner:
+ def __init__(self, *, dry_run=False):
+ self.dry_run = dry_run
+
+ def run(self, command, *, check=True, **kwargs):
+ commands.append(command)
+ return subprocess.CompletedProcess(command, 0)
+
+ monkeypatch.setattr(incus_regression, "current_repo_root", lambda: repo)
+ monkeypatch.setattr(incus_regression, "git_common_root", lambda _repo_root: repo)
+ monkeypatch.setattr(incus_regression, "load_env_file", lambda _repo_root, _env_file: None)
+ monkeypatch.setattr(incus_regression, "require_incus", lambda: None)
+ monkeypatch.setattr(incus_regression, "Runner", RecordingRunner)
+
+ exit_code = incus_regression.cmd_delete(
+ argparse.Namespace(
+ target="worktree",
+ slug=slug,
+ env_file=None,
+ host_port=None,
+ ui_host="127.0.0.1",
+ ui_port=5123,
+ worktree_port_start=15200,
+ worktree_port_end=15399,
+ dry_run=False,
+ remote=None,
+ yes=True,
+ )
+ )
+
+ assert exit_code == 0
+ assert commands == [
+ ["incus", "--project", project, "delete", instance, "--force"],
+ ["incus", "project", "delete", project],
+ ]
+ payload = json.loads(mapping_path.read_text(encoding="utf-8"))
+ assert payload["worktrees"] == {}
+
+
+def test_delete_against_a_remote_keeps_the_local_metadata(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
+) -> None:
+ """A removal somewhere else is no evidence about the row describing this machine.
+
+ `worktrees.json` reserves host ports here and records what this machine's
+ daemon holds. The same slug can be in use on both daemons, so dropping the
+ local row because the remote copy was deleted releases a port a live local
+ environment is bound to.
+ """
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ runtime = repo / ".runtime" / "incus-regression"
+ runtime.mkdir(parents=True)
+ slug = "shared-slug"
+ row = {"path": str(repo), "project": f"avr-wt-{slug}", "instance": f"avibe-wt-{slug}", "host_port": 15207}
+ mapping_path = runtime / "worktrees.json"
+ mapping_path.write_text(json.dumps({"schema_version": 1, "worktrees": {slug: row}}), encoding="utf-8")
+
+ class RecordingRunner:
+ def __init__(self, *, dry_run=False):
+ self.dry_run = dry_run
+
+ def run(self, command, *, check=True, **kwargs):
+ return subprocess.CompletedProcess(command, 0)
+
+ monkeypatch.setattr(incus_regression, "current_repo_root", lambda: repo)
+ monkeypatch.setattr(incus_regression, "git_common_root", lambda _repo_root: repo)
+ monkeypatch.setattr(incus_regression, "load_env_file", lambda _repo_root, _env_file: None)
+ monkeypatch.setattr(incus_regression, "require_incus", lambda: None)
+ monkeypatch.setattr(incus_regression, "Runner", RecordingRunner)
+
+ exit_code = incus_regression.cmd_delete(
+ argparse.Namespace(
+ target="worktree",
+ slug=slug,
+ env_file=None,
+ host_port=None,
+ ui_host="127.0.0.1",
+ ui_port=5123,
+ worktree_port_start=15200,
+ worktree_port_end=15399,
+ dry_run=False,
+ remote="lab",
+ yes=True,
+ )
+ )
+
+ assert exit_code == 0
+ assert "Kept the local metadata" in capsys.readouterr().out
+ payload = json.loads(mapping_path.read_text(encoding="utf-8"))
+ assert payload["worktrees"] == {slug: row}
+
+
+def _delete_args(slug: str, **overrides) -> argparse.Namespace:
+ fields = {
+ "target": "worktree",
+ "slug": slug,
+ "env_file": None,
+ "host_port": None,
+ "ui_host": "127.0.0.1",
+ "ui_port": 5123,
+ "worktree_port_start": 15200,
+ "worktree_port_end": 15399,
+ "dry_run": False,
+ "remote": None,
+ "yes": True,
+ }
+ fields.update(overrides)
+ return argparse.Namespace(**fields)
+
+
+def test_deleting_a_slug_another_run_holds_changes_nothing(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A live run owns its slug, so a delete of it stops instead of taking half of it.
+
+ The half is what makes this worth refusing rather than racing. An `up`
+ reserves under this lock and builds for minutes inside it, so a delete
+ arriving in that window finds no objects to remove and would remove the row
+ anyway -- and `complete` will not restore a row that is no longer the one its
+ run reserved, so the environment would finish built, untracked, with its host
+ port free for the next slug to take.
+ """
+ repo = tmp_path / "repo"
+ (repo / ".runtime" / "incus-regression").mkdir(parents=True)
+ slug = "held-by-someone-else"
+ row = {"path": str(repo), "project": f"avr-wt-{slug}", "instance": f"avibe-wt-{slug}", "host_port": 15211}
+ mapping_path = repo / ".runtime" / "incus-regression" / "worktrees.json"
+ mapping_path.write_text(json.dumps({"schema_version": 1, "worktrees": {slug: row}}), encoding="utf-8")
+ commands = []
+
+ class RecordingRunner:
+ def __init__(self, *, dry_run=False):
+ self.dry_run = dry_run
+
+ def run(self, command, *, check=True, **kwargs):
+ commands.append(command)
+ return subprocess.CompletedProcess(command, 0)
+
+ monkeypatch.setattr(incus_regression, "current_repo_root", lambda: repo)
+ monkeypatch.setattr(incus_regression, "git_common_root", lambda _repo_root: repo)
+ monkeypatch.setattr(incus_regression, "load_env_file", lambda _repo_root, _env_file: None)
+ monkeypatch.setattr(incus_regression, "require_incus", lambda: None)
+ monkeypatch.setattr(incus_regression, "Runner", RecordingRunner)
+
+ with incus_regression.target_update_lock(repo, None, f"avr-wt-{slug}", dry_run=False):
+ with pytest.raises(incus_regression.RegressionError) as excinfo:
+ incus_regression.cmd_delete(_delete_args(slug))
+
+ assert "Another run holds the regression update lock" in str(excinfo.value)
+ assert commands == []
+ payload = json.loads(mapping_path.read_text(encoding="utf-8"))
+ assert payload["worktrees"] == {slug: row}
+
+
+def test_delete_holds_the_slug_lock_across_the_objects_and_the_row(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Stated as "the lock is held while each half changes", not as where the `with` sits.
+
+ Both halves are one change to what the slug names, so an interruption between
+ them is what has to be impossible -- an environment removed with its row kept
+ strands a port, and a row removed with the environment kept hides one. The
+ probe is the same one `reconcile` uses, which cannot be satisfied by holding
+ the lock somewhere nearby: `flock` conflicts with this process too, so it
+ answers for the moment it is asked.
+ """
+ repo = tmp_path / "repo"
+ (repo / ".runtime" / "incus-regression").mkdir(parents=True)
+ slug = "deleted-under-lock"
+ project = f"avr-wt-{slug}"
+ row = {"path": str(repo), "project": project, "instance": f"avibe-wt-{slug}", "host_port": 15212}
+ mapping_path = repo / ".runtime" / "incus-regression" / "worktrees.json"
+ mapping_path.write_text(json.dumps({"schema_version": 1, "worktrees": {slug: row}}), encoding="utf-8")
+ observed = []
+
+ def held() -> bool:
+ return incus_regression.target_run_in_flight(repo, None, project)
+
+ class ProbingRunner:
+ def __init__(self, *, dry_run=False):
+ self.dry_run = dry_run
+
+ def run(self, command, *, check=True, **kwargs):
+ observed.append(("objects", held()))
+ return subprocess.CompletedProcess(command, 0)
+
+ forget = incus_regression.WorktreeMetadata.forget
+
+ def probing_forget(self, slugs):
+ observed.append(("row", held()))
+ return forget(self, slugs)
+
+ monkeypatch.setattr(incus_regression, "current_repo_root", lambda: repo)
+ monkeypatch.setattr(incus_regression, "git_common_root", lambda _repo_root: repo)
+ monkeypatch.setattr(incus_regression, "load_env_file", lambda _repo_root, _env_file: None)
+ monkeypatch.setattr(incus_regression, "require_incus", lambda: None)
+ monkeypatch.setattr(incus_regression, "Runner", ProbingRunner)
+ monkeypatch.setattr(incus_regression.WorktreeMetadata, "forget", probing_forget)
+
+ assert incus_regression.cmd_delete(_delete_args(slug)) == 0
+
+ assert observed == [("objects", True), ("objects", True), ("row", True)]
+ # Not vacuous: the same probe is False once the command has released it.
+ assert held() is False
+ payload = json.loads(mapping_path.read_text(encoding="utf-8"))
+ assert payload["worktrees"] == {}
+
+
+def test_metadata_about_another_daemon_neither_reads_nor_writes_the_local_file(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Every accessor is bound to the daemon it describes, so `--remote` reaches nothing.
+
+ Stated over the accessor rather than over the commands that use it. A
+ predicate each command was expected to consult came first, and being a
+ question is what made it forgettable: `up --remote` never asked, and so it
+ reserved a host port on this machine, overwrote whatever live local row shared
+ its slug, and left that reservation behind for good. Asserting it here covers
+ every present and future caller, because the file has no other way in.
+ """
+ repo = tmp_path / "repo"
+ runtime = repo / ".runtime" / "incus-regression"
+ runtime.mkdir(parents=True)
+ mapping_path = runtime / "worktrees.json"
+ recorded = {
+ "schema_version": 1,
+ "worktrees": {"demo": {"host_port": 15234, "branch": "local/work", "claim": "seeded"}},
+ }
+ mapping_path.write_text(json.dumps(recorded), encoding="utf-8")
+ monkeypatch.setattr(incus_regression, "git_common_root", lambda _repo_root: repo)
+ before = mapping_path.read_bytes()
+
+ metadata = incus_regression.WorktreeMetadata(repo, "lab")
+ target = incus_regression.RegressionTarget(
+ target="worktree",
+ slug="demo",
+ project="avr-wt-demo",
+ instance="avibe-wt-demo",
+ host_port=15234,
+ ui_host="127.0.0.1",
+ ui_port=5123,
+ )
+
+ assert metadata.owned is False
+ assert metadata.rows() == {}
+ assert metadata.allocated_ports() == set()
+ assert metadata.port_for("demo") is None
+
+ # The seeded row carries the claim these writes name, so each of them would
+ # land if authority were ignored -- the file is unchanged because of who the
+ # accessor is bound to, not because the writes had nothing to match.
+ metadata.reserve(target)
+ metadata.complete(target, "seeded")
+ metadata.release(target, "seeded")
+ metadata.forget(["demo"])
+ metadata.mutate(lambda worktrees: worktrees.clear())
+
+ assert mapping_path.read_bytes() == before
+
+ # The mirror: the same calls through the owning accessor do reach the file,
+ # so the reads and writes above are scoped by authority rather than broken.
+ owner = incus_regression.WorktreeMetadata(repo)
+ assert owner.port_for("demo") == 15234
+ owner.forget(["demo"])
+ assert json.loads(mapping_path.read_text(encoding="utf-8"))["worktrees"] == {}
+
+
+def test_the_mapping_file_has_exactly_one_way_in() -> None:
+ """`worktrees.json` is reachable only through the accessor bound to its daemon.
+
+ The enumeration is asserted rather than described, so a sixth access point
+ added outside the owner fails here instead of costing a review round. This is
+ the whole reason the authority check cannot be forgotten: a caller has no name
+ for the file, only for an accessor that already knows which daemon it is
+ evidence about.
+ """
+ import ast
+
+ tree = ast.parse(SCRIPT_PATH.read_text(encoding="utf-8"))
+ owner = next(
+ node
+ for node in tree.body
+ if isinstance(node, ast.ClassDef) and node.name == "WorktreeMetadata"
+ )
+ inside = {id(node) for node in ast.walk(owner)}
+ readers = {"_load_worktree_mapping", "_write_worktree_mapping"}
+ strays = sorted(
+ {
+ node.id
+ for node in ast.walk(tree)
+ if isinstance(node, ast.Name) and node.id in readers and id(node) not in inside
+ }
+ )
+
+ assert strays == [], f"reached outside WorktreeMetadata: {strays}"
+
+
+def test_the_mapping_lock_nests_without_deadlocking(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ """`flock` is owned by an open file description, not by a process.
+
+ A writer that takes the lock itself is nested inside every command that
+ already holds it across a decision, so a second `open` plus `flock` would
+ block forever on a lock this very process holds -- and a deadlocked runner
+ looks like a hung daemon, not like a bug here.
+ """
+ repo = tmp_path / "repo"
+ (repo / ".runtime" / "incus-regression").mkdir(parents=True)
+ monkeypatch.setattr(incus_regression, "git_common_root", lambda _repo_root: repo)
+ written = []
+
+ with incus_regression.worktree_mapping_lock(repo, dry_run=False):
+ incus_regression.WorktreeMetadata(repo).mutate(lambda worktrees: worktrees.update({"nested": {"host_port": 1}}))
+ written.append(json.loads((repo / ".runtime" / "incus-regression" / "worktrees.json").read_text(encoding="utf-8")))
+
+ assert written == [{"schema_version": 1, "worktrees": {"nested": {"host_port": 1}}}]
+ # The outer span released the lock on the way out, so the next acquisition is
+ # a real one rather than a leaked no-op.
+ with incus_regression.worktree_mapping_lock(repo, dry_run=False):
+ pass
+
+
+def test_up_skips_host_port_preflight_for_existing_instance(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ write_ui_builder_stage(tmp_path)
+ (tmp_path / "pyproject.toml").write_text("[project]\nname='x'\n", encoding="utf-8")
+ (tmp_path / "uv.lock").write_text("", encoding="utf-8")
+ (tmp_path / "ui").mkdir()
+ (tmp_path / "ui" / "package.json").write_text("{}", encoding="utf-8")
(tmp_path / "ui" / "package-lock.json").write_text("{}", encoding="utf-8")
(tmp_path / "ui" / "src").mkdir()
@@ -1537,7 +2709,7 @@ def test_up_skips_host_port_preflight_for_existing_instance(tmp_path: Path, monk
monkeypatch.setattr(incus_regression, "write_metadata", lambda *args, **kwargs: None)
monkeypatch.setattr(incus_regression, "restart_and_verify", lambda *args, **kwargs: None)
monkeypatch.setattr(incus_regression, "prepare_show_runtime", lambda *args, **kwargs: None)
- monkeypatch.setattr(incus_regression, "update_worktree_mapping", lambda *args, **kwargs: None)
+ monkeypatch.setattr(incus_regression.WorktreeMetadata, "complete", lambda *args, **kwargs: None)
args = argparse.Namespace(
target="master",
@@ -1596,7 +2768,6 @@ def test_up_defers_master_port_preflight_until_after_instance_exists(
"ensure_host_port_available",
lambda host, port: (_ for _ in ()).throw(AssertionError("should not preflight existing master instance")),
)
- monkeypatch.setattr(incus_regression, "reserve_worktree_mapping", lambda *args, **kwargs: None)
monkeypatch.setattr(incus_regression, "ensure_project_and_instance", lambda *args, **kwargs: None)
monkeypatch.setattr(incus_regression, "stop_service_for_update", lambda *args, **kwargs: None)
monkeypatch.setattr(incus_regression, "write_runtime_env", lambda *args, **kwargs: None)
@@ -1607,7 +2778,7 @@ def test_up_defers_master_port_preflight_until_after_instance_exists(
monkeypatch.setattr(incus_regression, "write_metadata", lambda *args, **kwargs: None)
monkeypatch.setattr(incus_regression, "restart_and_verify", lambda *args, **kwargs: None)
monkeypatch.setattr(incus_regression, "prepare_show_runtime", lambda *args, **kwargs: None)
- monkeypatch.setattr(incus_regression, "update_worktree_mapping", lambda *args, **kwargs: None)
+ monkeypatch.setattr(incus_regression.WorktreeMetadata, "complete", lambda *args, **kwargs: None)
args = argparse.Namespace(
target="master",
@@ -1666,7 +2837,7 @@ def test_up_checks_host_port_preflight_for_new_local_instance(tmp_path: Path, mo
monkeypatch.setattr(incus_regression, "write_metadata", lambda *args, **kwargs: None)
monkeypatch.setattr(incus_regression, "restart_and_verify", lambda *args, **kwargs: None)
monkeypatch.setattr(incus_regression, "prepare_show_runtime", lambda *args, **kwargs: None)
- monkeypatch.setattr(incus_regression, "update_worktree_mapping", lambda *args, **kwargs: None)
+ monkeypatch.setattr(incus_regression.WorktreeMetadata, "complete", lambda *args, **kwargs: None)
args = argparse.Namespace(
target="master",
@@ -1983,7 +3154,7 @@ def test_up_dry_run_does_not_require_seed_env(tmp_path: Path, monkeypatch: pytes
monkeypatch.setattr(incus_regression, "write_metadata", record("write_metadata"))
monkeypatch.setattr(incus_regression, "restart_and_verify", record("restart_and_verify"))
monkeypatch.setattr(incus_regression, "prepare_show_runtime", record("prepare_show_runtime"))
- monkeypatch.setattr(incus_regression, "update_worktree_mapping", record("update_worktree_mapping"))
+ monkeypatch.setattr(incus_regression.WorktreeMetadata, "complete", record("complete_worktree_metadata"))
args = argparse.Namespace(
target="master",
@@ -2054,7 +3225,7 @@ def test_up_stops_old_service_before_mutating_runtime(tmp_path: Path, monkeypatc
monkeypatch.setattr(incus_regression, "write_metadata", record("write_metadata"))
monkeypatch.setattr(incus_regression, "restart_and_verify", record("restart_and_verify"))
monkeypatch.setattr(incus_regression, "prepare_show_runtime", record("prepare_show_runtime"))
- monkeypatch.setattr(incus_regression, "update_worktree_mapping", record("update_worktree_mapping"))
+ monkeypatch.setattr(incus_regression.WorktreeMetadata, "complete", record("complete_worktree_metadata"))
args = argparse.Namespace(
target="master",
@@ -2132,7 +3303,7 @@ def test_up_preserves_runtime_env_when_existing_target_has_no_env_file(tmp_path:
monkeypatch.setattr(incus_regression, "write_metadata", record("write_metadata"))
monkeypatch.setattr(incus_regression, "restart_and_verify", record("restart_and_verify"))
monkeypatch.setattr(incus_regression, "prepare_show_runtime", record("prepare_show_runtime"))
- monkeypatch.setattr(incus_regression, "update_worktree_mapping", record("update_worktree_mapping"))
+ monkeypatch.setattr(incus_regression.WorktreeMetadata, "complete", record("complete_worktree_metadata"))
args = argparse.Namespace(
target="master",
@@ -2202,7 +3373,7 @@ def test_up_rewrites_runtime_env_when_env_file_is_loaded(tmp_path: Path, monkeyp
monkeypatch.setattr(incus_regression, "write_metadata", record("write_metadata"))
monkeypatch.setattr(incus_regression, "restart_and_verify", record("restart_and_verify"))
monkeypatch.setattr(incus_regression, "prepare_show_runtime", record("prepare_show_runtime"))
- monkeypatch.setattr(incus_regression, "update_worktree_mapping", record("update_worktree_mapping"))
+ monkeypatch.setattr(incus_regression.WorktreeMetadata, "complete", record("complete_worktree_metadata"))
args = argparse.Namespace(
target="master",
@@ -2233,8 +3404,22 @@ def test_up_rewrites_runtime_env_when_env_file_is_loaded(tmp_path: Path, monkeyp
assert "write_runtime_env" in calls
-def test_up_reserves_worktree_port_under_mapping_lock(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+def test_up_reserves_worktree_port_under_both_locks_that_protect_it(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ """Every row `up` writes is written under the mapping lock and its slug's lock.
+
+ Two locks, two properties. The mapping lock makes a read-modify-write of
+ `worktrees.json` atomic. The slug's update lock is what tells `reconcile` this
+ run exists at all, so a row written outside it is a row a concurrent
+ `reconcile --yes` may prune while this run is still building against it -- and
+ a second `up` on the same slug could merge its own port over this one's before
+ either had finished. Recording the depth each write saw states that as one
+ property over all writers, rather than naming the two that exist today.
+ """
calls = []
+ held = []
+ building = []
+ locked = []
+ writes = []
class ExistingRunner:
def __init__(self, *, dry_run=False):
@@ -2249,18 +3434,33 @@ def test_up_reserves_worktree_port_under_mapping_lock(tmp_path: Path, monkeypatc
class Lock:
def __enter__(self):
calls.append("mapping_lock_enter")
+ held.append("lock")
def __exit__(self, exc_type, exc, tb):
+ held.pop()
calls.append("mapping_lock_exit")
return Lock()
- def target_lock(repo_root, target, *, dry_run):
+ # Records the depth every write sees rather than naming the writers, so a
+ # write added later is covered without editing this test.
+ original_write = incus_regression._write_worktree_mapping
+
+ def recording_write(repo_root, payload):
+ writes.append((len(held), len(building)))
+ original_write(repo_root, payload)
+
+ monkeypatch.setattr(incus_regression, "_write_worktree_mapping", recording_write)
+
+ def target_lock(repo_root, remote, project, *, dry_run):
class Lock:
def __enter__(self):
calls.append("target_lock_enter")
+ locked.append(project)
+ building.append(project)
def __exit__(self, exc_type, exc, tb):
+ building.pop()
calls.append("target_lock_exit")
return Lock()
@@ -2283,14 +3483,14 @@ def test_up_reserves_worktree_port_under_mapping_lock(tmp_path: Path, monkeypatc
# be free on the machine running it.
monkeypatch.setattr(incus_regression, "ensure_host_port_available", lambda host, port: None)
monkeypatch.setattr(incus_regression, "worktree_mapping_lock", mapping_lock)
- original_reserve_worktree_mapping = incus_regression.reserve_worktree_mapping
+ original_reserve = incus_regression.WorktreeMetadata.reserve
- def reserve_worktree_mapping(repo_root, target):
- calls.append("reserve_worktree_mapping")
- original_reserve_worktree_mapping(repo_root, target)
+ def reserve(self, target, **kwargs):
+ calls.append("reserve_worktree_metadata")
+ return original_reserve(self, target, **kwargs)
monkeypatch.setattr(incus_regression, "target_update_lock", target_lock)
- monkeypatch.setattr(incus_regression, "reserve_worktree_mapping", reserve_worktree_mapping)
+ monkeypatch.setattr(incus_regression.WorktreeMetadata, "reserve", reserve)
monkeypatch.setattr(incus_regression, "ensure_project_and_instance", record("ensure_project_and_instance"))
monkeypatch.setattr(incus_regression, "stop_service_for_update", record("stop_service_for_update"))
monkeypatch.setattr(incus_regression, "should_seed_state", lambda *args, **kwargs: False)
@@ -2332,12 +3532,421 @@ def test_up_reserves_worktree_port_under_mapping_lock(tmp_path: Path, monkeypatc
assert incus_regression.cmd_up(args) == 0
- assert calls[:4] == ["mapping_lock_enter", "reserve_worktree_mapping", "mapping_lock_exit", "target_lock_enter"]
+ assert calls[:3] == ["target_lock_enter", "mapping_lock_enter", "reserve_worktree_metadata"]
+ # The reservation and the completion stamp are two writes, and `up` releases
+ # the mapping lock between them, so the mapping's own writer has to take it.
+ # Both depths are asserted for every write: whoever performs it, no write to
+ # `worktrees.json` happens outside the mapping lock, and none happens outside
+ # the lock that proves this run is the one holding the slug.
+ assert len(writes) == 2
+ assert all(mapping_depth >= 1 and slug_depth >= 1 for mapping_depth, slug_depth in writes)
payload = json.loads((tmp_path / ".runtime" / "incus-regression" / "worktrees.json").read_text(encoding="utf-8"))
mapping = payload["worktrees"]["demo-branch"]
assert mapping["host_port"] == 15200
assert mapping["project"] == "avr-wt-demo-branch"
assert "updated_at" in mapping
+ # The lock is named before the row exists, so it is asserted against the row:
+ # a lock on any other name would be held while a different environment built.
+ assert locked == [mapping["project"]]
+
+
[email protected]("holds_project", [False, True], ids=["daemon-empty", "daemon-holds-project"])
[email protected]("recorded", [False, True], ids=["new-row", "existing-row"])
+ "fail_at",
+ ["require_runtime_seed_env", "ensure_project_and_instance", "sync_source"],
+)
+def test_up_gives_its_row_back_only_when_the_daemon_says_nothing_came_of_it(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, fail_at: str, recorded: bool, holds_project: bool
+) -> None:
+ """A failed `up` drops its row exactly when the daemon holds no project for it.
+
+ The expectation is derived from what the daemon reports, not from a table of
+ steps, because that is the whole rule: releasing is safe while nothing binds
+ this port, and only the daemon knows. Asserting the step instead would be
+ asserting a prediction -- a run that fails inside
+ `ensure_project_and_instance` may have created the project or may have
+ failed on the listing that decides whether to, and those are opposite
+ answers from one step.
+
+ The row's own age is on the same assertion for the same reason. It used to
+ decide the outcome, on the theory that a pre-existing row is a claim older
+ than the run -- but "older" was standing in for "something exists", and here
+ those come apart: a row whose environment was deleted behind the runner's
+ back is not a claim about anything, while a project the daemon holds must
+ keep its port whether this run recorded it or not.
+
+ Left behind, an abandoned reservation reads as one still in flight, which
+ `reconcile` refuses to prune by design, so its port stayed reserved until
+ someone deleted the slug by hand.
+ """
+ calls = []
+ inventory = ("avr-wt-demo-branch",) if holds_project else ()
+
+ class NewRunner:
+ def __init__(self, *, dry_run=False):
+ self.dry_run = dry_run
+
+ names = daemon_listing(*inventory)
+
+ def run(self, command, **kwargs):
+ return subprocess.CompletedProcess(command, 0, stdout="{}")
+
+ def record(name):
+ def wrapper(*args, **kwargs):
+ calls.append(name)
+ if name == fail_at:
+ raise RuntimeError(f"{name} failed")
+ if name == "update_dependencies_and_build":
+ return set()
+
+ return wrapper
+
+ mapping_path = tmp_path / ".runtime" / "incus-regression" / "worktrees.json"
+ if recorded:
+ mapping_path.parent.mkdir(parents=True)
+ mapping_path.write_text(
+ json.dumps(
+ {
+ "schema_version": 1,
+ "worktrees": {
+ "demo-branch": {
+ "path": str(tmp_path),
+ "project": "avr-wt-demo-branch",
+ "instance": "avibe-wt-demo-branch",
+ "host_port": 15200,
+ "updated_at": "2026-08-01T00:00:00+00:00",
+ }
+ },
+ }
+ ),
+ encoding="utf-8",
+ )
+
+ monkeypatch.setattr(incus_regression, "current_repo_root", lambda: tmp_path)
+ monkeypatch.setattr(incus_regression, "git_common_root", lambda repo_root: repo_root)
+ monkeypatch.setattr(incus_regression, "load_env_file", lambda repo_root, env_file: None)
+ monkeypatch.setattr(incus_regression, "require_incus", lambda: None)
+ monkeypatch.setattr(incus_regression, "ensure_host_port_available", lambda host, port: None)
+ monkeypatch.setattr(incus_regression, "Runner", NewRunner)
+ monkeypatch.setattr(incus_regression, "should_seed_state", lambda *args, **kwargs: False)
+ monkeypatch.setattr(incus_regression, "compute_fingerprints", lambda repo_root: {})
+ monkeypatch.setattr(incus_regression, "read_existing_fingerprints", lambda *args, **kwargs: {})
+ for name in (
+ "require_runtime_seed_env",
+ "guard_paired_master_reset",
+ "ensure_project_and_instance",
+ "stop_service_for_update",
+ "write_runtime_env",
+ "migrate_legacy_backend_runtimes",
+ "sync_source",
+ "invalidate_fingerprints",
+ "update_dependencies_and_build",
+ "run_prepare_state",
+ "normalize_runtime_config",
+ "write_metadata",
+ "prepare_show_runtime",
+ "restart_and_verify",
+ ):
+ monkeypatch.setattr(incus_regression, name, record(name))
+
+ args = argparse.Namespace(
+ target="worktree",
+ slug="demo-branch",
+ host_port=None,
+ ui_host="127.0.0.1",
+ ui_port=5123,
+ worktree_port_start=15200,
+ worktree_port_end=15399,
+ env_file=None,
+ dry_run=False,
+ image="avibe-regression-base-current",
+ storage_pool="default",
+ network="incusbr0",
+ cpus="2",
+ memory="4GiB",
+ disk="20GiB",
+ processes="4096",
+ remote=None,
+ clean=False,
+ force_deps=False,
+ no_build_ui=True,
+ force_ui=False,
+ reset_mode="none",
+ )
+
+ with pytest.raises(RuntimeError):
+ incus_regression.cmd_up(args)
+
+ assert fail_at in calls
+ mapping = json.loads(mapping_path.read_text(encoding="utf-8"))["worktrees"]
+ assert ("demo-branch" in mapping) == holds_project
+ if holds_project:
+ # A project the daemon holds keeps its port, and `--host-port`-free
+ # reuse of a recorded one is the reason the row exists at all.
+ assert mapping["demo-branch"]["host_port"] == 15200
+
+
+def test_up_leaves_behind_a_row_another_run_has_taken_over(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A failing `up` must not release a row a concurrent `up` now owns.
+
+ `reserve` merges over whatever row it finds, so two `up` commands on one slug
+ are ordered by the mapping lock and not excluded by it: the second takes the
+ row while the first is still between its reserve and its failure. Everything
+ else here says release -- the daemon reports nothing, so nothing binds the
+ port, and the first run is the one that brought the row into existence. Only
+ the claim recorded in the row says otherwise, which is why it is the row and
+ not the run that gets asked.
+ """
+ claims = []
+
+ class NewRunner:
+ def __init__(self, *, dry_run=False):
+ self.dry_run = dry_run
+
+ names = daemon_listing()
+
+ def run(self, command, **kwargs):
+ return subprocess.CompletedProcess(command, 0, stdout="{}")
+
+ def take_over(*call_args, **kwargs):
+ other = incus_regression.resolve_target(args, tmp_path, dry_run=False)
+ claims.append(incus_regression.WorktreeMetadata(tmp_path, None).reserve(other).claim)
+ raise RuntimeError("taken over")
+
+ monkeypatch.setattr(incus_regression, "current_repo_root", lambda: tmp_path)
+ monkeypatch.setattr(incus_regression, "git_common_root", lambda repo_root: repo_root)
+ monkeypatch.setattr(incus_regression, "load_env_file", lambda repo_root, env_file: None)
+ monkeypatch.setattr(incus_regression, "require_incus", lambda: None)
+ monkeypatch.setattr(incus_regression, "ensure_host_port_available", lambda host, port: None)
+ monkeypatch.setattr(incus_regression, "Runner", NewRunner)
+ monkeypatch.setattr(incus_regression, "require_runtime_seed_env", take_over)
+
+ args = argparse.Namespace(
+ target="worktree",
+ slug="demo-branch",
+ host_port=None,
+ ui_host="127.0.0.1",
+ ui_port=5123,
+ worktree_port_start=15200,
+ worktree_port_end=15399,
+ env_file=None,
+ dry_run=False,
+ image="avibe-regression-base-current",
+ storage_pool="default",
+ network="incusbr0",
+ cpus="2",
+ memory="4GiB",
+ disk="20GiB",
+ processes="4096",
+ remote=None,
+ clean=False,
+ force_deps=False,
+ no_build_ui=True,
+ force_ui=False,
+ reset_mode="none",
+ )
+
+ with pytest.raises(RuntimeError):
+ incus_regression.cmd_up(args)
+
+ mapping = json.loads(
+ (tmp_path / ".runtime" / "incus-regression" / "worktrees.json").read_text(encoding="utf-8")
+ )["worktrees"]
+ assert mapping["demo-branch"]["claim"] == claims[0]
+ assert mapping["demo-branch"]["host_port"] == 15200
+
+
+def test_no_end_of_a_reservation_writes_over_a_row_another_run_took(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Every write a reservation performs stops at a row that is not its own.
+
+ Enumerated from the class rather than listed, because listing is how this got
+ in: the comparison was added to the release while completion kept writing
+ unconditionally, so an `up` that finished first replaced a newer run's row --
+ and with it that run's port and its claim, leaving the port allocated to a
+ row that no longer records it. A write added to the class later is covered
+ here without editing this test, and one needing an argument this test cannot
+ supply fails it instead of being skipped in silence.
+ """
+ import inspect
+
+ monkeypatch.setattr(incus_regression, "git_common_root", lambda repo_root: repo_root)
+ mapping_path = tmp_path / ".runtime" / "incus-regression" / "worktrees.json"
+ mapping_path.parent.mkdir(parents=True)
+
+ def target_on(port: int) -> incus_regression.RegressionTarget:
+ return incus_regression.RegressionTarget(
+ target="worktree",
+ slug="demo",
+ project="avr-wt-demo",
+ instance="avibe-wt-demo",
+ host_port=port,
+ ui_host="127.0.0.1",
+ ui_port=5123,
+ )
+
+ class NewRunner:
+ # The daemon holds nothing, so nothing but the claim can stop a write.
+ def __init__(self, *, dry_run=False):
+ self.dry_run = dry_run
+
+ names = daemon_listing()
+
+ mine = incus_regression.WorktreeMetadata(tmp_path, None).reserve(target_on(15200))
+ theirs = incus_regression.WorktreeMetadata(tmp_path, None).reserve(target_on(15201))
+ assert mine.claim and theirs.claim and mine.claim != theirs.claim
+
+ writes = sorted(
+ name
+ for name, value in vars(incus_regression.WorktreeReservation).items()
+ if callable(value) and not name.startswith("_")
+ )
+ assert writes, "the reservation performs no writes, so this test proves nothing"
+ for name in writes:
+ method = getattr(mine, name)
+ parameters = set(inspect.signature(method).parameters)
+ unknown = parameters - {"runner"}
+ assert not unknown, f"{name} takes {sorted(unknown)}: teach this test how to call it"
+ method(**({"runner": NewRunner()} if "runner" in parameters else {}))
+
+ rows = json.loads(mapping_path.read_text(encoding="utf-8"))["worktrees"]
+ assert rows["demo"]["claim"] == theirs.claim
+ assert rows["demo"]["host_port"] == 15201
+
+
+def test_a_reserved_row_still_reports_the_environment_that_is_installed(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Taking a slug over does not restate what is built there.
+
+ `reserve` merges into whatever row it finds, so every field it writes lands
+ beside the previous run's. Build identity is therefore written only by
+ `complete`, the end of the reservation that has one: a reservation that wrote
+ its own branch produced a row naming the new branch next to the old commit --
+ an environment that never existed -- and the report that row feeds is what an
+ operator reads before deciding whether the environment is still wanted.
+ """
+ monkeypatch.setattr(incus_regression, "git_common_root", lambda repo_root: repo_root)
+ monkeypatch.setattr(incus_regression, "branch_name", lambda repo_root: "fix/installed")
+ monkeypatch.setattr(incus_regression, "commit_sha", lambda repo_root: "aaaaaaaaaaaa")
+ (tmp_path / ".runtime" / "incus-regression").mkdir(parents=True)
+ target = incus_regression.RegressionTarget(
+ target="worktree",
+ slug="demo",
+ project="avr-wt-demo",
+ instance="avibe-wt-demo",
+ host_port=15300,
+ ui_host="127.0.0.1",
+ ui_port=5123,
+ )
+
+ metadata = incus_regression.WorktreeMetadata(tmp_path, None)
+ built = metadata.reserve(target)
+ metadata.complete(target, built.claim)
+
+ monkeypatch.setattr(incus_regression, "branch_name", lambda repo_root: "fix/arriving")
+ taking_over = metadata.reserve(target)
+
+ row = metadata.rows()["demo"]
+ assert row["claim"] == taking_over.claim
+ assert row["commit"] == "aaaaaaaaaaaa"
+ described = incus_regression.describe_worktree_entry(row)
+ assert "fix/installed" in described
+ assert "fix/arriving" not in described
+
+
+def test_an_empty_remote_names_the_local_daemon_for_every_command() -> None:
+ """`--remote ""` is this machine's daemon everywhere, not two authorities at once.
+
+ `remote_ref` has always read an empty name as local, while the metadata
+ accessor read the argument itself and called it another daemon, so an
+ unexpanded `--remote "$INCUS_REMOTE"` created the environment here and
+ recorded nothing about it: the host port allocated with no row naming it.
+ Either reader could have been taught the other's rule, which is why the value
+ is normalized once where it is defined, and why the property is asserted over
+ every command discovered from the parser rather than over a list written here.
+ """
+ parser = incus_regression.build_parser()
+ subcommands = parser._subparsers._group_actions[0].choices
+ checked = [
+ name
+ for name, sub in subcommands.items()
+ if any("--remote" in action.option_strings for action in sub._actions)
+ ]
+ assert checked, "no subcommand accepts --remote"
+
+ for name in checked:
+ for spelling in ("", " "):
+ assert parser.parse_args([name, "--remote", spelling]).remote is None, name
+ assert parser.parse_args([name, "--remote", " lab "]).remote == "lab", name
+
+ # The consequence, at the reader that used to disagree with `remote_ref`.
+ empty = parser.parse_args(["up", "--remote", ""])
+ assert incus_regression.WorktreeMetadata(Path("/nonexistent"), empty.remote).owned is True
+
+
+def test_up_releases_its_reservation_when_the_run_is_interrupted(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ # Ctrl-C is how an `up` is abandoned in practice, and a KeyboardInterrupt is
+ # not an Exception -- catching only that class would leave exactly the row
+ # this release exists for.
+ class NewRunner:
+ def __init__(self, *, dry_run=False):
+ self.dry_run = dry_run
+
+ names = daemon_listing()
+
+ def run(self, command, **kwargs):
+ return subprocess.CompletedProcess(command, 0, stdout="{}")
+
+ def interrupt(*args, **kwargs):
+ raise KeyboardInterrupt
+
+ monkeypatch.setattr(incus_regression, "current_repo_root", lambda: tmp_path)
+ monkeypatch.setattr(incus_regression, "git_common_root", lambda repo_root: repo_root)
+ monkeypatch.setattr(incus_regression, "load_env_file", lambda repo_root, env_file: None)
+ monkeypatch.setattr(incus_regression, "require_incus", lambda: None)
+ monkeypatch.setattr(incus_regression, "ensure_host_port_available", lambda host, port: None)
+ monkeypatch.setattr(incus_regression, "Runner", NewRunner)
+ monkeypatch.setattr(incus_regression, "require_runtime_seed_env", interrupt)
+
+ args = argparse.Namespace(
+ target="worktree",
+ slug="demo-branch",
+ host_port=None,
+ ui_host="127.0.0.1",
+ ui_port=5123,
+ worktree_port_start=15200,
+ worktree_port_end=15399,
+ env_file=None,
+ dry_run=False,
+ image="avibe-regression-base-current",
+ storage_pool="default",
+ network="incusbr0",
+ cpus="2",
+ memory="4GiB",
+ disk="20GiB",
+ processes="4096",
+ remote=None,
+ clean=False,
+ force_deps=False,
+ no_build_ui=True,
+ force_ui=False,
+ reset_mode="none",
+ )
+
+ with pytest.raises(KeyboardInterrupt):
+ incus_regression.cmd_up(args)
+
+ mapping = json.loads(
+ (tmp_path / ".runtime" / "incus-regression" / "worktrees.json").read_text(encoding="utf-8")
+ )["worktrees"]
+ assert mapping == {}
def test_normalize_runtime_config_updates_preserved_backend_paths_host_and_port() -> None: