From d7e3746ea14616cf6c8743a80a7c9e790edaf058 Mon Sep 17 00:00:00 2001 From: Tianyi Cui <53024+tianyicui@users.noreply.github.com> Date: Mon, 5 Oct 2026 18:58:40 +0800 Subject: [PATCH] fix(ptc): preserve Python spawning and CPU soft limits --- ...-ptc-runtime-python-fd3-protocol.i18n.yaml | 4 +- ...6-07-31-ptc-runtime-python-fd3-protocol.md | 2 +- ...7-31-ptc-runtime-python-fd3-protocol.zh.md | 2 +- .../ptc-runtime-python/README.i18n.yaml | 12 +++--- .../experimental/ptc-runtime-python/README.md | 6 +-- .../ptc-runtime-python/README.zh.md | 6 +-- .../ptc-runtime-python/py/bootstrap.py | 21 +++------- .../ptc-runtime-python/src/launch.ts | 5 +-- .../tests/boot-write-failure.spec.ts | 6 +-- .../ptc-runtime-python/tests/runtime.spec.ts | 39 ++++++++++++++++++- .../ptc-runtime-python/tests/sandbox.spec.ts | 23 ++++++++--- 11 files changed, 79 insertions(+), 47 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-07-31-ptc-runtime-python-fd3-protocol.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-31-ptc-runtime-python-fd3-protocol.i18n.yaml index e187778573..b790e7c558 100644 --- a/.agents/notes/implemented/architecture/2026-07-31-ptc-runtime-python-fd3-protocol.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-31-ptc-runtime-python-fd3-protocol.i18n.yaml @@ -12,8 +12,8 @@ en: f0d0d5ba5a9066ad zh: fbdab3731c33eb26 /agent-note-the-ptc-runtime-python-fd-3-frame-protocol/wire-contract: - en: 5f3078d1176014e7 - zh: 4b52aa19cc64fcde + en: 1225a32af91fcf84 + zh: 1dab4ecbd9ff7e34 /agent-note-the-ptc-runtime-python-fd-3-frame-protocol/mirror-alignment: en: 26128b65f2763920 zh: df24359faebcbfed diff --git a/.agents/notes/implemented/architecture/2026-07-31-ptc-runtime-python-fd3-protocol.md b/.agents/notes/implemented/architecture/2026-07-31-ptc-runtime-python-fd3-protocol.md index 3b3e5abfdc..b22ea4cddf 100644 --- a/.agents/notes/implemented/architecture/2026-07-31-ptc-runtime-python-fd3-protocol.md +++ b/.agents/notes/implemented/architecture/2026-07-31-ptc-runtime-python-fd3-protocol.md @@ -26,7 +26,7 @@ The package ships the runtime alongside the protocol; it remains independently b ## Wire contract -Frames are JSON-lines on fd 3, one object per line, leaving stdout/stderr free for the program's own output. Child → host: `boot-ack`, `call`, `log`, `done`. Host → child: `boot` (first frame), `run` (after `boot-ack`), and one `reply` per `call`. The `log` frame's `truncated` flag marks the frame that IS the child ledger's own truncation marker, so the host stops capturing at the same point the child did instead of inferring it from its own budget. The `log` frame's `open` flag marks an unterminated line committed by an explicit flush: the host holds it and appends the next frame to the same entry, so an explicit flush followed by more text reads back as one line rather than a fake newline. The one exception is truncation: when a later over-budget frame trips the ledger, the already-billed prefix is committed as its own entry and the truncation marker follows it (marker last, no re-charge). The merged entry's wire cost is billed exactly once, split incrementally across its fragments on both sides (O(k) for k fragments, never a re-walk of the whole hold): the FIRST fragment pays the full JSON-string cost plus the separator, each continuation and the closing frame pay only their content; the host's exact-cost caps are `logBudget - 1` for a first fragment (the ledger's reserved byte, matching `admit`) and `logBudget + 2` for a continuation or closing frame (billed without the two quotes), and `jsonStringCostUpTo` returns `undefined` below a 2-byte cap; the child keys its split billing off `_open_started` alone, so a closing frame bills as the merged tail. `done.error.kind` is one of `exception`, `invalid-output`, `output-limit`, or CPU `timeout`; wall deadlines, aborts, and substrate death are observed host-side. CPU diagnostics travel on fd 3 because a sandbox launcher can convert signal termination into an ambiguous exit code. These frames remain untrusted outcome reports; kernel resource limits enforce the CPU ceiling independently. +Frames are JSON-lines on fd 3, one object per line, leaving stdout/stderr free for the program's own output. Child → host: `boot-ack`, `call`, `log`, `done`. Host → child: `boot` (first frame), `run` (after `boot-ack`), and one `reply` per `call`. The `log` frame's `truncated` flag marks the frame that IS the child ledger's own truncation marker, so the host stops capturing at the same point the child did instead of inferring it from its own budget. The `log` frame's `open` flag marks an unterminated line committed by an explicit flush: the host holds it and appends the next frame to the same entry, so an explicit flush followed by more text reads back as one line rather than a fake newline. The one exception is truncation: when a later over-budget frame trips the ledger, the already-billed prefix is committed as its own entry and the truncation marker follows it (marker last, no re-charge). The merged entry's wire cost is billed exactly once, split incrementally across its fragments on both sides (O(k) for k fragments, never a re-walk of the whole hold): the FIRST fragment pays the full JSON-string cost plus the separator, each continuation and the closing frame pay only their content; the host's exact-cost caps are `logBudget - 1` for a first fragment (the ledger's reserved byte, matching `admit`) and `logBudget + 2` for a continuation or closing frame (billed without the two quotes), and `jsonStringCostUpTo` returns `undefined` below a 2-byte cap; the child keys its split billing off `_open_started` alone, so a closing frame bills as the merged tail. `done.error.kind` is one of `exception`, `invalid-output`, `output-limit`, or `timeout` from the CPU check after model code returns; wall deadlines, aborts, and substrate death are observed host-side. The post-return CPU check attempts a diagnostic on fd 3 before mandatory signal termination because a sandbox launcher can convert that signal into an ambiguous exit code. Ordinary soft-limit expiry retains default `SIGXCPU` termination without a Python handler, so native calls cannot postpone enforcement until Python resumes. These frames remain untrusted outcome reports; kernel resource limits enforce the CPU ceiling independently. ## Mirror alignment diff --git a/.agents/notes/implemented/architecture/2026-07-31-ptc-runtime-python-fd3-protocol.zh.md b/.agents/notes/implemented/architecture/2026-07-31-ptc-runtime-python-fd3-protocol.zh.md index d13742168c..a8e7ea4ef4 100644 --- a/.agents/notes/implemented/architecture/2026-07-31-ptc-runtime-python-fd3-protocol.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-31-ptc-runtime-python-fd3-protocol.zh.md @@ -26,7 +26,7 @@ CPython PTC 运行时位于 `packages/experimental/ptc-runtime-python`,以 `@d ## Wire contract -帧是 fd 3 上的 JSON-lines,每行一个对象,让 stdout/stderr 空出给程序自己的输出。Child → host:`boot-ack`、`call`、`log`、`done`。Host → child:`boot`(首帧)、`run`(在 `boot-ack` 之后)、以及每个 `call` 对应一个 `reply`。`log` 帧的 `truncated` 标志标记那个本身就是子进程 ledger 截断标记的帧,使 host 在与子进程相同的点停止捕获,而不是从自己的预算去推断。`log` 帧的 `open` 标志标记由显式 flush 提交的未结束行:宿主持有它并把下一个帧追加到同一条目,因此显式 flush 后接更多文本读回为一行而不是假换行。唯一例外是截断:当后续超预算帧触发账本时,已计费的前缀作为独立条目先提交,截断 marker 跟在后面(marker 保持末位,无重复计费)。合并条目的线上成本恰好计费一次,在两侧按片段增量分摊(k 个片段 O(k),绝不对整个持有重走):首片段付完整 JSON 字符串成本加分隔符,每个续接与闭合帧只付内容;宿主精确成本 cap 是首片段 `logBudget - 1`(账本预留字节,与 `admit` 一致)、续接或闭合帧 `logBudget + 2`(不含两个引号计费),且 `jsonStringCostUpTo` 在低于 2 字节 cap 时返回 `undefined`;子进程按 `_open_started` 单独键控拆分计费,因此闭合帧按合并尾部计费。`done.error.kind` 是 `exception`、`invalid-output`、`output-limit` 或 CPU `timeout` 之一;wall 截止、abort 和 substrate 死亡在 host 侧观测。CPU 诊断通过 fd 3 传输,因为沙箱 launcher 可能把信号终止转换为有歧义的退出码。这些帧仍是不可信的结果报告;内核资源限制独立强制执行 CPU 上限。 +帧是 fd 3 上的 JSON-lines,每行一个对象,让 stdout/stderr 空出给程序自己的输出。Child → host:`boot-ack`、`call`、`log`、`done`。Host → child:`boot`(首帧)、`run`(在 `boot-ack` 之后)、以及每个 `call` 对应一个 `reply`。`log` 帧的 `truncated` 标志标记那个本身就是子进程 ledger 截断标记的帧,使 host 在与子进程相同的点停止捕获,而不是从自己的预算去推断。`log` 帧的 `open` 标志标记由显式 flush 提交的未结束行:宿主持有它并把下一个帧追加到同一条目,因此显式 flush 后接更多文本读回为一行而不是假换行。唯一例外是截断:当后续超预算帧触发账本时,已计费的前缀作为独立条目先提交,截断 marker 跟在后面(marker 保持末位,无重复计费)。合并条目的线上成本恰好计费一次,在两侧按片段增量分摊(k 个片段 O(k),绝不对整个持有重走):首片段付完整 JSON 字符串成本加分隔符,每个续接与闭合帧只付内容;宿主精确成本 cap 是首片段 `logBudget - 1`(账本预留字节,与 `admit` 一致)、续接或闭合帧 `logBudget + 2`(不含两个引号计费),且 `jsonStringCostUpTo` 在低于 2 字节 cap 时返回 `undefined`;子进程按 `_open_started` 单独键控拆分计费,因此闭合帧按合并尾部计费。`done.error.kind` 是 `exception`、`invalid-output`、`output-limit` 或模型代码返回后 CPU 检查产生的 `timeout` 之一;wall 截止、abort 和 substrate 死亡在 host 侧观测。返回后的 CPU 检查会在强制信号终止前尝试通过 fd 3 报告诊断,因为沙箱 launcher 可能把该信号转换为有歧义的退出码。普通软限制到期保留默认的 `SIGXCPU` 终止行为,不安装 Python handler,因此原生调用不能把强制执行延后到 Python 恢复运行。这些帧仍是不可信的结果报告;内核资源限制独立强制执行 CPU 上限。 ## Mirror alignment diff --git a/packages/experimental/ptc-runtime-python/README.i18n.yaml b/packages/experimental/ptc-runtime-python/README.i18n.yaml index 4a37d1f34a..8891300eb9 100644 --- a/packages/experimental/ptc-runtime-python/README.i18n.yaml +++ b/packages/experimental/ptc-runtime-python/README.i18n.yaml @@ -30,11 +30,11 @@ en: 7824816505e2b844 zh: 3603d1c332c2ed5d /deepseek-ai-dsh-experimental-ptc-runtime-python/understand-the-implementation/design-concept: - en: a2e806da2fff7fd1 - zh: bfa9b6770a5db4d8 + en: 706fb5750d6e766f + zh: b8f054bffb4c1ff2 /deepseek-ai-dsh-experimental-ptc-runtime-python/understand-the-implementation/wire-contract: - en: 7d96660c891e77ec - zh: f7a8d27e47c34219 + en: 56cb353442d0aa01 + zh: bcb13e5dc761af4a /deepseek-ai-dsh-experimental-ptc-runtime-python/understand-the-implementation/lossless-json-crossing: en: 6252e86fa10e9dd0 zh: 9b95b033ea0b5463 @@ -54,8 +54,8 @@ en: 40294c1c31b74824 zh: d805c6bd7270505e /deepseek-ai-dsh-experimental-ptc-runtime-python/known-limitations-and-deferred-work: - en: b56613c784bbd9f8 - zh: 424a8956f6434b82 + en: 5d62ed07fefbefc4 + zh: 2a03d9bc9265a200 /deepseek-ai-dsh-experimental-ptc-runtime-python/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: 3bb0c20c93f16f98 diff --git a/packages/experimental/ptc-runtime-python/README.md b/packages/experimental/ptc-runtime-python/README.md index d97b5a8e94..179f5a6886 100644 --- a/packages/experimental/ptc-runtime-python/README.md +++ b/packages/experimental/ptc-runtime-python/README.md @@ -67,11 +67,11 @@ This section explains the design behind the backend; observable behavior is full One direction of trust: the host treats every inbound frame as hostile (model code can forge anything on fd 3) and REBUILDS it field by field before reading; the Python side trusts host replies. The bootstrap (`py/bootstrap.py`) runs the program as the body of an async function, so top-level `await` and `return` work; binding calls travel over fd 3 as JSON-lines and replies are paced across the pump so a flood of large replies cannot pin the host's fd-3 write buffer. -The shipped bootstrap and protocol sources reach the interpreter over trusted stdin, independently of sandbox temporary-directory mounts. Model programs and binding traffic use fd 3. The host resolves the sandbox runner before spawning with only `TMPDIR` in the child environment. The wall deadline includes sandbox setup. The configured interpreter's load-time version probe runs outside confinement and executes no model code. +The shipped bootstrap and protocol sources reach the interpreter as UTF-8 JSON on trusted binary stdin, independently of sandbox temporary-directory mounts and locale text encoding. Model programs and binding traffic use fd 3. The host resolves the sandbox runner before spawning with only `TMPDIR` in the child environment. The wall deadline includes sandbox setup. The configured interpreter's load-time version probe runs outside confinement and executes no model code. ### Wire contract -The frames are `boot` / `run` (host → child) and `boot-ack` / `call` / `log` / `done` plus one `reply` per call (child → host). The `log` frame's `truncated` flag marks the frame that IS the child ledger's truncation marker, so the host stops capturing at the same point the child did instead of inferring it from its own budget. The `log` frame's `open` flag marks an unterminated line committed by an explicit flush: the host merges the next log frame into the same entry, so `print('a', end='', flush=True); print('b')` reads back as one `'ab'` entry rather than a fake newline (the split-billing arithmetic lives in the fd-3 protocol Agent Note's wire-contract section). The one exception to merging is truncation: the already-billed prefix is committed as its own entry and the truncation marker follows it (marker last, no re-charge). `done.error.kind` is one of `exception`, `invalid-output`, `output-limit`, or CPU `timeout`; wall deadlines, aborts, and substrate death are observed host-side. +The frames are `boot` / `run` (host → child) and `boot-ack` / `call` / `log` / `done` plus one `reply` per call (child → host). The `log` frame's `truncated` flag marks the frame that IS the child ledger's truncation marker, so the host stops capturing at the same point the child did instead of inferring it from its own budget. The `log` frame's `open` flag marks an unterminated line committed by an explicit flush: the host merges the next log frame into the same entry, so `print('a', end='', flush=True); print('b')` reads back as one `'ab'` entry rather than a fake newline (the split-billing arithmetic lives in the fd-3 protocol Agent Note's wire-contract section). The one exception to merging is truncation: the already-billed prefix is committed as its own entry and the truncation marker follows it (marker last, no re-charge). `done.error.kind` is one of `exception`, `invalid-output`, `output-limit`, or `timeout` from the CPU check after model code returns; wall deadlines, aborts, and substrate death are observed host-side. ### Lossless JSON crossing @@ -142,7 +142,7 @@ These limits define what the package does and does not cover; they are current p - **A child that stops reading its replies settles the run as a worker-exit once the reply backlog passes 1024 frames** — the host writes replies one at a time, waiting for `drain` when the pipe is full; a child that keeps sending calls without consuming replies would otherwise grow the retained backlog (and the binding results it pins) until the wall clock, so the backlog cap fails the run early. Binding results carry no seam-level byte cap, so this is a count bound, not a byte bound. - **A child that floods calls against a binding that never settles settles the run as a worker-exit once 1024 calls are in flight** — binding calls are counted before dispatch and released when the async body settles, so a binding whose promise never resolves would otherwise accumulate one async closure per call frame until the wall clock. Like the reply backlog, this is a count bound, not a byte bound. - **A combined log-and-value peak is not modelled by the load gate** — a model daemon thread that keeps writing while the completion value is metered and framed can add the two peaks in a way no gate admits or rejects; the run dies as `worker-exit`, containment holds, and only the failure classification is degraded. -- **CPU timeout reporting can be unavailable** — the child reports CPU expiry without waiting for a busy or backpressured control channel, then terminates by signal. If a launcher converts that signal to an exit code and no complete timeout frame arrives, the host reports `worker-exit`; an exit code alone does not establish CPU exhaustion. Kernel limits and the wall deadline still apply. +- **CPU signal classification depends on the launcher** — the soft limit retains default `SIGXCPU` termination, including during native calls. A launcher such as bwrap can convert that signal into an ambiguous exit code, reported as `worker-exit`; a directly observed `SIGXCPU` is `timeout`. Only the CPU check after model code returns attempts a `timeout` frame before termination, and a busy or backpressured control channel can prevent that report. Kernel limits and the wall deadline remain in force. - **A 1-second dual-limit `ulimit -t 1` CPU overrun is reported as `worker-exit`, not a timeout** — when the host starts under a hard CPU limit equal to the soft and that limit is 1, `_clamped` cannot lower the soft, so the kernel SIGKILLs the busy loop and SIGXCPU is never delivered; containment holds, only the classification is degraded. - **No byte cap on intermediate binding values** — the implementation remains bounded by the lossless-JSON serialization cost and process memory, and a provider or executor may apply its own fetch cap. diff --git a/packages/experimental/ptc-runtime-python/README.zh.md b/packages/experimental/ptc-runtime-python/README.zh.md index 7dc3b76f1d..74b7d4a35d 100644 --- a/packages/experimental/ptc-runtime-python/README.zh.md +++ b/packages/experimental/ptc-runtime-python/README.zh.md @@ -67,11 +67,11 @@ Each call runs in a fresh Python process. Relative paths use the supplied workin 单向信任:宿主把每条入站帧都视为敌意(模型代码可以在 fd 3 上伪造任何内容)并逐字段重建后才读取;Python 侧信任宿主回复。bootstrap(`py/bootstrap.py`)把程序作为 async 函数体执行,因此顶层 `await` 与 `return` 都可用;binding 调用经 fd 3 以 JSON-lines 往返,回复在 pump 中限速,以免大量大回复钉住宿主的 fd-3 可写缓冲。 -已发布的 bootstrap 与 protocol 源码通过可信 stdin 传入解释器,不依赖沙箱中的临时目录挂载。模型程序与 binding 通信使用 fd 3。宿主在启动前解析沙箱 runner,子进程环境中只保留 `TMPDIR`。经过时间截止包含沙箱准备。所配置解释器的加载期版本探测在约束之外运行,不执行模型代码。 +已发布的 bootstrap 与 protocol 源码以 UTF-8 JSON 通过可信二进制 stdin 传入解释器,不依赖沙箱中的临时目录挂载或 locale 文本编码。模型程序与 binding 通信使用 fd 3。宿主在启动前解析沙箱 runner,子进程环境中只保留 `TMPDIR`。经过时间截止包含沙箱准备。所配置解释器的加载期版本探测在约束之外运行,不执行模型代码。 ### wire 契约 -帧为 `boot`/`run`(宿主 → 子进程)与 `boot-ack`/`call`/`log`/`done` (子进程 → 宿主),以及每个 `call` 对应一个 `reply`(宿主 → 子进程)。`log` 帧的 `truncated` 标志标记的就是子进程账本自己的截断标记帧,因此宿主在与子进程相同的点停止捕获,而不是从自己的预算推断。`log` 帧的 `open` 标志标记由显式 flush 提交的未结束行:宿主把下一个 log 帧合并进同一条目,因此 `print('a', end='', flush=True); print('b')` 读回为一条 `'ab'` 条目而不是假换行(拆分计费算术在 fd-3 协议 Agent Note 的 wire-contract 段)。合并的唯一例外是截断:当后续超预算帧触发账本时,已计费的前缀作为独立条目先提交,截断 marker 跟在后面(marker 保持末位,无重复计费)。`done.error.kind` 为 `exception`、`invalid-output`、`output-limit` 或 CPU `timeout` 之一;墙钟截止、中止与基底死亡在宿主侧观察。 +帧为 `boot`/`run`(宿主 → 子进程)与 `boot-ack`/`call`/`log`/`done` (子进程 → 宿主),以及每个 `call` 对应一个 `reply`(宿主 → 子进程)。`log` 帧的 `truncated` 标志标记的就是子进程账本自己的截断标记帧,因此宿主在与子进程相同的点停止捕获,而不是从自己的预算推断。`log` 帧的 `open` 标志标记由显式 flush 提交的未结束行:宿主把下一个 log 帧合并进同一条目,因此 `print('a', end='', flush=True); print('b')` 读回为一条 `'ab'` 条目而不是假换行(拆分计费算术在 fd-3 协议 Agent Note 的 wire-contract 段)。合并的唯一例外是截断:当后续超预算帧触发账本时,已计费的前缀作为独立条目先提交,截断 marker 跟在后面(marker 保持末位,无重复计费)。`done.error.kind` 为 `exception`、`invalid-output`、`output-limit` 或模型代码返回后 CPU 检查产生的 `timeout` 之一;墙钟截止、中止与基底死亡在宿主侧观察。 ### 无损 JSON 跨越 @@ -142,7 +142,7 @@ Each call runs in a fresh Python process. Relative paths use the supplied workin - **停止读取回复的子进程会在回复积压超过 1024 帧时以 worker-exit 结算运行**——宿主每次写一条回复,管道满时等待 `drain`;只持续发送调用而不消费回复的子进程会让保留的积压(及其钉住的 binding 结果)一直增长到墙钟,因此积压上限让运行提前失败。binding 结果在 seam 层没有字节上限,所以这是计数上限而非字节上限。 - **向永不结算的 binding 洪泛调用的子进程会在 1024 个调用在途时以 worker-exit 结算运行**——binding 调用在分发前计数、异步体结算时释放,否则 promise 永不 resolve 的 binding 会让每个调用帧累积一个异步闭包直到墙钟。与回复积压一样,这是计数上限而非字节上限。 - **组合日志与值的峰值不被加载门建模**——持续写入的模型 daemon 线程与完成值计量、分帧相加的峰值没有任何门会放行或拒绝;运行以 `worker-exit` 告终,隔离成立,只有失败分类降级。 -- **CPU 超时报告可能不可用**——子进程报告 CPU 耗尽时不等待繁忙或反压中的控制通道,随后通过信号终止。如果 launcher 将该信号转换为退出码,且没有完整的 timeout 帧到达,宿主报告 `worker-exit`;仅凭退出码不能判定 CPU 耗尽。内核限制与墙钟截止仍然生效。 +- **CPU 信号的分类取决于 launcher**——软限制保留默认的 `SIGXCPU` 终止行为,包括执行原生调用期间。bwrap 等 launcher 可能将该信号转换为有歧义的退出码,此时报告 `worker-exit`;直接观察到的 `SIGXCPU` 则为 `timeout`。仅模型代码返回后的 CPU 检查会在终止前尝试发送 `timeout` 帧,繁忙或反压中的控制通道可能阻止该报告。内核限制与墙钟截止仍然生效。 - **1 秒双限 `ulimit -t 1` CPU 超限被报告为 `worker-exit` 而非 timeout**——当宿主在一个与软限相等的硬 CPU 限下启动且该限为 1 时,`_clamped` 无法下调软限,内核在同一 tick SIGKILL 忙循环,SIGXCPU 永远不会送达;隔离成立,只有分类降级。 - **中间 binding 值没有字节上限**——实现仍受无损 JSON 序列化成本与进程内存约束,提供方或执行器可能应用自己的获取上限。 diff --git a/packages/experimental/ptc-runtime-python/py/bootstrap.py b/packages/experimental/ptc-runtime-python/py/bootstrap.py index 5b9317f1bd..93de6d72ad 100644 --- a/packages/experimental/ptc-runtime-python/py/bootstrap.py +++ b/packages/experimental/ptc-runtime-python/py/bootstrap.py @@ -1015,17 +1015,6 @@ async def _run(channel: ProtocolChannel) -> None: raise RuntimeError("bootstrap: expected boot frame on fd 3") report_cpu_timeout = _make_cpu_timeout_reporter(channel, boot["cpuSeconds"]) - set_signal, sigxcpu, sig_dfl = signal.signal, signal.SIGXCPU, signal.SIG_DFL - kill, getpid = os.kill, os.getpid - - def on_cpu_limit(_signum: int, _frame: Any) -> None: - try: - report_cpu_timeout() - finally: - set_signal(sigxcpu, sig_dfl) - kill(getpid(), sigxcpu) - - signal.signal(signal.SIGXCPU, on_cpu_limit) # A limit that cannot be applied must fail the run as a diagnosable done # frame, not a bare traceback + exit(1): running the program UNCAPPED would @@ -1037,7 +1026,7 @@ async def _run(channel: ProtocolChannel) -> None: # timeout would otherwise write a large memory-bearing core file into # the workspace. Forbid core dumps first so the timeout path leaves none. resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) - # The soft limit reports CPU expiry before SIGXCPU terminates the child. + # SIG_DFL terminates at the soft limit even inside a long native C call. # Hard limit at +1s is a SIGKILL backstop for a program that traps # SIGXCPU and keeps burning CPU. cpu_soft, cpu_hard = _clamped( @@ -2137,10 +2126,10 @@ def _lossless_json_violation(value: Any) -> str | None: def _make_cpu_timeout_reporter(channel: ProtocolChannel, cpu_seconds: int) -> Any: - """Report CPU expiry before a launcher converts the signal into an exit code. + """Report the post-return CPU check before mandatory SIGXCPU termination. - A busy writer keeps its frame intact: the reporter never waits on a lock - held by the interrupted thread. Signal termination remains the fallback. + Reporting never waits for a busy writer or a backpressured channel. The + caller immediately terminates the process; fd 3 remains nonblocking. """ acquire, release = channel._write_lock.acquire, channel._write_lock.release @@ -2163,7 +2152,7 @@ def _make_cpu_timeout_reporter(channel: ProtocolChannel, cpu_seconds: int) -> An remaining = view_of(payload) while remaining: remaining = remaining[write(fd, remaining):] - except caught as error: + except caught as _error: # Closed or backpressured transport cannot carry the report; termination still runs. pass finally: diff --git a/packages/experimental/ptc-runtime-python/src/launch.ts b/packages/experimental/ptc-runtime-python/src/launch.ts index f2ab92f1ab..d8cdb01e9a 100644 --- a/packages/experimental/ptc-runtime-python/src/launch.ts +++ b/packages/experimental/ptc-runtime-python/src/launch.ts @@ -4,13 +4,12 @@ import { readFileSync } from 'node:fs' /** Small interpreter entry point; bootstrap sources arrive on stdin before model execution. */ export const PYTHON_BOOTSTRAP_LOADER = [ 'import json, sys, types', - '_sources = json.load(sys.stdin)', + '_sources = json.load(sys.stdin.buffer)', '_protocol = types.ModuleType("protocol")', '_protocol.__file__ = ""', 'exec(compile(_sources["protocol"], _protocol.__file__, "exec"), _protocol.__dict__)', 'sys.modules["protocol"] = _protocol', - '__file__ = ""', - 'exec(compile(_sources["bootstrap"], __file__, "exec"), globals())', + 'exec(compile(_sources["bootstrap"], "", "exec"), globals())', ].join('\n') /** diff --git a/packages/experimental/ptc-runtime-python/tests/boot-write-failure.spec.ts b/packages/experimental/ptc-runtime-python/tests/boot-write-failure.spec.ts index e623c82e10..e8d8c70189 100644 --- a/packages/experimental/ptc-runtime-python/tests/boot-write-failure.spec.ts +++ b/packages/experimental/ptc-runtime-python/tests/boot-write-failure.spec.ts @@ -26,10 +26,8 @@ function fakeChildWithThrowingFd3(): EventEmitter { stderr: PassThrough stdio: unknown[] } - // Leave `pid` absent: `finish()` still runs its `clearTimeout(wallTimer)` / - // `removeEventListener(onAbort)` prologue (the TDZ site) before short- - // circuiting on `child.pid === undefined` to `settle` instead of waiting on a - // `close` this fake never emits, so the run resolves promptly. + // An absent pid settles without waiting for a process-close event that this + // pipe fixture does not emit. child.stdout = new PassThrough() child.stderr = new PassThrough() // A duplex whose `write` throws synchronously, standing in for an fd-3 pipe diff --git a/packages/experimental/ptc-runtime-python/tests/runtime.spec.ts b/packages/experimental/ptc-runtime-python/tests/runtime.spec.ts index 40bf64c1bc..139172bbb6 100644 --- a/packages/experimental/ptc-runtime-python/tests/runtime.spec.ts +++ b/packages/experimental/ptc-runtime-python/tests/runtime.spec.ts @@ -580,11 +580,46 @@ describe('PythonPtcRuntime — seam descriptors and misuse', () => { it('delivers packaged Python modules without exposing a writable bootstrap file', async () => { const { runtime } = await setup() const result = await runtime.run(runtime.resolve({ - program: 'import sys, os, protocol\nreturn [sys.modules["__main__"].__file__, protocol.__file__, sys.stdin.read(), os.path.exists(sys.modules["__main__"].__file__)]', + program: 'import sys, protocol\nreturn [hasattr(sys.modules["__main__"], "__file__"), protocol.__file__, sys.stdin.read()]', bindings: [], })) expect(result.error).toBeUndefined() - expect(result.value).toEqual(['', '', '', false]) + expect(result.value).toEqual([false, '', '']) + }) + + it('starts a spawn-context ProcessPoolExecutor with an importable function', async () => { + const { runtime } = await setup({ maxWallMs: 30_000 }) + const result = await runtime.run(runtime.resolve({ + program: [ + 'from concurrent.futures import ProcessPoolExecutor', + 'from multiprocessing import get_context', + 'with ProcessPoolExecutor(max_workers=1, mp_context=get_context("spawn")) as pool:', + ' return pool.submit(abs, -42).result()', + ].join('\n'), + bindings: [], + })) + expect(result.error).toBeUndefined() + expect(result.value).toBe(42) + }) + + it('decodes packaged source as UTF-8 when the interpreter stdin uses ASCII', async () => { + const wrapper = join(await makeTempDir('dsh-python-ascii-'), 'python-ascii') + await writeFile(wrapper, `#!/bin/sh\nLC_ALL=C exec "${PYABS}" -X utf8=0 "$@"\n`, { mode: 0o755 }) + const { runtime } = await setup({ pythonBin: wrapper }) + const result = await runtime.run(runtime.resolve({ program: 'import sys\nreturn [sys.stdin.encoding, "你好"]', bindings: [] })) + expect(result.error).toBeUndefined() + expect(result.value).toEqual(['ascii', '你好']) + }) + + it('preserves the kernel CPU soft limit while Python is executing native C code', async () => { + const { runtime } = await setup({ cpuSeconds: 1, maxWallMs: 30_000 }) + const result = await runtime.run(runtime.resolve({ + program: 'import hashlib\nhashlib.pbkdf2_hmac("sha256", b"password", b"salt", 2147483647)\nreturn "escaped"', + bindings: [], + })) + expect(result.error?.kind).toBe('timeout') + expect(result.error?.message).toContain('CPU time exhausted') + expect(result.value).toBeUndefined() }) it('disposes the first run before any program can outlive its provider', async () => { diff --git a/packages/experimental/ptc-runtime-python/tests/sandbox.spec.ts b/packages/experimental/ptc-runtime-python/tests/sandbox.spec.ts index 16ee1f80d3..a6c7acd6e5 100644 --- a/packages/experimental/ptc-runtime-python/tests/sandbox.spec.ts +++ b/packages/experimental/ptc-runtime-python/tests/sandbox.spec.ts @@ -1,7 +1,7 @@ import { mkdir, mkdtemp, readFile, rm, symlink, writeFile } from 'node:fs/promises' import { homedir } from 'node:os' import { createServer, type Socket } from 'node:net' -import { delimiter, join } from 'node:path' +import { basename, delimiter, join } from 'node:path' import { Context } from '@deepseek-ai/cordis' import Sandbox from '@deepseek-ai/dsh-sandbox-local' import SandboxPolicy from '@deepseek-ai/dsh-sandbox-policy' @@ -221,16 +221,27 @@ describe('Python file sandbox', () => { expect(await readFile(target, 'utf8')).toBe('original') }) - it.skipIf(!sandboxUsable)('preserves CPU exhaustion through the confining launcher', async () => { - const { run } = await setup('read-only', { cpuSeconds: 1, maxWallMs: 30_000 }) + it.skipIf(!sandboxUsable)('reports CPU termination according to the selected launcher signal transport', async () => { + const { ctx, run } = await setup('read-only', { cpuSeconds: 1, maxWallMs: 30_000 }) + const confine = ctx.sandbox.confine.bind(ctx.sandbox) + let mapsSignalsToExitCodes = false + vi.spyOn(ctx.sandbox, 'confine').mockImplementation(async (argv, policy, signal) => { + const result = await confine(argv, policy, signal) + mapsSignalsToExitCodes = basename(result.argv[0]!) === 'bwrap' + return result + }) const result = await run('while True: pass') - expect(result.error?.kind).toBe('timeout') - expect(result.error?.message).toContain('CPU time exhausted') + expect(result.error?.kind).toBe(mapsSignalsToExitCodes ? 'worker-exit' : 'timeout') + expect(result.error?.message).toContain(mapsSignalsToExitCodes ? 'code=152, signal=null' : 'CPU time exhausted') expect(result.sandbox).toMatchObject({ mode: 'read-only', denied: false }) }) it.each([ - { program: 'while True: pass', kind: 'timeout' }, + { program: 'while True: pass', kind: 'worker-exit' }, + { + program: 'import signal,time\nsignal.signal(signal.SIGXCPU, signal.SIG_IGN)\nend = time.process_time() + 1.05\nwhile time.process_time() < end: pass\nreturn "escaped"', + kind: 'timeout', + }, { program: 'import os\nos._exit(152)', kind: 'worker-exit' }, ])('distinguishes CPU exhaustion from a numeric exit behind a signal-mapping launcher: $kind', async ({ program, kind }) => { const { ctx, run } = await setup('read-only', { cpuSeconds: 1, maxWallMs: 30_000 })