Skip to content
Python

OpenShell clean-up removes only the sandboxes its own state folder made

Rohit C Prasad0a3c7413611c
diff --git a/coworker/sandbox/providers/openshell.py b/coworker/sandbox/providers/openshell.py
index 93d76df7..c32073a4 100644
--- a/coworker/sandbox/providers/openshell.py
+++ b/coworker/sandbox/providers/openshell.py
@@ -35,6 +35,7 @@ import yaml
from ...secrets import state_dir
from ..bundle import build_runner_zipapp
+from ..registry import REGISTRY_LABEL, registry_id
from ..transport import Transport
from .. import credentials as creds
from . import openshell_policy as policy
@@ -215,10 +216,13 @@ class OpenShellProvider:
label: str = "",
credentials: Sequence[creds.Grant] = (),
extra_hosts: Sequence[str] = (),
+ registry: Optional[str] = None,
) -> None:
"""`roots`: [{"path", "writable"}], primary first. `label`: who this sandbox is for
(session and agent), stored on the sandbox so leftovers can be found. `extra_hosts`:
- the machine's own additions to the network list ("host:port")."""
+ the machine's own additions to the network list ("host:port"). `registry`: the id
+ of the registry that records this sandbox (default: this state folder's); only that
+ registry's clean-up may delete it."""
if not roots:
raise ValueError("an OpenShell sandbox needs at least one folder")
self.roots = [{"path": str(Path(r["path"]).expanduser().resolve()), "writable": bool(r.get("writable"))} for r in roots]
@@ -228,6 +232,7 @@ class OpenShellProvider:
self.image = image or sandbox_image()
# A label value may hold letters, digits, '-', '_' and '.', and at most 63 characters.
self.label = "".join(c if c.isalnum() or c in "-_." else "-" for c in label)[:63].strip("-_.")
+ self.registry = registry or registry_id()
self.sandbox_name = f"ow-{uuid.uuid4().hex[:12]}"
self.sandbox_id: Optional[str] = None
self._runner = build_runner_zipapp()
@@ -282,7 +287,7 @@ class OpenShellProvider:
"sandbox", "create", "--name", self.sandbox_name, "--from", self.image,
"--no-tty", "--detach", "--no-auto-providers",
"--policy", str(policy_file), "--driver-config-json", driver_config,
- "--label", f"{LABEL}=1", *[x for k, v in env.items() for x in ("--env", f"{k}={v}")],
+ "--label", f"{LABEL}=1", "--label", f"{REGISTRY_LABEL}={self.registry}", *[x for k, v in env.items() for x in ("--env", f"{k}={v}")],
] # fmt: skip
if self.label:
args += ["--label", f"{LABEL}-owner={self.label}"]
@@ -365,13 +370,18 @@ class OpenShellProvider:
shutil.rmtree(self._tmp, ignore_errors=True)
-def list_our_sandboxes() -> list[dict[str, Any]]:
- """Every sandbox on this gateway that OpenWorker created (for the registry's clean-up)."""
- done = _cli("sandbox", "list", "--selector", f"{LABEL}=1", "-o", "json", timeout=60, check=False)
+def list_our_sandboxes(registry: str) -> list[dict[str, Any]]:
+ """The sandboxes on this gateway that the given registry made (for its clean-up). Other
+ OpenWorker processes of this user share the gateway; their sandboxes are not listed."""
+ selector = f"{LABEL}=1,{REGISTRY_LABEL}={registry}"
+ done = _cli("sandbox", "list", "--selector", selector, "-o", "json", timeout=60, check=False)
if done.returncode != 0 or not done.stdout.strip():
return []
data = json.loads(done.stdout)
- return data.get("sandboxes", data) if isinstance(data, dict) else data
+ listed = data.get("sandboxes", data) if isinstance(data, dict) else data
+ # Checked here too: whatever the gateway did with the selector, never hand back a
+ # sandbox that carries another registry's label (or none).
+ return [s for s in listed if (s.get("labels") or {}).get(REGISTRY_LABEL) == registry]
class GrpcExecTransport:
diff --git a/coworker/sandbox/registry.py b/coworker/sandbox/registry.py
index 559d35ff..eaf7967e 100644
--- a/coworker/sandbox/registry.py
+++ b/coworker/sandbox/registry.py
@@ -11,6 +11,7 @@ gone (a crash, a kill) so they do not pile up.
from __future__ import annotations
+import hashlib
import json
import logging
import os
@@ -26,6 +27,12 @@ from ..secrets import state_dir
log = logging.getLogger(__name__)
LOCAL_MACHINE = "local"
+# The label that says which registry (which state folder) made an OpenShell sandbox. The
+# gateway is shared by every OpenWorker process of this user on this machine, and each
+# process only knows the sandboxes in its own registry; without this label a second
+# OpenWorker with another state folder (a test server, a one-shot run) took every other
+# sandbox for an orphan and deleted it (seen on the Linux VM 2026-09-29).
+REGISTRY_LABEL = "openworker-registry"
MAX_ENV = "OPENWORKER_SANDBOX_MAX"
DEFAULT_MAX = 20
@@ -51,6 +58,13 @@ class SandboxLimitReached(RuntimeError):
pass
+def registry_id(path: Optional[Path] = None) -> str:
+ """A short, stable id for a registry file: the same state folder always gives the same
+ id, and another state folder a different one. It is a label value on each sandbox."""
+ target = Path(path) if path is not None else state_dir() / "sandbox" / "registry.db"
+ return hashlib.sha256(str(target.expanduser().resolve()).encode()).hexdigest()[:16]
+
+
def _alive(pid: int) -> bool:
if sys.platform == "win32":
# `os.kill(pid, 0)` is TerminateProcess on Windows, not a probe.
@@ -70,6 +84,7 @@ class SandboxRegistry:
def __init__(self, path: Optional[Path] = None) -> None:
self.path = Path(path) if path is not None else state_dir() / "sandbox" / "registry.db"
self.path.parent.mkdir(parents=True, exist_ok=True)
+ self.id = registry_id(self.path)
self._lock = threading.Lock()
with self._connect() as db:
db.executescript(_SCHEMA)
@@ -141,8 +156,9 @@ class SandboxRegistry:
# -- clean-up ---------------------------------------------------------------------
def reap(self) -> list[str]:
- """Remove sandboxes whose server process is gone, and OpenShell sandboxes that carry
- our label but that no living server owns. Returns the names removed."""
+ """Remove sandboxes whose server process is gone, and OpenShell sandboxes made from
+ THIS registry that no living server owns. A sandbox another registry made is never
+ touched here, whatever its state. Returns the names removed."""
removed: list[str] = []
rows = self.list(LOCAL_MACHINE)
dead = [r for r in rows if not _alive(int(r["server_pid"]))]
@@ -151,7 +167,7 @@ class SandboxRegistry:
from .providers import openshell
try:
- listed = openshell.list_our_sandboxes()
+ listed = openshell.list_our_sandboxes(self.id)
except Exception:
listed = []
openshell_names = {str(s.get("name") or s.get("metadata", {}).get("name") or "") for s in listed} - {""}
diff --git a/coworker/sandbox/workspace.py b/coworker/sandbox/workspace.py
index b2e41796..f0d52cd8 100644
--- a/coworker/sandbox/workspace.py
+++ b/coworker/sandbox/workspace.py
@@ -309,10 +309,11 @@ def open_workspace(
from .registry import SandboxRegistry
label = "-".join(part for part in (session_id[:24], agent[:24]) if part)
+ registry = SandboxRegistry()
return RunnerWorkspace(
- OpenShellProvider(roots=listed, cwd=str(cwd), label=label, credentials=grants, profile=profile, extra_hosts=added),
+ OpenShellProvider(roots=listed, cwd=str(cwd), label=label, credentials=grants, profile=profile, extra_hosts=added, registry=registry.id),
cwd=cwd,
- registry=SandboxRegistry(),
+ registry=registry,
session_id=session_id,
agent=agent,
live_roots=roots,
diff --git a/tests/test_sandbox_openshell.py b/tests/test_sandbox_openshell.py
index b1f85096..1f7591f4 100644
--- a/tests/test_sandbox_openshell.py
+++ b/tests/test_sandbox_openshell.py
@@ -190,7 +190,7 @@ def test_reap_leaves_a_sandbox_that_a_living_server_is_still_creating(tmp_path,
reg = registry_mod.SandboxRegistry(tmp_path / "registry.db")
reg.record("ow-building", provider="openshell", session_id="s1", state="creating") # this server, alive
monkeypatch.setattr(registry_mod, "_openshell_present", lambda: True)
- monkeypatch.setattr(openshell, "list_our_sandboxes", lambda: [{"name": "ow-building"}, {"name": "ow-orphan"}])
+ monkeypatch.setattr(openshell, "list_our_sandboxes", lambda registry: [{"name": "ow-building"}, {"name": "ow-orphan"}])
deleted: list[str] = []
monkeypatch.setattr(openshell, "_cli", lambda *args, **kw: deleted.append(args[2]))
assert reg.reap() == ["ow-orphan"]
@@ -198,6 +198,65 @@ def test_reap_leaves_a_sandbox_that_a_living_server_is_still_creating(tmp_path,
assert reg.find("s1")["state"] == "creating"
+def test_each_state_folder_cleans_up_only_the_sandboxes_it_made(tmp_path, monkeypatch):
+ # Seen on the Linux VM 2026-09-29: a second OpenWorker with its own state folder (a test
+ # server) deleted the live sandbox of the machine's server on start, because its own
+ # registry did not list it. Each sandbox now carries its registry's id, and a registry's
+ # clean-up lists only sandboxes with its own id.
+ import json as _json
+
+ from coworker.sandbox import registry as registry_mod
+
+ machine = registry_mod.SandboxRegistry(tmp_path / "machine" / "registry.db")
+ other = registry_mod.SandboxRegistry(tmp_path / "test-server" / "registry.db")
+ assert machine.id != other.id
+ assert machine.id == registry_mod.registry_id(tmp_path / "machine" / "registry.db") # stable
+ machine.record("ow-live", provider="openshell", session_id="s1") # the machine's session
+ gateway = [
+ {"name": "ow-live", "labels": {"openworker": "1", "openworker-registry": machine.id}},
+ {"name": "ow-crashed", "labels": {"openworker": "1", "openworker-registry": other.id}},
+ {"name": "ow-unlabelled", "labels": {"openworker": "1"}},
+ ]
+ deleted: list[str] = []
+
+ def cli(*args, **kw):
+ if args[:2] == ("sandbox", "list"):
+ # Even a gateway that ignored the selector must not lead to a foreign delete.
+ return subprocess.CompletedProcess(args, 0, _json.dumps({"sandboxes": gateway}), "")
+ deleted.append(args[2])
+ return subprocess.CompletedProcess(args, 0, "", "")
+
+ monkeypatch.setattr(registry_mod, "_openshell_present", lambda: True)
+ monkeypatch.setattr(openshell, "_cli", cli)
+ assert other.reap() == ["ow-crashed"] # its own orphan only; the machine's live sandbox stays
+ assert deleted == ["ow-crashed"]
+ assert machine.reap() == [] and deleted == ["ow-crashed"] # owned by a live server: kept
+
+
+def test_a_sandbox_is_created_with_its_registry_label(tmp_path, monkeypatch):
+ monkeypatch.setenv("COWORKER_STATE_DIR", str(tmp_path))
+ monkeypatch.setattr(openshell, "build_runner_zipapp", lambda: tmp_path / "sandbox" / "runner-x.pyz")
+ monkeypatch.setattr(openshell, "preflight", lambda: None)
+ project = tmp_path / "project"
+ project.mkdir()
+ seen: list = []
+
+ def cli(*args, **kw):
+ seen.append(args)
+ raise RuntimeError("stop here")
+
+ monkeypatch.setattr(openshell, "_cli", cli)
+ provider = openshell.OpenShellProvider(roots=[{"path": str(project), "writable": True}], registry="abc123")
+ with pytest.raises(RuntimeError, match="stop here"):
+ provider._create()
+ create = seen[0]
+ assert "openworker-registry=abc123" in create and "openworker=1" in create
+ # Without an explicit id the sandbox belongs to this state folder's registry.
+ from coworker.sandbox.registry import SandboxRegistry, registry_id
+
+ assert openshell.OpenShellProvider(roots=[{"path": str(project), "writable": True}]).registry == registry_id() == SandboxRegistry().id
+
+
def test_a_workspace_reserves_its_name_before_creating_the_sandbox(tmp_path):
from coworker.sandbox import registry as registry_mod
from coworker.sandbox.workspace import RunnerWorkspace
@@ -294,7 +353,8 @@ def _open(folder, **kwargs):
@live
def test_a_session_in_a_real_sandbox(folder):
(folder / "hello.txt").write_text("from the machine\n")
- ws, roots = _open(folder, session_id="s-test", agent="swe-lead")
+ # Nothing is allowed until the machine ticks it: api.github.com is ticked for this test.
+ ws, roots = _open(folder, session_id="s-test", agent="swe-lead", extra_hosts=["api.github.com"])
try:
assert ws.describe()["enforcement"] == "full" and ws.describe()["runner"]["os"] == "Linux"
row = ws.registry.find("s-test", "swe-lead")
@@ -377,12 +437,33 @@ def test_a_sandbox_left_behind_by_a_dead_server_is_removed(folder):
orphan = OpenShellProvider(roots=[{"path": str(folder), "writable": True}], label="orphan")
orphan.create() # created, never recorded by a living server
- names = lambda: {str(s.get("name")) for s in list_our_sandboxes()} # noqa: E731
+ names = lambda: {str(s.get("name")) for s in list_our_sandboxes(SandboxRegistry().id)} # noqa: E731
assert orphan.sandbox_name in names()
removed = SandboxRegistry().reap()
assert orphan.sandbox_name in removed and orphan.sandbox_name not in names()
+@live
+def test_another_state_folder_never_removes_a_live_sandbox(folder, tmp_path):
+ """Two OpenWorker processes with different state folders share this user's gateway. The
+ second one's clean-up must leave the first one's sandbox alone (Linux VM, 2026-09-29)."""
+ from coworker.sandbox.providers.openshell import OpenShellProvider, list_our_sandboxes
+ from coworker.sandbox.registry import SandboxRegistry
+
+ mine = SandboxRegistry()
+ other = SandboxRegistry(tmp_path / "other-state" / "sandbox" / "registry.db")
+ live_one = OpenShellProvider(roots=[{"path": str(folder), "writable": True}], label="live", registry=mine.id)
+ live_one.create()
+ mine.record(live_one.sandbox_name, provider="openshell", session_id="live")
+ try:
+ assert live_one.sandbox_name not in other.reap()
+ assert live_one.sandbox_name in {str(s.get("name")) for s in list_our_sandboxes(mine.id)}
+ assert not list_our_sandboxes(other.id)
+ finally:
+ mine.close(live_one.sandbox_name)
+ live_one.destroy()
+
+
@live
def test_credential_grants_are_copied_into_a_real_sandbox(folder):
"""A fake `.ssh` and `.config/gh` under a made-up home are granted: inside, HOME is the