From b4eb44f06fdf32a1178f13780b1932b0edc66af6 Mon Sep 17 00:00:00 2001 From: lester076 <105119185+lester076@users.noreply.github.com> Date: Mon, 23 Nov 2026 09:45:14 +0800 Subject: [PATCH] fix(sandbox): park a boxd machine only when its last claim is released (#8391) * fix(sandbox): park a boxd machine only when its last claim is released Two overlapping acquires in one scope record two claims, but the first release parked the shared machine in the warm pool anyway: its outputs were mirrored while the second claimant was still mid-turn, and another caller could reclaim the machine under it (#8382). _release_scope_locked now decrements the claim count first and returns while any other claimant is active; only the last release mirrors outputs and parks the machine. _drop_claim (abandoned async acquires) uses the same primitive instead of decrementing on its own, so the two paths cannot diverge. * fix(sandbox): scope Boxd claims to machine generations --------- Co-authored-by: Willem Jiang --- .../deerflow/community/boxd_sandbox/AGENTS.md | 3 + .../deerflow/community/boxd_sandbox/README.md | 21 ++-- .../boxd_sandbox/boxd_sandbox_provider.py | 108 +++++++++--------- backend/tests/test_boxd_sandbox_provider.py | 86 +++++++++++--- 4 files changed, 139 insertions(+), 79 deletions(-) diff --git a/backend/packages/harness/deerflow/community/boxd_sandbox/AGENTS.md b/backend/packages/harness/deerflow/community/boxd_sandbox/AGENTS.md index 09d13cf694..9d5f0ca875 100644 --- a/backend/packages/harness/deerflow/community/boxd_sandbox/AGENTS.md +++ b/backend/packages/harness/deerflow/community/boxd_sandbox/AGENTS.md @@ -31,3 +31,6 @@ cd backend && python -m pytest tests -q -k "boxd" - **Claims decide when a cancelled acquire releases.** Each caller that receives a sandbox holds a claim; a cancelled caller gives its claim back under the scope serializer, and the last one releases the sandbox. + Sandbox IDs include the machine generation so stale releases cannot consume + a replacement's claims. Serialize lifecycle work and find warm machines by + the stable scope token. diff --git a/backend/packages/harness/deerflow/community/boxd_sandbox/README.md b/backend/packages/harness/deerflow/community/boxd_sandbox/README.md index 62b16e2c62..038db06bd6 100644 --- a/backend/packages/harness/deerflow/community/boxd_sandbox/README.md +++ b/backend/packages/harness/deerflow/community/boxd_sandbox/README.md @@ -45,9 +45,10 @@ snapshot here. New machines start from it. ## Lifecycle and contract -- **One machine per scope.** The local sandbox id comes from - `derive_sandbox_scope_token(user_id, thread_id)`. Every SDK call addresses the - machine by the id that `create` returned. +- **One machine per scope.** The scope token comes from the user and thread. + The local sandbox ID stays the same while that machine is in use or parked. + A replacement machine gets a new sandbox ID. Every SDK call uses the machine + ID returned by `create`. - **Isolated.** Machines are created with `isolated: true`: no private network, no boxd credentials inside the machine. The API key stays in the Gateway, and per-call secrets travel as exec environment, not in the command string. @@ -61,13 +62,13 @@ snapshot here. New machines start from it. a skill policy gets its own projection through `sync_agent_skills`, which replaces the managed skill categories; the machine sees only what was uploaded. -- **Release.** Output files are copied back to the thread's output directory - (at most 2,000 files, 512 MiB and 120 seconds per release), then the machine is - parked in the warm pool. Names that differ only by case or Unicode - normalization, unsafe names and linked destinations are skipped. A copy - failure keeps the previous copy. Listing and downloads share the remaining - 120-second budget. A stopped machine's copy is skipped, and recovery waits - for the next normal sandbox call. +- **Release.** Once the last caller releases a machine, output files are copied + back to the thread's output directory (at most 2,000 files, 512 MiB and 120 + seconds per release), then the machine is parked in the warm pool. Names + that differ only by case or Unicode normalization, unsafe names and linked + destinations are skipped. A copy failure keeps the previous copy. Listing + and downloads share the remaining 120-second budget. A stopped machine's + copy is skipped, and recovery waits for the next normal sandbox call. - **Reuse.** Only the same scope can reclaim a warm machine, after a health check. A failed check deletes the machine and creates a new one. - **Stopped machines** are started on the next call. A file call then runs diff --git a/backend/packages/harness/deerflow/community/boxd_sandbox/boxd_sandbox_provider.py b/backend/packages/harness/deerflow/community/boxd_sandbox/boxd_sandbox_provider.py index 20a98fccd3..c81192bf4a 100644 --- a/backend/packages/harness/deerflow/community/boxd_sandbox/boxd_sandbox_provider.py +++ b/backend/packages/harness/deerflow/community/boxd_sandbox/boxd_sandbox_provider.py @@ -157,8 +157,7 @@ class BoxdSandboxProvider(WarmPoolLifecycleMixin[BoxdSandbox], SandboxProvider): self._shutdown_lock = threading.Lock() self._accepting = True self._acquires = 0 - # Keyed by object identity: a replacement can reuse the logical id - # while an older machine still needs deletion. + # Keyed by object identity, including wrappers for failed creates. self._pending_closes: dict[int, BoxdSandbox] = {} self._closing: set[int] = set() # Callers that received each active sandbox and have not released it. @@ -282,17 +281,18 @@ class BoxdSandboxProvider(WarmPoolLifecycleMixin[BoxdSandbox], SandboxProvider): # ── Identity ───────────────────────────────────────────────────────── @staticmethod - def _sandbox_id(thread_id: str, user_id: str) -> str: - return derive_sandbox_scope_token(user_id=user_id, thread_id=thread_id) + def _scope_from_sandbox_id(sandbox_id: str) -> str: + # Local IDs append the machine generation to the stable scope token. + return sandbox_id.partition("-")[0] @staticmethod def _thread_key(thread_id: str, user_id: str | None) -> tuple[str, str]: return (user_id or "", thread_id) - def _machine_name(self, sandbox_id: str) -> str: + def _machine_name(self, scope_id: str) -> str: # Names are unique per owner and are not free again the moment a # machine is deleted, so each generation gets a random suffix. - return f"{self._config['name_prefix']}{sandbox_id}-{uuid.uuid4().hex[:6]}" + return f"{self._config['name_prefix']}{scope_id}-{uuid.uuid4().hex[:6]}" # ── Warm pool plumbing ─────────────────────────────────────────────── @@ -338,22 +338,19 @@ class BoxdSandboxProvider(WarmPoolLifecycleMixin[BoxdSandbox], SandboxProvider): for sandbox in pending: self._close_quietly(sandbox, context="retry deletion") - def _invalidate_sandbox(self, sandbox_id: str, reason: str, *, expected_sandbox: BoxdSandbox | None = None) -> None: + def _invalidate_sandbox(self, sandbox_id: str, reason: str) -> None: """Deregister a sandbox whose machine is gone, and finish its cleanup.""" + scope_id = self._scope_from_sandbox_id(sandbox_id) with self._lock: - active = self._sandboxes.get(sandbox_id) - warm_entry = self._warm_pool.get(sandbox_id) - current = active or (warm_entry[0] if warm_entry is not None else None) - if expected_sandbox is not None and current is not expected_sandbox: - logger.debug("Ignoring late terminal failure from replaced boxd sandbox %s: %s", sandbox_id, reason) - return - self._sandboxes.pop(sandbox_id, None) - self._claims.pop(sandbox_id, None) - self._warm_pool.pop(sandbox_id, None) - for key in [k for k, sid in self._thread_sandboxes.items() if sid == sandbox_id]: - self._thread_sandboxes.pop(key, None) + current = self._sandboxes.pop(sandbox_id, None) if current is None: - return + warm_entry = self._warm_pool.get(scope_id) + if warm_entry is None or warm_entry[0].id != sandbox_id: + return + current, _ = self._warm_pool.pop(scope_id) + self._claims.pop(sandbox_id, None) + for key in [key for key, value in self._thread_sandboxes.items() if value == sandbox_id]: + self._thread_sandboxes.pop(key, None) self._pending_closes[id(current)] = current logger.warning("Invalidating boxd sandbox %s: %s", sandbox_id, reason) self._close_quietly(current, context="terminal failure") @@ -378,11 +375,11 @@ class BoxdSandboxProvider(WarmPoolLifecycleMixin[BoxdSandbox], SandboxProvider): def _acquire(self, thread_id: str | None, user_id: str | None, ticket: _AcquireTicket | None = None) -> str: with self._acquiring(): if thread_id is None: - sandbox_id = str(uuid.uuid4())[:8] - sandbox_id = self._publish_sandbox(self._create_sandbox(sandbox_id, thread_id=None, user_id=user_id)) + scope_id = uuid.uuid4().hex[:8] + sandbox_id = self._publish_sandbox(self._create_sandbox(scope_id, thread_id=None, user_id=user_id)) else: key = self._thread_key(thread_id, user_id) - scope_id = self._sandbox_id(thread_id, user_id or "") + scope_id = derive_sandbox_scope_token(user_id=user_id or "", thread_id=thread_id) with self._acquire_serializer.hold(scope_id): sandbox_id = self._acquire_scope_locked(key, scope_id, thread_id=thread_id, user_id=user_id) if ticket is not None: @@ -418,16 +415,7 @@ class BoxdSandboxProvider(WarmPoolLifecycleMixin[BoxdSandbox], SandboxProvider): def _drop_claim(self, sandbox_id: str) -> None: """Give back the claim of a caller that never received ``sandbox_id``.""" try: - with self._acquire_serializer.hold(sandbox_id): - with self._lock: - if sandbox_id not in self._sandboxes: - return - remaining = self._claims.get(sandbox_id, 1) - 1 - self._claims[sandbox_id] = remaining - if remaining > 0: - return - logger.info("Releasing boxd sandbox %s: every caller that acquired it was cancelled", sandbox_id) - self._release_scope_locked(sandbox_id) + self.release(sandbox_id) except AcquireSerializerClosed: pass # reset/shutdown owns the sandbox now except Exception: @@ -446,7 +434,7 @@ class BoxdSandboxProvider(WarmPoolLifecycleMixin[BoxdSandbox], SandboxProvider): self._close_quietly(sandbox, context="acquired after provider retirement") raise RuntimeError("boxd provider retired or shut down during acquire") - def _acquire_scope_locked(self, key: tuple[str, str], sandbox_id: str, *, thread_id: str, user_id: str | None) -> str: + def _acquire_scope_locked(self, key: tuple[str, str], scope_id: str, *, thread_id: str, user_id: str | None) -> str: with self._lock: if not self._accepting: raise RuntimeError("boxd provider is retired or shutting down") @@ -455,7 +443,7 @@ class BoxdSandboxProvider(WarmPoolLifecycleMixin[BoxdSandbox], SandboxProvider): self._claims[existing] = self._claims.get(existing, 0) + 1 return existing - reclaimed = self._reclaim_warm_pool(sandbox_id) + reclaimed = self._reclaim_warm_pool(scope_id) if reclaimed is not None: with self._lock: if not self._accepting: @@ -463,18 +451,19 @@ class BoxdSandboxProvider(WarmPoolLifecycleMixin[BoxdSandbox], SandboxProvider): self._thread_sandboxes[key] = reclaimed return reclaimed - sandbox = self._create_sandbox(sandbox_id, thread_id=thread_id, user_id=user_id) + sandbox = self._create_sandbox(scope_id, thread_id=thread_id, user_id=user_id) return self._publish_sandbox(sandbox, key) - def _create_sandbox(self, sandbox_id: str, *, thread_id: str | None, user_id: str | None) -> BoxdSandbox: + def _create_sandbox(self, scope_id: str, *, thread_id: str | None, user_id: str | None) -> BoxdSandbox: + generation = uuid.uuid4().hex + sandbox_id = f"{scope_id}-{generation}" replicas, total = self._replica_count() if total >= replicas: evicted = self._evict_oldest_warm() self._log_replicas_soft_cap(replicas, sandbox_id, evicted) client = self._get_client() - generation = uuid.uuid4().hex - labels = {**self._config["labels"], _LABEL_APP: "sandbox", _LABEL_SCOPE: sandbox_id, _LABEL_GENERATION: generation} + labels = {**self._config["labels"], _LABEL_APP: "sandbox", _LABEL_SCOPE: scope_id, _LABEL_GENERATION: generation} create_kwargs: dict[str, Any] = { "org": self._config["org"], # The agent runs untrusted code: an isolated machine joins no @@ -486,7 +475,7 @@ class BoxdSandboxProvider(WarmPoolLifecycleMixin[BoxdSandbox], SandboxProvider): if self._config[name] is not None: create_kwargs[name] = self._config[name] try: - machine = client.machines.create(self._machine_name(sandbox_id), **create_kwargs) + machine = client.machines.create(self._machine_name(scope_id), **create_kwargs) except BaseException: self._delete_generation(client, generation, sandbox_id) raise @@ -508,7 +497,7 @@ class BoxdSandboxProvider(WarmPoolLifecycleMixin[BoxdSandbox], SandboxProvider): # Never hand out a half-prepared machine, and never leave one running. self._close_quietly(sandbox, context="preparation failure") raise - sandbox._on_terminal_failure = lambda failed_id, reason: self._invalidate_sandbox(failed_id, reason, expected_sandbox=sandbox) + sandbox._on_terminal_failure = self._invalidate_sandbox logger.info("Created boxd sandbox %s (machine %s)", sandbox_id, machine.id) return sandbox @@ -674,7 +663,7 @@ class BoxdSandboxProvider(WarmPoolLifecycleMixin[BoxdSandbox], SandboxProvider): Holds the same scope serializer as acquire and release, so no other lifecycle step sees a half-written skills tree. """ - with self._acquire_serializer.hold(sandbox_id): + with self._acquire_serializer.hold(self._scope_from_sandbox_id(sandbox_id)): with self._lock: sandbox = self._sandboxes.get(sandbox_id) if sandbox is None: @@ -683,31 +672,31 @@ class BoxdSandboxProvider(WarmPoolLifecycleMixin[BoxdSandbox], SandboxProvider): # ── Reuse ──────────────────────────────────────────────────────────── - def _reclaim_warm_pool(self, sandbox_id: str) -> str | None: + def _reclaim_warm_pool(self, scope_id: str) -> str | None: with self._lock: - warm_entry = self._warm_pool.get(sandbox_id) + warm_entry = self._warm_pool.get(scope_id) if warm_entry is None: return None sandbox = warm_entry[0] if not sandbox.ping(): with self._lock: - removed = self._warm_pool.pop(sandbox_id, None) + removed = self._warm_pool.pop(scope_id, None) if removed is not None: - self._destroy_warm_entry(sandbox_id, removed[0], reason="health_check_failed") + self._destroy_warm_entry(scope_id, removed[0], reason="health_check_failed") return None with self._lock: - removed = self._warm_pool.pop(sandbox_id, None) + removed = self._warm_pool.pop(scope_id, None) if removed is None: return None admitted = self._accepting if admitted: - self._sandboxes[sandbox_id] = removed[0] - self._claims[sandbox_id] = 1 + self._sandboxes[sandbox.id] = sandbox + self._claims[sandbox.id] = 1 if not admitted: self._close_quietly(removed[0], context="reclaimed after provider retirement") raise RuntimeError("boxd provider retired or shut down during acquire") - logger.info("Reclaimed warm boxd sandbox %s", sandbox_id) - return sandbox_id + logger.info("Reclaimed warm boxd sandbox %s", sandbox.id) + return sandbox.id def get(self, sandbox_id: str) -> Sandbox | None: with self._lock: @@ -726,7 +715,7 @@ class BoxdSandboxProvider(WarmPoolLifecycleMixin[BoxdSandbox], SandboxProvider): if sandbox_id not in self._sandboxes: return try: - with self._acquire_serializer.hold(sandbox_id): + with self._acquire_serializer.hold(self._scope_from_sandbox_id(sandbox_id)): self._release_scope_locked(sandbox_id) except AcquireSerializerClosed: # reset/shutdown closed the serializer after the check above. @@ -738,9 +727,17 @@ class BoxdSandboxProvider(WarmPoolLifecycleMixin[BoxdSandbox], SandboxProvider): def _release_scope_locked(self, sandbox_id: str) -> None: with self._lock: sandbox = self._sandboxes.get(sandbox_id) + if sandbox is None: + return + # Overlapping turns can hold several claims on one machine. Only the + # LAST release parks it: mirroring outputs and re-entering the warm + # pool while another claimant is mid-turn hands its files to a + # stranger (#8382). + remaining = self._claims.get(sandbox_id, 1) - 1 + if remaining > 0: + self._claims[sandbox_id] = remaining + return scope = next((key for key, value in self._thread_sandboxes.items() if value == sandbox_id), None) - if sandbox is None: - return if scope is not None and scope[0]: try: self._sync_outputs_to_host(sandbox, user_id=scope[0], thread_id=scope[1]) @@ -759,7 +756,7 @@ class BoxdSandboxProvider(WarmPoolLifecycleMixin[BoxdSandbox], SandboxProvider): if close_now: self._pending_closes[id(sandbox)] = sandbox else: - self._warm_pool[sandbox_id] = (sandbox, time.monotonic()) + self._warm_pool[self._scope_from_sandbox_id(sandbox_id)] = (sandbox, time.monotonic()) if close_now: self._close_quietly(sandbox, context="released during shutdown") else: @@ -901,8 +898,9 @@ class BoxdSandboxProvider(WarmPoolLifecycleMixin[BoxdSandbox], SandboxProvider): self._accepting = False now = time.monotonic() for sandbox_id, sandbox in self._sandboxes.items(): - self._warm_pool.setdefault(sandbox_id, (sandbox, now)) + self._warm_pool.setdefault(self._scope_from_sandbox_id(sandbox_id), (sandbox, now)) self._sandboxes.clear() + self._claims.clear() self._thread_sandboxes.clear() self._acquire_serializer.close() diff --git a/backend/tests/test_boxd_sandbox_provider.py b/backend/tests/test_boxd_sandbox_provider.py index 0fe14a53f2..0961d5a0ac 100644 --- a/backend/tests/test_boxd_sandbox_provider.py +++ b/backend/tests/test_boxd_sandbox_provider.py @@ -21,12 +21,14 @@ import threading import types from pathlib import Path from typing import Any +from unittest.mock import Mock import pytest from deerflow.community.boxd_sandbox.boxd_sandbox import BoxdSandbox from deerflow.community.boxd_sandbox.boxd_sandbox_provider import BoxdSandboxProvider, _import_client, _ShutdownIncompleteError from deerflow.config.paths import Paths +from deerflow.sandbox.identity import derive_sandbox_scope_token posix_only = pytest.mark.skipif(os.name != "posix", reason="runs generated scripts with the local bash") @@ -335,8 +337,10 @@ def test_create_is_isolated_labelled_and_sized(monkeypatch: pytest.MonkeyPatch, assert kwargs["auto_suspend_timeout"] == 300 generation = kwargs["labels"].pop("deer-flow-generation") assert re.fullmatch(r"[0-9a-f]{32}", generation) - assert kwargs["labels"] == {"team": "research", "deer-flow": "sandbox", "deer-flow-scope": sandbox_id} - assert re.fullmatch(rf"deer-flow-{sandbox_id}-[0-9a-f]{{6}}", name) + scope_id = derive_sandbox_scope_token(user_id="owner", thread_id="thread") + assert kwargs["labels"] == {"team": "research", "deer-flow": "sandbox", "deer-flow-scope": scope_id} + assert sandbox_id == f"{scope_id}-{generation}" + assert re.fullmatch(rf"deer-flow-{scope_id}-[0-9a-f]{{6}}", name) assert fake.client_kwargs == {"api_key": "test-key", "region": "fra"} # Every later call addresses the machine by the id create returned. assert {call["machine"] for call in fake.execs} == {"m-1"} @@ -396,6 +400,10 @@ def test_each_generation_gets_a_new_machine_name(installed) -> None: # ── Acquire, reuse and release ─────────────────────────────────────────── +def _warm_sandbox_ids(provider: BoxdSandboxProvider) -> set[str]: + return {sandbox.id for sandbox, _ in provider._warm_pool.values()} + + def test_scope_reuse_and_user_thread_isolation(installed) -> None: provider, fake = installed first = provider.acquire("thread", user_id="alice") @@ -415,12 +423,63 @@ def test_release_parks_and_same_scope_reclaims_without_create(installed) -> None assert len(fake.created) == 1 +def test_release_mirrors_and_parks_only_after_the_last_claim(installed, monkeypatch: pytest.MonkeyPatch) -> None: + """Overlapping turns share one machine until the final release (#8382).""" + provider, fake = installed + first = provider.acquire("thread", user_id="owner") + assert provider.acquire("thread", user_id="owner") == first + sandbox = provider.get(first) + sync_outputs = Mock() + monkeypatch.setattr(provider, "_sync_outputs_to_host", sync_outputs) + + provider.release(first) + + assert sandbox is not None and provider.get(first) is sandbox + assert provider._warm_pool == {} + assert provider._claims[first] == 1 + sync_outputs.assert_not_called() + + provider.release(first) + + assert provider.get(first) is None + assert _warm_sandbox_ids(provider) == {first} + sync_outputs.assert_called_once_with(sandbox, user_id="owner", thread_id="thread") + assert len(fake.created) == 1 + + +@pytest.mark.parametrize("release_method", ["release", "_drop_claim"]) +def test_release_from_invalidated_machine_keeps_replacement_claim(installed, monkeypatch: pytest.MonkeyPatch, release_method: str) -> None: + provider, fake = installed + old_id = provider.acquire("thread", user_id="owner") + provider._invalidate_sandbox(old_id, "gone") + replacement_id = provider.acquire("thread", user_id="owner") + replacement = provider.get(replacement_id) + sync_outputs = Mock() + monkeypatch.setattr(provider, "_sync_outputs_to_host", sync_outputs) + + getattr(provider, release_method)(old_id) + + assert replacement is not None and provider.get(replacement_id) is replacement + assert provider._claims[replacement_id] == 1 + assert provider.get(old_id) is None + assert provider._warm_pool == {} + assert fake.deleted == ["m-1"] + sync_outputs.assert_not_called() + + provider.release(replacement_id) + sync_outputs.assert_called_once_with(replacement, user_id="owner", thread_id="thread") + provider._invalidate_sandbox(old_id, "late terminal failure") + assert provider.acquire("thread", user_id="owner") == replacement_id + assert provider.get(replacement_id) is replacement + assert len(fake.created) == 2 + + def test_unhealthy_warm_machine_is_deleted_and_replaced(installed) -> None: provider, fake = installed sandbox_id = provider.acquire("thread", user_id="owner") provider.release(sandbox_id) fake.health_ok = False - provider.acquire("thread", user_id="owner") + assert provider.acquire("thread", user_id="owner") != sandbox_id assert fake.deleted == ["m-1"] assert len(fake.created) == 2 @@ -622,7 +681,7 @@ def test_output_mirror_passes_remaining_deadline_to_downloads(installed, paths: assert [call["timeout"] for call in downloads] == [1.0, 0.25] assert (outputs / "a.txt").read_bytes() == (b"previous" if first_transfer_fails else b"a") assert (outputs / "b.txt").read_bytes() == b"b" - assert sandbox_id in provider._warm_pool + assert _warm_sandbox_ids(provider) == {sandbox_id} def test_expired_output_mirror_starts_no_download(installed, monkeypatch: pytest.MonkeyPatch) -> None: @@ -640,7 +699,7 @@ def test_expired_output_mirror_starts_no_download(installed, monkeypatch: pytest fake.exec_override = listing provider.release(sandbox_id) assert all(call["argv"][0] != "head" for call in fake.execs) - assert sandbox_id in provider._warm_pool + assert _warm_sandbox_ids(provider) == {sandbox_id} @pytest.mark.parametrize("stop_during_listing", [False, True]) @@ -664,7 +723,7 @@ def test_output_mirror_defers_stopped_machine_recovery(installed, paths: Paths, provider.release(sandbox_id) assert fake.starts == [] assert (outputs / "a.txt").read_bytes() == b"previous" - assert sandbox_id in provider._warm_pool + assert _warm_sandbox_ids(provider) == {sandbox_id} fake.exec_override = None provider.acquire("thread", user_id="owner") assert fake.starts == ["m-1"] @@ -685,7 +744,7 @@ def test_output_mirror_rechecks_deadline_after_local_preflight(installed, monkey monkeypatch.setattr(provider, "_output_destination", preflight) provider.release(sandbox_id) assert all(call["argv"][0] != "head" for call in fake.execs) - assert sandbox_id in provider._warm_pool + assert _warm_sandbox_ids(provider) == {sandbox_id} def test_output_sync_skips_ambiguous_and_unsafe_names(installed, paths: Paths) -> None: @@ -706,20 +765,19 @@ def test_output_sync_failure_still_parks_machine(installed, monkeypatch: pytest. sandbox_id = provider.acquire("thread", user_id="owner") monkeypatch.setattr(provider, "_sync_outputs_to_host", lambda *a, **k: (_ for _ in ()).throw(OSError("listing failed"))) provider.release(sandbox_id) - assert sandbox_id in provider._warm_pool + assert _warm_sandbox_ids(provider) == {sandbox_id} def test_invalidated_during_sync_is_not_parked(installed, monkeypatch: pytest.MonkeyPatch) -> None: provider, fake = installed sandbox_id = provider.acquire("thread", user_id="owner") - sandbox = provider.get(sandbox_id) def invalidate(*args, **kwargs): - provider._invalidate_sandbox(sandbox_id, "gone", expected_sandbox=sandbox) + provider._invalidate_sandbox(sandbox_id, "gone") monkeypatch.setattr(provider, "_sync_outputs_to_host", invalidate) provider.release(sandbox_id) - assert sandbox_id not in provider._warm_pool + assert provider._warm_pool == {} assert fake.deleted == ["m-1"] @@ -1007,7 +1065,7 @@ def test_reset_parks_active_machines_for_later_cleanup(installed) -> None: sandbox_id = provider.acquire("thread", user_id="owner") provider.reset() assert provider.get(sandbox_id) is None - assert sandbox_id in provider._warm_pool + assert _warm_sandbox_ids(provider) == {sandbox_id} assert fake.deleted == [] @@ -1051,7 +1109,7 @@ def test_cancelled_acquire_releases_its_new_machine(installed) -> None: await asyncio.sleep(0.01) asyncio.run(scenario()) - assert list(provider._warm_pool) == [provider._sandbox_id("thread", "owner")] + assert list(provider._warm_pool) == [derive_sandbox_scope_token(user_id="owner", thread_id="thread")] assert provider._sandboxes == {} @@ -1103,7 +1161,7 @@ def test_two_cancelled_acquires_release_the_machine(installed) -> None: await asyncio.sleep(0.01) asyncio.run(scenario()) - assert list(provider._warm_pool) == [provider._sandbox_id("thread", "owner")] + assert list(provider._warm_pool) == [derive_sandbox_scope_token(user_id="owner", thread_id="thread")] assert provider._sandboxes == {} assert len(fake.created) == 1