diff --git a/src/agent_env/providers/sandbox_providers/modal_vm_sandbox.py b/src/agent_env/providers/sandbox_providers/modal_vm_sandbox.py index f54d90f1a..6d804ad6f 100644 --- a/src/agent_env/providers/sandbox_providers/modal_vm_sandbox.py +++ b/src/agent_env/providers/sandbox_providers/modal_vm_sandbox.py @@ -130,6 +130,19 @@ _DISK_IDLE_TIMEOUT_S = 30 * 60 +#: The most bytes of arguments an exec sends as argv; Modal rejects one past ~48 KB. A longer one goes over stdin. +_MAX_EXEC_ARG_BYTES = 32 * 1024 +#: Reads a NUL-separated argv from stdin and runs it, with no input of its own. Linux caps one argument at 128 KiB +#: (MAX_ARG_STRLEN), so a shell's ``-c`` script goes into a file that the shell reads, removes and evals, keeping its $0 +#: and $@. Another program's ``-c`` (python3, say) is left as it is. +_FROM_STDIN = ( + 'mapfile -d "" -t a && ' + 'if [ "${#a[@]}" -ge 3 ] && [ "${a[1]}" = -c ] && case "${a[0]##*/}" in bash|sh) true;; *) false;; esac; then ' + r'f=$(mktemp) && printf %s "${a[2]}" > "$f" && a[2]="eval \"\$(cat -- $f && rm -f -- $f)\""; fi && ' + 'exec "${a[@]}" tuple[int, str, str]: diff --git a/tst/unit/providers/sandbox_providers/modal_vm_sandbox_test.py b/tst/unit/providers/sandbox_providers/modal_vm_sandbox_test.py index 036351aa3..41ddbdaf8 100644 --- a/tst/unit/providers/sandbox_providers/modal_vm_sandbox_test.py +++ b/tst/unit/providers/sandbox_providers/modal_vm_sandbox_test.py @@ -53,6 +53,78 @@ async def fake_exec(*cmd, text=False): assert captured["cmd"] == ("docker", "images") +@pytest.mark.asyncio +async def test_exec_past_modals_arg_limit_sends_the_argv_over_stdin(): + # A parallel load of many signed image URLs runs past Modal's exec limit; the argv goes over stdin instead. + sb = MagicMock() + sb.object_id = "sb-test" + captured: dict = {} + process = MagicMock() + process.stdin.drain.aio = AsyncMock() + + async def fake_exec(*cmd, text=False): + captured["cmd"] = cmd + return process + + sb.exec.aio = fake_exec + script = " & ".join(f"(curl -fsSL 'https://b/img{i}?{'x' * 2400}' | docker load)" for i in range(36)) + " & wait" + await ModalVmSandbox(sb, {}).exec("sudo", "bash", "-c", script) + + assert captured["cmd"] == ("bash", "-c", mvs._FROM_STDIN) + sent = b"".join(call.args[0] for call in process.stdin.write.call_args_list) + assert sent == b"bash\0-c\0" + script.encode() + b"\0" + assert all(len(call.args[0]) <= mvs._MAX_EXEC_ARG_BYTES for call in process.stdin.write.call_args_list) + process.stdin.write_eof.assert_called_once() + + +def _bash_has_mapfile_d() -> bool: + import subprocess + + return subprocess.run(["bash", "-c", 'mapfile -d "" a