From 5c93f6d0be1482a95509cf31a0b82a2d43f33b19 Mon Sep 17 00:00:00 2001 From: Jimmy <316484903+jimmyallinai@users.noreply.github.com> Date: Thu, 26 Nov 2026 07:52:57 +0800 Subject: [PATCH] fix(sandbox): ignore late terminal failure from replaced BoxLite box (#8621) * fix(sandbox): ignore late terminal failure from replaced BoxLite box * fix(sandbox): bind each BoxLite failure callback to its box --------- Co-authored-by: Willem Jiang --- .../deerflow/community/boxlite/provider.py | 27 ++++- backend/tests/test_boxlite_provider.py | 114 ++++++++++++++---- 2 files changed, 117 insertions(+), 24 deletions(-) diff --git a/backend/packages/harness/deerflow/community/boxlite/provider.py b/backend/packages/harness/deerflow/community/boxlite/provider.py index 66aa5b3570..8f2504abd5 100644 --- a/backend/packages/harness/deerflow/community/boxlite/provider.py +++ b/backend/packages/harness/deerflow/community/boxlite/provider.py @@ -312,10 +312,31 @@ class BoxliteProvider(WarmPoolLifecycleMixin[BoxliteBox], SandboxProvider): else: logger.warning("Error closing BoxLite box %s (reason=%s): %s", sandbox_id, reason, e) - def _invalidate_box(self, sandbox_id: str, reason: str) -> None: + def _wrap_box(self, sandbox_id: str, box: SimpleBox | _AsyncBoxAdapter) -> BoxliteBox: + """Bind the terminal-failure callback to this adapter instance.""" + wrapped = BoxliteBox( + sandbox_id, + box, + self._loop.run, + default_env=self._config["environment"], + on_terminal_failure=lambda failed_id, reason: self._invalidate_box(failed_id, reason, expected_box=wrapped), + ) + return wrapped + + def _invalidate_box(self, sandbox_id: str, reason: str, *, expected_box: BoxliteBox | None = None) -> None: """Destroy and deregister a box after a terminal command-path failure.""" box_to_close: BoxliteBox | None = None with self._lock: + active_box = self._boxes.get(sandbox_id) + warm_entry = self._warm_pool.get(sandbox_id) + current = active_box or (warm_entry[0] if warm_entry is not None else None) + if expected_box is not None and current is not expected_box: + # Operations already in flight can fail after another failure + # has removed their adapter and acquire rebuilt this scope. + # The logical id is stable; only the originating adapter owns + # the right to invalidate this active or warm generation. + logger.debug("Ignoring late terminal failure from replaced BoxLite box %s: %s", sandbox_id, reason) + return active_box = self._boxes.pop(sandbox_id, None) warm_entry = self._warm_pool.pop(sandbox_id, None) self._active_box_identity.pop(sandbox_id, None) @@ -372,7 +393,7 @@ class BoxliteProvider(WarmPoolLifecycleMixin[BoxliteBox], SandboxProvider): continue if box is None: continue - wrapped = BoxliteBox(sandbox_id, _AsyncBoxAdapter(box), self._loop.run, default_env=self._config["environment"], on_terminal_failure=self._invalidate_box) + wrapped = self._wrap_box(sandbox_id, _AsyncBoxAdapter(box)) with self._lock: if sandbox_id in self._boxes or sandbox_id in self._warm_pool: continue @@ -502,7 +523,7 @@ class BoxliteProvider(WarmPoolLifecycleMixin[BoxliteBox], SandboxProvider): box = self._loop.run(_make()) logger.info("Created BoxLite box %s (name=%s, image=%s)", sandbox_id, self._box_name(sandbox_id), self._config["image"]) - return BoxliteBox(sandbox_id, box, self._loop.run, default_env=self._config["environment"], on_terminal_failure=self._invalidate_box) + return self._wrap_box(sandbox_id, box) def get(self, sandbox_id: str) -> Sandbox | None: with self._lock: diff --git a/backend/tests/test_boxlite_provider.py b/backend/tests/test_boxlite_provider.py index df0d32c4d3..bc95395635 100644 --- a/backend/tests/test_boxlite_provider.py +++ b/backend/tests/test_boxlite_provider.py @@ -431,18 +431,25 @@ def test_create_box_passes_prefixed_sandbox_id_as_name(monkeypatch): def test_startup_reconciliation_adopts_prefixed_existing_boxes(monkeypatch): - """Existing DeerFlow-named BoxLite boxes are adopted into the warm pool.""" + """Recovered boxes keep independent failure callbacks after warm-pool adoption.""" monkeypatch.setattr( "deerflow.community.boxlite.provider.get_app_config", lambda: _stub_config(), ) stopped: list[str] = [] commands = [] + first_id = BoxliteProvider._sandbox_id("thread", "user") + second_id = BoxliteProvider._sandbox_id("other-thread", "user") monkeypatch.setitem(sys.modules, "boxlite", types.SimpleNamespace(ExecResult=types.SimpleNamespace)) class _NativeBox: + def __init__(self, sandbox_id): + self.sandbox_id = sandbox_id + async def exec(self, command, args=None, env=None, tty=False, user=None, timeout_secs=None, cwd=None): commands.append((command, args, env, timeout_secs, threading.get_ident())) + if args[-1] == "echo disconnected": + raise RuntimeError("vsock disconnected") async def stream(*values): for value in values: @@ -454,20 +461,16 @@ def test_startup_reconciliation_adopts_prefixed_existing_boxes(monkeypatch): return types.SimpleNamespace(stdout=lambda: stream("ok\n" if args[-1] == "echo ok" else "restored\n"), stderr=lambda: stream(), wait=wait) async def stop(self): - stopped.append("adopted") + stopped.append(self.sandbox_id) + + recovered = {f"deer-flow-boxlite-{sandbox_id}": _NativeBox(sandbox_id) for sandbox_id in (first_id, second_id)} class _Runtime: async def list_info(self): - return [ - types.SimpleNamespace(name="deer-flow-boxlite-adopted"), - types.SimpleNamespace(name="unrelated-box"), - types.SimpleNamespace(name=None), - ] + return [types.SimpleNamespace(name=name) for name in [*recovered, "unrelated-box", None]] async def get(self, name): - if name == "deer-flow-boxlite-adopted": - return _NativeBox() - raise AssertionError(f"unexpected box lookup: {name}") + return recovered[name] class _Boxlite: @staticmethod @@ -478,18 +481,26 @@ def test_startup_reconciliation_adopts_prefixed_existing_boxes(monkeypatch): provider = BoxliteProvider() - assert list(provider._warm_pool) == ["adopted"] - adopted_box = provider._warm_pool["adopted"][0] - assert adopted_box.id == "adopted" - assert provider._reclaim_warm_pool("adopted", ("user", "thread")) == "adopted" - assert adopted_box.execute_command("echo restored", env={"KEY": "value"}, timeout=2) == "restored\n" - assert commands == [ - ("sh", ["-lc", "echo ok"], None, 5, provider._loop._thread.ident), - ("sh", ["-lc", "echo restored"], [("KEY", "value")], 2, provider._loop._thread.ident), - ] + try: + assert list(provider._warm_pool) == [first_id, second_id] + first_box = provider._warm_pool[first_id][0] + second_box = provider._warm_pool[second_id][0] + assert provider.acquire("thread", user_id="user") == first_id + assert provider.get(first_id) is first_box + assert first_box.execute_command("echo restored", env={"KEY": "value"}, timeout=2) == "restored\n" + assert commands == [ + ("sh", ["-lc", "echo ok"], None, 5, provider._loop._thread.ident), + ("sh", ["-lc", "echo restored"], [("KEY", "value")], 2, provider._loop._thread.ident), + ] - provider.shutdown() - assert stopped == ["adopted"] + assert first_box.execute_command("echo disconnected") == "Error: vsock disconnected" + assert provider.get(first_id) is None + assert stopped == [first_id] + assert provider._warm_pool[second_id][0] is second_box + finally: + provider.shutdown() + + assert stopped == [first_id, second_id] def test_release_parks_in_warm_pool(monkeypatch): @@ -851,6 +862,67 @@ def test_stale_closed_adapter_cannot_invalidate_recreated_box(monkeypatch): provider.shutdown() +def test_late_terminal_failure_from_replaced_box_keeps_replacement(monkeypatch): + """A replaced generation's late failure must not close the recreated box. + + Unlike the stale-closed case above, this command is already past the + ``_closed`` check when the scope is rebuilt, so its terminal failure + reaches the provider after the replacement exists (#8619). + """ + monkeypatch.setattr( + "deerflow.community.boxlite.provider.get_app_config", + lambda: _stub_config({"health_check_skip_seconds": 5}), + ) + monkeypatch.setattr( + "deerflow.community.boxlite.provider._import_simplebox", + lambda: _FakeBox, + ) + + provider = BoxliteProvider() + provider._loop.run = _fake_run + + sid = provider.acquire("thread-1", user_id="u1") + old = provider.get(sid) + assert old is not None + + slow_mode, entered, gate = threading.Event(), threading.Event(), threading.Event() + + def controlled_run(coro, *, timeout=None): + if slow_mode.is_set(): + coro.close() + entered.set() + gate.wait(10) + raise RuntimeError("vsock disconnected") + return _fake_run(coro, timeout=timeout) + + old._run = controlled_run + slow_mode.set() + result: list[str] = [] + worker = threading.Thread(target=lambda: result.append(old.execute_command("echo slow")), daemon=True) + try: + worker.start() + assert entered.wait(10) # the command is inside the runner + slow_mode.clear() + provider._invalidate_box(sid, "vsock disconnected") # a concurrent failure evicts this generation + provider._loop.run = _fake_run + sid2 = provider.acquire("thread-1", user_id="u1") + replacement = provider.get(sid2) + assert sid2 == sid + assert replacement is not None + assert replacement is not old + gate.set() # the in-flight command now fails terminally + worker.join(10) + assert not worker.is_alive() + assert result == ["Error: vsock disconnected"] + + assert provider.get(sid2) is replacement + assert replacement._closed is False + finally: + gate.set() + worker.join(10) + provider.shutdown() + + def test_acquire_different_threads_dont_reclaim_each_other(monkeypatch): """Thread A's box can't be reclaimed by thread B.""" monkeypatch.setattr(