fix(sandbox): stop the rest of a cancelled AIO command (#8566)

* fix(sandbox): stop the rest of a cancelled AIO command

The AIO persistent shell and the bash.exec script export the cancel marker
after bash has started, so bash's own /proc environ lacks it. Cleanup
terminated only the marked children, and bash then ran the remaining
statements of a `;`, newline, loop, pipeline or subshell command after the
run was cancelled.

Cleanup now first sends SIGINT to every process in a process group that
contains a marked process, as Ctrl-C would, and then terminates the marked
processes as before. An interactive shell drops the rest of the line and
keeps its cwd and exports; a one-off `bash -c` exits. A process group never
spans sessions, so only the shell session that ran the command is reached.

* test(sandbox): keep persistent-shell teardown quiet when the shell is gone
This commit is contained in:
kongxin 2026-11-25 05:14:08 -08:00 committed by GitHub
parent 5d2f9014c1
commit 6e3746e04e
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 137 additions and 1 deletions

View File

@ -63,6 +63,9 @@ make test-blocking-io
state or a missing cleanup receipt quarantines the sandbox.
- **Cleanup markers support cooperative cleanup.** They do not isolate hostile
code.
- **Cleanup interrupts the marked process groups before it terminates them.**
The shell exported the marker itself, so its own environ lacks it; killing
only the children first lets it run the rest of the command.
- **Broker logs carry argument count, exit code and duration**, never argument
values.
- **`read_file` returns content or an `Error: ...` string and never raises.** A

View File

@ -5,14 +5,54 @@ import shlex
# pidfds keep a recycled PID from receiving a late cancellation signal. Only
# exact inherited execution markers are selected; no command-name matching.
# The shell running the command exported the marker after it started, so its
# own environ lacks it, and terminating only the marked children lets it run
# the rest of the command. Interrupting their process groups first, as Ctrl-C
# would, makes the shell drop the remaining statements: an interactive shell
# keeps its state, and a one-off `bash -c` exits. A process group never spans
# sessions, so this reaches only the shell session that ran the command.
_SCRIPT = r"""import json, os, select, signal, sys, time
probe = os.pidfd_open(os.getpid())
os.close(probe)
needle = b'DEERFLOW_COMMAND_OWNER=' + sys.argv[1].encode('ascii')
def group(name):
with open('/proc/' + name + '/stat', 'rb') as stream:
return int(stream.read().rsplit(b')', 1)[1].split()[2])
def interrupt():
groups = set()
for name in os.listdir('/proc'):
if not name.isdecimal() or int(name) == os.getpid():
continue
try:
with open('/proc/' + name + '/environ', 'rb') as stream:
if needle not in stream.read().split(b'\0'):
continue
groups.add(group(name))
except OSError:
continue
for name in os.listdir('/proc') if groups else ():
if not name.isdecimal() or int(name) == os.getpid():
continue
try:
fd = os.pidfd_open(int(name))
except OSError:
continue
try:
if group(name) in groups:
signal.pidfd_send_signal(fd, signal.SIGINT)
except OSError:
pass
finally:
os.close(fd)
return bool(groups)
deadline = time.monotonic() + 4
stopped = set()
empty = 0
interrupted = False
while time.monotonic() < deadline:
if not interrupted and interrupt():
interrupted = True
time.sleep(0.1)
owned = []
blocked = False
for name in os.listdir('/proc'):

View File

@ -373,6 +373,99 @@ def test_aio_cleanup_does_not_report_success_without_pidfd_support():
assert '"remaining": 0' not in result.stdout
def _marked_process(token: str) -> int:
needle = f"DEERFLOW_COMMAND_OWNER={token}".encode()
for _ in range(1000):
for name in os.listdir("/proc"):
try:
with open(f"/proc/{name}/environ", "rb") as stream:
if needle in stream.read().split(b"\0"):
return int(name)
except (OSError, ValueError):
continue
threading.Event().wait(0.01)
raise AssertionError("marked command did not start")
@pytest.mark.skipif(not sys.platform.startswith("linux") or not hasattr(os, "pidfd_open"), reason="Linux /proc and pidfd")
@pytest.mark.parametrize("job_control", ["-m", "+m"])
def test_aio_cleanup_stops_the_rest_of_a_persistent_shell_command(tmp_path, job_control):
import json
import pty
import uuid
from deerflow.community.aio_sandbox.command_cleanup import cleanup_command
# The AIO persistent shell is an interactive bash on a PTY that exports the
# marker itself, so only its children carry it.
token = uuid.uuid4().hex
shell, terminal = pty.fork()
if shell == 0:
os.execve("/bin/bash", ["bash", "--norc", "--noprofile", "-i", job_control], {"PATH": os.environ["PATH"], "HOME": str(tmp_path), "PS1": "$ ", "TERM": "dumb"})
def drain():
try:
while os.read(terminal, 4096):
pass
except OSError:
pass
threading.Thread(target=drain, daemon=True).start()
state = tmp_path / "state.txt"
try:
os.write(terminal, f"cd {shlex.quote(str(tmp_path))}\nexport DEERFLOW_COMMAND_OWNER={token}; sleep 30; echo tail > tail.txt\n".encode())
_marked_process(token)
command = shlex.split(cleanup_command(token))
receipt = subprocess.run([sys.executable, *command[1:]], capture_output=True, text=True, timeout=15, check=True)
assert json.loads(receipt.stdout)["remaining"] == 0
# The shell reads lines in order, so once it answers this probe the
# cancelled line has either run its tail or been abandoned.
for _ in range(10):
os.write(terminal, b'echo "$PWD|$DEERFLOW_COMMAND_OWNER" > state.txt\n')
for _ in range(100):
if state.exists() and state.read_text().strip():
break
threading.Event().wait(0.01)
else:
continue
break
assert state.exists() and state.read_text().strip() == f"{tmp_path}|{token}", "the shell must survive with its state"
assert not (tmp_path / "tail.txt").exists(), "cancel must stop the rest of the command"
finally:
try:
os.kill(shell, signal.SIGKILL)
os.waitpid(shell, 0)
except (ProcessLookupError, ChildProcessError):
pass
os.close(terminal)
@pytest.mark.skipif(not sys.platform.startswith("linux") or not hasattr(os, "pidfd_open"), reason="Linux /proc and pidfd")
def test_aio_cleanup_stops_the_rest_of_a_one_off_bash_command(tmp_path):
import json
import uuid
from deerflow.community.aio_sandbox.command_cleanup import cleanup_command
# AIO bash.exec runs each env-bearing command as its own `bash -c` session
# without a terminal; the script exports the marker after bash started.
token = uuid.uuid4().hex
script = f"exec < /dev/null\nexport DEERFLOW_COMMAND_OWNER={token}\nsleep 30; echo tail > tail.txt"
shell = subprocess.Popen(["/bin/bash", "-c", script], cwd=tmp_path, start_new_session=True)
try:
_marked_process(token)
command = shlex.split(cleanup_command(token))
receipt = subprocess.run([sys.executable, *command[1:]], capture_output=True, text=True, timeout=15, check=True)
assert json.loads(receipt.stdout)["remaining"] == 0
shell.wait(timeout=10)
assert not (tmp_path / "tail.txt").exists(), "cancel must stop the rest of the command"
finally:
if shell.poll() is None:
shell.kill()
shell.wait()
@pytest.mark.parametrize("case", ["missing-command", "missing-stdout-cursor", "missing-stderr-cursor", "completed-without-cursors", "empty-poll"])
def test_aio_owned_bash_handles_optional_output_fields_without_unsafe_reuse(monkeypatch, case):
from types import SimpleNamespace as N

View File

@ -376,7 +376,7 @@ async with runtime:
Gateway run finalization also retains ownership through caller cancellation: it finishes terminal persistence, stream completion, and resource cleanup before propagating the interruption. Backend I/O must terminate or enforce its own timeout. Gateway shutdown includes workers still finalizing after their terminal status commits; an expired shutdown drain budget is logged and does not cancel their outstanding writes.
Cancelled, replaced, failed or hard-stopped executions stop their owned bash processes before releasing the sandbox lease on AIO and POSIX LocalSandbox, including ordinary `nohup` children. Background services from successful earlier turns remain running. Cleanup tracks inherited execution markers and process groups; it is not a security boundary against scripts deliberately escaping that ownership. Windows LocalSandbox and third-party providers retain their existing behavior.
Cancelled, replaced, failed or hard-stopped executions stop their owned bash processes before releasing the sandbox lease on AIO and POSIX LocalSandbox, including ordinary `nohup` children. On AIO, cleanup first interrupts the cancelled command's process groups the way Ctrl-C does, so the shell skips the rest of a `;`, newline, loop, pipeline or subshell command; the persistent shell keeps its working directory and exports. If the running program ignores or handles that interrupt, the shell runs the next statement once cleanup has stopped the program. Background services from successful earlier turns remain running. Cleanup tracks inherited execution markers and process groups; it is not a security boundary against scripts deliberately escaping that ownership. Windows LocalSandbox and third-party providers retain their existing behavior.
Terminal cleanup releases the run journal and its message-sequence callback even when diagnostic logs retain a checkpoint-inspection traceback.