Merge remote-tracking branch 'origin/master' into claude/tool-errors-experimental-c89252
# Conflicts: # docs/module-graph.md # docs/module-graph.zh.md # packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts # packages/experimental/cua/README.i18n.yaml # packages/experimental/cua/README.md # packages/experimental/cua/README.zh.md # packages/experimental/cua/package.json # packages/experimental/cua/src/index.ts # packages/experimental/cua/src/native-client.ts # packages/experimental/ptc-runtime-python/README.i18n.yaml # packages/experimental/ptc-runtime-python/src/index.ts # packages/experimental/ptc-runtime-python/tests/runtime.spec.ts # packages/ptc-runtime/ptc-runtime/package.json # packages/ptc-runtime/ptc-runtime/tsconfig.json # pnpm-lock.yaml # snapshots/session/cua-native/session.v4.jsonl # snapshots/session/cua-ptc/session.v4.jsonl
This commit is contained in:
commit
fa96728ee0
994 files changed
+28588
-4228
No files matched your search
@@ -15,14 +15,14 @@
|
||||
en: d152484eb41ac6b4
|
||||
zh: 09388d293f9be9cb
|
||||
/deepseek-ai-dsh-experimental-ptc-runtime-python/use-this-package:
|
||||
en: 8c92675234e417ea
|
||||
zh: 336502466e3c8790
|
||||
en: f101e1349d534a94
|
||||
zh: 42c7352f600e4f59
|
||||
/deepseek-ai-dsh-experimental-ptc-runtime-python/use-this-package/what-you-get:
|
||||
en: ca7b9cc958069c7f
|
||||
zh: 8a4ac72d02ad76eb
|
||||
en: 5e339e8d7c293dd2
|
||||
zh: ff6a86ce83918aa4
|
||||
/deepseek-ai-dsh-experimental-ptc-runtime-python/use-this-package/the-wire:
|
||||
en: e690628dc6197c3b
|
||||
zh: 2b9cdad8b41dcde5
|
||||
en: b15b31d62db5253d
|
||||
zh: 3eec4849570c7916
|
||||
/deepseek-ai-dsh-experimental-ptc-runtime-python/use-this-package/what-can-go-wrong:
|
||||
en: 9a0c3294b510cd22
|
||||
zh: 5635886060044ae3
|
||||
@@ -33,8 +33,8 @@
|
||||
en: 706fb5750d6e766f
|
||||
zh: b8f054bffb4c1ff2
|
||||
/deepseek-ai-dsh-experimental-ptc-runtime-python/understand-the-implementation/wire-contract:
|
||||
en: 56cb353442d0aa01
|
||||
zh: bcb13e5dc761af4a
|
||||
en: 261a827d31bb983e
|
||||
zh: 0590a57d64eaa499
|
||||
/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: 5d62ed07fefbefc4
|
||||
zh: 2a03d9bc9265a200
|
||||
en: 09cd151c631bd9c2
|
||||
zh: 5c9a34fc6b4e9804
|
||||
/deepseek-ai-dsh-experimental-ptc-runtime-python/known-limitations-and-deferred-work/dev-note:
|
||||
en: e67f633dc6fe7773
|
||||
zh: 3bb0c20c93f16f98
|
||||
@@ -27,7 +27,7 @@ Run model-generated Python in a fresh CPython 3.10+ process on macOS or Linux un
|
||||
|
||||
Choose this published experimental package only in an explicit composition. Register `PythonPtcRuntime` beside `dsh-tools`; `run(resolve(request))` executes each program in a fresh CPython 3.10+ subprocess, resolving with `result.value` on success and `result.error` on failure (the orthogonal `PtcRunFailure.kind` taxonomy classifies parse failures, thrown exceptions, invalid completions, output overflows, budget expiry, aborts, unavailable confinement, and substrate death). It rejects only for caller misuse, with `PtcRuntimeError`: `PTC_RUNTIME_INVALID_ARGUMENT` for malformed bindings, a relative `cwd`, or unresolved or unsupported execution options, and `PTC_RUNTIME_UNAVAILABLE` for a call after disposal. Configuration is rejected at load: a non-Unix platform; an explicit `pythonBin` that is not an executable regular file or a bare name that does not resolve on `PATH`; a non-CPython, pre-3.10, or probe-failing interpreter; a non-positive or non-integer budget; a `maxLogBytes` below the truncation-marker floor (64); a timer value `setTimeout` would clamp; a budget larger than the effective fd-3 frame cap (lowered when the host heap cannot safely parse a near-cap frame); or an `addressSpaceMb`/output-budget pair whose worst-case peak would breach `RLIMIT_AS`.
|
||||
|
||||
The composition must supply `sandbox` and `sandboxPolicy` for this local execution host. `resolve(request)` accepts an explicit `sandboxPolicy` or resolves the shared deployment policy, and defaults `cwd` to that policy's workspace root. PTC mode supplies the calling Session's policy and directory. The configured `maxWallMs` remains the execution deadline; explicit `timeoutMs` overrides are unsupported.
|
||||
The composition must supply `sandbox` and `sandboxPolicy` for this local execution host. `resolve(request)` accepts an explicit `sandboxPolicy` or resolves the shared deployment policy, and defaults `cwd` to that policy's workspace root. PTC mode supplies the calling Session's policy and directory. The configured `maxWallMs` remains the execution deadline; explicit `timeoutMs` overrides are unsupported and reject during resolution. Environment initializer registration is unsupported.
|
||||
|
||||
`read-only` and `workspace-write` execute through the configured sandbox provider; `danger-full-access` explicitly bypasses confinement. `result.sandbox` reports the mode, observed denial, and the backend's full or partial enforcement separately from the program outcome. The [sandbox service](../../sandbox/sandbox/README.md) defines the file restrictions and backend limits; these modes do not restrict network access or arbitrary file reads.
|
||||
|
||||
@@ -43,9 +43,13 @@ The program is the body of an async Python function. Top-level await and return
|
||||
|
||||
The package's default export is the `PythonPtcRuntime` plugin. Its public surface also re-exports the host-side protocol vocabulary: `validateChildFrame` (rebuilds every inbound frame), the lossless-JSON codec and meters (`encodeJsonPlain`, `checkDoneValue`, `hasUnsafeIntegerToken`, `hasNonLosslessNumber`), `logTruncationMarker` (the shared truncation-marker text), plus `resolvePythonBin` (interpreter lookup against the current `PATH`), `readProcessStart` (process-start statistics for tests), `detachResidual` (a test seam for the settled run's resource cleanup), and `hostFrameParseCeiling` (the heap-derived frame parse cap a given heap limit admits). Every cap is a validated `Config` field with a default: `cpuSeconds` (60), `maxWallMs` (600000), `addressSpaceMb` (512, not applied on Darwin), `maxLogBytes` (65536), `maxValueBytes` (32768), `graceMs` (3000), and `pythonBin` (`python3`, resolved, executable-checked, version-probed under a five-second force-kill deadline, and frozen at load). Each child receives only `TMPDIR`; ambient credentials, `PATH`, `HOME`, and other host state stay unavailable.
|
||||
|
||||
`resolve` rejects `discardCompletion: true` before starting a Python process. Omitted or false values preserve the program completion.
|
||||
|
||||
`result.output` text entries retain written newlines and unterminated tails; concatenate their `text` fields with `join('')`. `print('a', 'b')` contributes `'a b\n'`, while `sys.stdout.write('a'); sys.stdout.write('b')` contributes `'ab'`. Both the child and host include newline escaping in `maxLogBytes` accounting.
|
||||
|
||||
### The wire
|
||||
|
||||
Frames travel on the child's fd 3 as JSON-lines — one object per line — so stdout/stderr stay clear for the program's own output. Child → host: `boot-ack`, `call`, `log`, `done`. Host → child: `boot` (first frame, carrying every cap and the namespace declarations), `run` (after `boot-ack`, carrying only the program body), and one `reply` per `call`. A forged frame can carry both `value` and `error` on `done`, so a consumer must check `error` first and ignore `value` when it is set. A `log` frame's `open` flag marks an unterminated line committed by an explicit flush: the host appends the next log frame to 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: 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 (the marker stays last, with no re-charge).
|
||||
Frames travel on the child's fd 3 as JSON-lines — one object per line — so stdout/stderr stay clear for the program's own output. Child → host: `boot-ack`, `call`, `log`, `done`. Host → child: `boot` (first frame, carrying every cap and the namespace declarations), `run` (after `boot-ack`, carrying only the program body), and one `reply` per `call`. A forged frame can carry both `value` and `error` on `done`, so a consumer must check `error` first and ignore `value` when it is set. A `log` frame's `open` flag marks an unterminated line committed by an explicit flush: the host appends the next log frame to the same entry, so `print('a', end='', flush=True); print('b')` reads back as one `'ab\n'` entry with its written newline (the split-billing arithmetic lives in the fd-3 protocol Agent Note's wire-contract section). The one exception to merging 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 (the marker stays last, with no re-charge).
|
||||
|
||||
### What can go wrong
|
||||
|
||||
@@ -71,7 +75,7 @@ The shipped bootstrap and protocol sources reach the interpreter as UTF-8 JSON o
|
||||
|
||||
### 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 `timeout` from the CPU check after model code returns; 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\n'` entry with its written 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
|
||||
|
||||
@@ -127,16 +131,16 @@ These limits define what the package does and does not cover; they are current p
|
||||
|
||||
- **The cross-language guard covers the executed surfaces and the frame field shapes, not the field types** — the mirror e2e compares required/optional field sets, not that `cpuSeconds` is an `int` on both sides; a type-level drift is caught by review plus the backend's real-subprocess suite.
|
||||
- **A descendant that escapes the child's process group with `setsid()` is not reaped by the group teardown** — `kill(-pid)` cannot reach it; the run still settles on the value the done frame decided, and the close-deadline backstop forces settlement if the orphan holds the pipes open, but the orphan itself outlives the fiber until it exits on its own.
|
||||
- **A `log` frame that arrives after settlement is dropped** — once the run has settled, host-side capture is closed; a late fd-3 `log` frame (from a thread that outlived the done frame) is discarded rather than appended to `logs`.
|
||||
- **A `log` frame that arrives after settlement is dropped** — once the run has settled, host-side capture is closed; a late fd-3 `log` frame (from a thread that outlived the done frame) is discarded rather than appended to `result.output`.
|
||||
- **A binding REPLY value has no seam-level byte or depth cap** — `maxValueBytes` meters only the done frame's completion value; a wide binding reply is rebuilt host-side (`snapshotJsonValue` traversal) and encoded whole, bounded on both sides only by process memory (like a binding argument, which has no child-side budget either).
|
||||
- **No shipped profile mounts this provider** — the keyless `ptc-python-turn` snapshot replaces the headless PTC runtime through the real Loader; released profiles use the sandboxed Node process backend.
|
||||
- **Workflow execution requires Node** — compositions using this Python provider disable `workflow-ptc`, `tool-workflow`, and `tool-ralph`; the workflow provider rejects an incompatible runtime when loaded.
|
||||
- **Cross-channel log interleaving is backend-dependent** — Python stdout, stderr, and fd-3 log frames travel independently; each channel preserves its own order, while their total order in `result.logs` may differ.
|
||||
- **Cross-channel log interleaving is backend-dependent** — Python stdout, stderr, and fd-3 log frames travel independently; each channel preserves its own order, while their total order in `result.output` may differ.
|
||||
- **CPython 3.10 or newer is required** — the configured executable is resolved and version-probed at load; unsupported interpreters fail before `ctx.ptcRuntime` is registered.
|
||||
- **Execution is local and Unix-only** — the interpreter, working directory, and sandbox runner must belong to the host running this plugin. The provider uses POSIX resource limits and process-group signals; it does not support Windows or remote execution providers.
|
||||
- **Sandbox enforcement inherits backend limits** — a successful program can report partial enforcement, and file confinement does not establish multi-tenant isolation or complete descendant cleanup.
|
||||
- **Diagnostic prefixes omit the package's experimental qualifier** — the marker `[dsh-ptc-runtime-python] log capture truncated at <N> bytes` identifies this provider independently of its npm package name. The protocol mirror verifies identical marker bytes in TypeScript and Python.
|
||||
- **`run()` is one-shot** — `logs` become available only after `PtcRunResult` resolves; there is no streaming-log or progress interface for output produced by a running program.
|
||||
- **`run()` is one-shot** — `output` becomes available only after `PtcRunResult` resolves; there is no streaming-log or progress interface for output produced by a running program.
|
||||
- **No state persists across runs** — every request executes in a fresh subprocess; a persistent REPL-style kernel stays deferred until a backend brings its own logging scheme.
|
||||
- **An fd-3 frame whose raw length exceeds the effective frame parse cap settles the run as a worker-exit** — the cap is 64 MiB, or lower when the host's configured heap cannot safely parse a near-cap frame (`hostFrameParseCeiling`); `maxLogBytes`/`maxValueBytes` are load-bounded to the same cap so an honest child's frames always fit; a model-constructed binding ARGUMENT above the cap (a value with no seam-level budget) trips it too — an accepted residual of the OOM guard.
|
||||
- **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.
|
||||
|
||||
@@ -27,7 +27,7 @@ kind: "package-reference"
|
||||
|
||||
仅在显式组合中选择这个已发布的实验包。将 `PythonPtcRuntime` 与 `dsh-tools` 一起注册后,`run(resolve(request))` 会在全新的 CPython 3.10+ 子进程中执行每个程序;成功时以 `result.value` resolve,失败时以 `result.error` resolve(正交的 `PtcRunFailure.kind` 分类涵盖解析失败、抛出异常、无效完成值、输出溢出、预算到期、中止、约束不可用与执行基底终止)。仅有调用方误用会 reject,错误为 `PtcRuntimeError`:binding 不合法、`cwd` 不是绝对路径、执行选项未解析或不受支持时为 `PTC_RUNTIME_INVALID_ARGUMENT`,在 dispose 后调用时为 `PTC_RUNTIME_UNAVAILABLE`。配置在加载期拒绝:非 Unix 平台;不是可执行普通文件的显式 `pythonBin`,或无法在 `PATH` 上解析的裸名;非 CPython、低于 3.10 或探测失败的解释器;非正或非整数预算;低于截断标记下限(64)的 `maxLogBytes`;会被 `setTimeout` 截断的定时器值;超过有效 fd-3 帧上限的预算(宿主堆无法安全解析接近上限的帧时,该上限会降低);或最坏峰值会突破 `RLIMIT_AS` 的 `addressSpaceMb`/输出预算组合。
|
||||
|
||||
组合必须为此本地执行宿主提供 `sandbox` 和 `sandboxPolicy`。`resolve(request)` 接受显式 `sandboxPolicy`,或解析共享部署策略,并将 `cwd` 默认设为该策略的工作区根目录。PTC mode 提供调用 Session 的策略和目录。配置的 `maxWallMs` 仍是执行截止时间;不支持显式 `timeoutMs` 覆盖。
|
||||
组合必须为此本地执行宿主提供 `sandbox` 和 `sandboxPolicy`。`resolve(request)` 接受显式 `sandboxPolicy`,或解析共享部署策略,并将 `cwd` 默认设为该策略的工作区根目录。PTC mode 提供调用 Session 的策略和目录。配置的 `maxWallMs` 仍是执行截止时间;不支持显式 `timeoutMs` 覆盖,解析时会拒绝。不支持注册环境初始化程序。
|
||||
|
||||
`read-only` 和 `workspace-write` 通过配置的沙箱提供方执行;`danger-full-access` 显式绕过约束。`result.sandbox` 独立于程序结果报告模式、观察到的拒绝,以及后端的完整或部分强制能力。[沙箱服务](../../sandbox/sandbox/README.zh.md)定义文件限制与后端局限;这些模式不限制网络访问或任意文件读取。
|
||||
|
||||
@@ -43,9 +43,13 @@ The program is the body of an async Python function. Top-level await and return
|
||||
|
||||
包的默认导出是 `PythonPtcRuntime` 插件。其公开面还重新导出宿主侧协议词汇:`validateChildFrame`(重建每条入站帧)、无损 JSON codec 与计量器(`encodeJsonPlain`、`checkDoneValue`、`hasUnsafeIntegerToken`、`hasNonLosslessNumber`)、`logTruncationMarker`(共享截断标记文本),以及 `resolvePythonBin`(对照当前 `PATH` 的解释器查找)、`readProcessStart`(供测试用的进程启动统计)、`detachResidual`(已结算运行的资源清理测试 seam)与 `hostFrameParseCeiling`(给定堆上限可容纳的堆推导帧解析上限)。每个上限都是带默认值并经校验的 `Config` 字段:`cpuSeconds`(60)、`maxWallMs`(600000)、`addressSpaceMb`(512,Darwin 上不生效)、`maxLogBytes`(65536)、`maxValueBytes`(32768)、`graceMs`(3000)与 `pythonBin`(`python3`,在加载期解析、检查可执行性,在五秒强制终止期限内探测版本并固定)。每个子进程只接收 `TMPDIR`;环境中的凭证、`PATH`、`HOME` 与其他宿主状态均不可见。
|
||||
|
||||
`resolve` 在启动 Python 进程前拒绝 `discardCompletion: true`。省略该选项或设为 false 时保留程序完成值。
|
||||
|
||||
`result.output` 的文本条目保留实际写入的换行和未换行尾段;用 `join('')` 连接各条目的 `text`。`print('a', 'b')` 输出 `'a b\n'`,而 `sys.stdout.write('a'); sys.stdout.write('b')` 输出 `'ab'`。子进程与宿主都将换行的 JSON 转义开销计入 `maxLogBytes`。
|
||||
|
||||
### wire
|
||||
|
||||
帧在子进程 fd 3 上以 JSON-lines 传输——每行一个对象——因此 stdout/stderr 留给程序自己的输出。子进程 → 宿主:`boot-ack`、`call`、`log`、`done`。宿主 → 子进程:`boot`(首帧,携带全部上限与命名空间声明)、`run`(`boot-ack` 之后,只携带程序体)与每个 `call` 一个 `reply`。伪造帧可在 `done` 上同时携带 `value` 与 `error`,因此消费方必须先检查 `error`,在它存在时忽略 `value`。`log` 帧的 `open` 标志标记由显式 flush 提交的未结束行:宿主把下一个 log 帧追加到同一条目,因此 `print('a', end='', flush=True); print('b')` 读回为一条 `'ab'` 条目而不是假换行(拆分计费算术见 fd-3 协议 Agent Note 的 wire-contract 一节)。合并的唯一例外是截断:当后续超预算帧触发账本时,已计费的前缀作为独立条目先提交,截断 marker 跟在后面(marker 保持末位,无重复计费)。
|
||||
帧在子进程 fd 3 上以 JSON-lines 传输——每行一个对象——因此 stdout/stderr 留给程序自己的输出。子进程 → 宿主:`boot-ack`、`call`、`log`、`done`。宿主 → 子进程:`boot`(首帧,携带全部上限与命名空间声明)、`run`(`boot-ack` 之后,只携带程序体)与每个 `call` 一个 `reply`。伪造帧可在 `done` 上同时携带 `value` 与 `error`,因此消费方必须先检查 `error`,在它存在时忽略 `value`。`log` 帧的 `open` 标志标记由显式 flush 提交的未结束行:宿主把下一个 log 帧追加到同一条目,因此 `print('a', end='', flush=True); print('b')` 读回为一条带有原始换行的 `'ab\n'` 条目(拆分计费算术见 fd-3 协议 Agent Note 的 wire-contract 一节)。合并的唯一例外是截断:当后续超预算帧触发账本时,已计费的前缀作为独立条目先提交,截断 marker 跟在后面(marker 保持末位,无重复计费)。
|
||||
|
||||
### 可能出错的地方
|
||||
|
||||
@@ -71,7 +75,7 @@ The program is the body of an async Python function. Top-level await and return
|
||||
|
||||
### 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\n'` 条目(拆分计费算术在 fd-3 协议 Agent Note 的 wire-contract 段)。合并的唯一例外是截断:当后续超预算帧触发账本时,已计费的前缀作为独立条目先提交,截断 marker 跟在后面(marker 保持末位,无重复计费)。`done.error.kind` 为 `exception`、`invalid-output`、`output-limit` 或模型代码返回后 CPU 检查产生的 `timeout` 之一;墙钟截止、中止与基底死亡在宿主侧观察。
|
||||
|
||||
### 无损 JSON 跨越
|
||||
|
||||
@@ -127,16 +131,16 @@ The program is the body of an async Python function. Top-level await and return
|
||||
|
||||
- **跨语言 guard 覆盖执行的表面与帧字段形状,而非字段类型**——mirror e2e 比较必填/可选字段集,而非 `cpuSeconds` 在两侧是否都是 `int`;类型级漂移由评审加后端的真实子进程套件捕获。
|
||||
- **以 `setsid()` 逃出子进程组后代不被组拆卸回收**——`kill(-pid)` 够不到它;运行仍按 done 帧决定的值结算,若该孤儿持有管道,close 截止兜底会强制结算,但孤儿本身在自行退出前一直存活到 fiber 之外。
|
||||
- **结算后到达的 `log` 帧被丢弃**——运行一旦结算,宿主侧捕获即关闭;迟到的 fd-3 `log` 帧(来自比 done 帧存活更久的线程)会被丢弃,而不是追加到 `logs`。
|
||||
- **结算后到达的 `log` 帧被丢弃**——运行一旦结算,宿主侧捕获即关闭;迟到的 fd-3 `log` 帧(来自比 done 帧存活更久的线程)会被丢弃,而不是追加到 `result.output`。
|
||||
- **binding 回复值没有 seam 级字节或深度上限**——`maxValueBytes` 只计量 done 帧的完成值;宽 binding 回复在宿主侧重建(`snapshotJsonValue` 遍历)并整帧编码,两侧都只受进程内存约束(与没有子进程侧预算的 binding 实参一样)。
|
||||
- **已发布 profile 均不挂载本提供方**——keyless `ptc-python-turn` 快照通过真实 Loader 替换 headless PTC 运行时;已发布 profile 使用沙箱 Node 进程后端。
|
||||
- **工作流执行需要 Node**——使用本 Python 提供方的组合禁用 `workflow-ptc`、`tool-workflow` 和 `tool-ralph`;工作流提供方在加载时拒绝不兼容的运行时。
|
||||
- **跨通道日志交错由后端决定**——Python stdout、stderr 与 fd-3 日志帧彼此独立传输;每个通道保留自身顺序,但它们在 `result.logs` 中的总顺序可能不同。
|
||||
- **跨通道日志交错由后端决定**——Python stdout、stderr 与 fd-3 日志帧彼此独立传输;每个通道保留自身顺序,但它们在 `result.output` 中的总顺序可能不同。
|
||||
- **需要 CPython 3.10 或更高版本**——配置的可执行文件会在加载期完成解析与版本探测;不受支持的解释器会在 `ctx.ptcRuntime` 注册前失败。
|
||||
- **执行限于本地 Unix 宿主**——解释器、工作目录与沙箱 runner 必须位于运行本插件的宿主上。提供方使用 POSIX 资源限制和进程组信号;不支持 Windows 或远程执行提供方。
|
||||
- **沙箱强制能力继承后端限制**——成功的程序也可能报告部分强制能力,文件约束不构成多租户隔离或完整的后代清理保证。
|
||||
- **诊断前缀省略包名中的 experimental 限定词**——标记 `[dsh-ptc-runtime-python] log capture truncated at <N> bytes` 独立于 npm 包名来标识本提供方。协议镜像检查 TypeScript 与 Python 的标记字节完全相同。
|
||||
- **`run()` 是一次性的**——`logs` 只有在 `PtcRunResult` resolve 后才能获得;没有为运行中程序产生的输出提供流式日志或进度接口。
|
||||
- **`run()` 是一次性的**——`output` 只有在 `PtcRunResult` resolve 后才能获得;没有为运行中程序产生的输出提供流式日志或进度接口。
|
||||
- **运行之间不保留状态**——每次请求都在全新子进程中执行;持久 REPL 风格内核在某个后端带来自己的日志方案之前保持延期。
|
||||
- **原始长度超过有效帧解析上限的 fd-3 帧会让本次运行以 worker-exit 结算**——上限为 64 MiB,或当宿主的配置堆无法安全解析接近上限的帧时更低(`hostFrameParseCeiling`);`maxLogBytes`/`maxValueBytes` 在加载期被限制到同一上限,因此诚实子进程的帧总能放得下;模型构造的超过该上限的 binding 实参(一个在 seam 层没有预算的值)会触发同一上限——这是该 OOM 防护的已接受残余。
|
||||
- **停止读取回复的子进程会在回复积压超过 1024 帧时以 worker-exit 结算运行**——宿主每次写一条回复,管道满时等待 `drain`;只持续发送调用而不消费回复的子进程会让保留的积压(及其钉住的 binding 结果)一直增长到墙钟,因此积压上限让运行提前失败。binding 结果在 seam 层没有字节上限,所以这是计数上限而非字节上限。
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh-experimental-ptc-runtime-python",
|
||||
"description": "CPython subprocess implementation of the DeepSeek Harness PTC execution seam",
|
||||
"version": "0.2.2-rc.1",
|
||||
"version": "0.2.2-rc.2",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/deepseek-ai/deepseek-harness.git",
|
||||
|
||||
@@ -215,14 +215,9 @@ class _LogStream(io.TextIOBase):
|
||||
"""A newline-coalescing text stream backed by a :class:`LogBuffer`.
|
||||
|
||||
Installed as ``sys.stdout`` / ``sys.stderr`` before executing the model
|
||||
program. ``print(...)`` calls ``write`` once per argument, separator, and
|
||||
newline, so a raw one-push-per-write stream would emit
|
||||
``["a", " ", "b", "\\n"]`` for ``print("a", "b")`` — and PTC mode renders
|
||||
``logs`` with ``join('\\n')``, turning that into spurious blank lines. This
|
||||
stream instead buffers writes and pushes one LogBuffer entry per completed
|
||||
LINE (the text up to each ``\\n``, newline stripped), so the rendered join
|
||||
reproduces ``a b``. Any unterminated tail is flushed by :meth:`flush_line`
|
||||
after the program settles.
|
||||
program. Writes are buffered into complete lines including their original
|
||||
newline. Explicit flushes and program settlement emit unterminated tails
|
||||
without adding a newline. Each emitted fragment is charged as written.
|
||||
"""
|
||||
|
||||
def __init__(self, logs: LogBuffer) -> None:
|
||||
@@ -290,22 +285,10 @@ class _LogStream(io.TextIOBase):
|
||||
pos = 0
|
||||
if self._pending or self._pending_blocks:
|
||||
newline = text.index("\n")
|
||||
# The +3 cheap-bound overhead (quotes + separator) belongs to a
|
||||
# NEW entry. While an `open` entry is accumulating, the closing
|
||||
# line is that entry's TAIL: its cheap bound is the content
|
||||
# length alone, matching `_push_locked`'s open-aware bound.
|
||||
# This bound's observable behavior is invariant under the
|
||||
# overhead either way: when the +3 form trips and the open-aware
|
||||
# form does not (pending + newline in [remaining - 2, remaining]),
|
||||
# _push_bounded_prefix re-slices the SAME line text (the extra
|
||||
# slice `text[:newline]` carries no newline) and _push_locked
|
||||
# admits it under the same open-aware billing, byte for byte.
|
||||
# The open-aware form only keeps _push_bounded_prefix's "certain
|
||||
# to reject" precondition true, which is exactly what the scan
|
||||
# pre-check below does NOT preserve (its slice carries the
|
||||
# newline, so push genuinely rejects and truncates).
|
||||
# A complete line includes its newline. New entries also pay
|
||||
# the quotes and separator; open entries already paid them.
|
||||
overhead = 3 if not self._logs._open_started else 0
|
||||
if self._pending_chars + newline + overhead > self._logs.remaining:
|
||||
if self._pending_chars + newline + 1 + overhead > self._logs.remaining:
|
||||
# The reconstructed first line cannot fit the ledger, so
|
||||
# LogBuffer would reject it whole: copy only the prefix that
|
||||
# fails its cheap bound and drop the chunks. The slice is
|
||||
@@ -314,9 +297,9 @@ class _LogStream(io.TextIOBase):
|
||||
# join was (measured: MemoryError inside `sys.stdout.write`
|
||||
# under a 400 MiB addressSpaceMb), and `remaining + 4`
|
||||
# characters are all the helper can use.
|
||||
self._push_bounded_prefix(text[: min(newline, self._logs.remaining + 4)])
|
||||
self._push_bounded_prefix(text[: min(newline + 1, self._logs.remaining + 4)])
|
||||
else:
|
||||
self._pending.append(text[:newline])
|
||||
self._pending.append(text[:newline + 1])
|
||||
line = "".join(self._pending_parts())
|
||||
self._pending = []
|
||||
self._pending_blocks = []
|
||||
@@ -341,10 +324,10 @@ class _LogStream(io.TextIOBase):
|
||||
# prefix is longer than `remaining`), so the marker is emitted
|
||||
# and the oversized line is never materialized.
|
||||
overhead = 3 if not self._logs._open_started else 0
|
||||
if newline - pos + overhead > self._logs.remaining:
|
||||
if newline - pos + 1 + overhead > self._logs.remaining:
|
||||
self._logs.push(text[pos:pos + self._logs.remaining + 4])
|
||||
break
|
||||
self._logs.push(text[pos:newline])
|
||||
self._logs.push(text[pos:newline + 1])
|
||||
pos = newline + 1
|
||||
if pos < length:
|
||||
if self._logs.remaining > 0:
|
||||
@@ -368,14 +351,8 @@ class _LogStream(io.TextIOBase):
|
||||
# cheap length lower bound rejects immediately, emits the
|
||||
# marker, and never encodes the tail — and a push after the
|
||||
# marker is already out returns without emitting a second.
|
||||
# Reaching 0 EXACTLY (65 one-character lines against the
|
||||
# default 3-byte-per-entry serialized charge) leaves
|
||||
# `_truncated` unset, so without this the tail vanished with
|
||||
# no marker at all. Sliced to a budget-sized prefix, not the
|
||||
# whole tail: the tail can be hundreds of megabytes and the
|
||||
# copy would be the RLIMIT_AS death this bound exists to
|
||||
# avoid, while push only needs enough characters to fail its
|
||||
# own cheap length check.
|
||||
# Keep the rejected prefix bounded even when the unscanned
|
||||
# tail is much larger than the output budget.
|
||||
self._logs.push(text[pos:pos + self._logs.remaining + 4])
|
||||
else:
|
||||
self._pending.append(text)
|
||||
@@ -476,9 +453,8 @@ class _LogStream(io.TextIOBase):
|
||||
self._pending = []
|
||||
self._pending_blocks = []
|
||||
self._pending_chars = 0
|
||||
# The line has NO trailing newline: mark the frame `open` so the
|
||||
# host appends the next log frame to the same entry instead of
|
||||
# inserting a fake newline between two entries.
|
||||
# Keep unterminated fragments in the same billed entry across
|
||||
# explicit flushes and the next newline-terminated write.
|
||||
self._logs.push(line, open=True)
|
||||
|
||||
|
||||
|
||||
@@ -223,7 +223,7 @@ const CLOSE_REAP_MARGIN_MS = 2_000
|
||||
* of astral characters is ~4x the budget in each string that holds it. The
|
||||
* heaviest path holds THREE such copies at once: a single
|
||||
* `sys.stdout.write(line + "\n")` keeps the caller's `text` argument (alive for
|
||||
* the whole `write` call, ~4x), the line slice `text[pos:newline]` handed to
|
||||
* the whole `write` call, ~4x), the line slice `text[pos:newline + 1]` handed to
|
||||
* `LogBuffer.push` (~4x), and the `text.encode("utf-8")` copy `_push_locked`
|
||||
* takes to charge and ship it (~4x). The settlement `flush_line` path holds only
|
||||
* two (its `"".join(...)` and that encode copy — it drops the pending chunks
|
||||
@@ -972,13 +972,14 @@ export class PythonPtcRuntime extends PtcRuntime {
|
||||
|
||||
/**
|
||||
* Resolve authority, directory, and the configured wall deadline.
|
||||
* @param request - Program inputs and optional resolved sandbox authority; timeout overrides are unsupported.
|
||||
* @param request - Program inputs and optional resolved sandbox authority.
|
||||
* @returns Complete inputs for the provider's run method.
|
||||
* @throws When a requested timeout is unsupported, cwd is relative, or the provider is disposed.
|
||||
* @throws When a requested timeout or completion-discard option is unsupported, cwd is relative, or the provider is disposed.
|
||||
*/
|
||||
resolve(request: PtcRunRequest): PtcRunSpec {
|
||||
if (this.disposed) throw new PtcRuntimeError('dsh-ptc-runtime-python: resolve() after disposal', 'PTC_RUNTIME_UNAVAILABLE')
|
||||
if (request.timeoutMs !== undefined) throw new PtcRuntimeError('dsh-ptc-runtime-python: per-call timeout is unsupported', 'PTC_RUNTIME_INVALID_ARGUMENT')
|
||||
if (request.discardCompletion === true) throw new PtcRuntimeError('dsh-ptc-runtime-python: discardCompletion is unsupported', 'PTC_RUNTIME_INVALID_ARGUMENT')
|
||||
const sandboxPolicy = request.sandboxPolicy ?? this.ctx.sandboxPolicy.resolve()
|
||||
const cwd = request.cwd ?? sandboxPolicy.workspaceRoot
|
||||
if (!isAbsolute(cwd)) throw new PtcRuntimeError('dsh-ptc-runtime-python: cwd must be absolute', 'PTC_RUNTIME_INVALID_ARGUMENT')
|
||||
@@ -1021,7 +1022,7 @@ export class PythonPtcRuntime extends PtcRuntime {
|
||||
try {
|
||||
input = bootstrapInput()
|
||||
} catch (error: unknown) {
|
||||
return { logs: [], sandbox, error: { kind: 'worker-exit', message: `failed to read the python bootstrap: ${messageOf(error)}` } }
|
||||
return { output: [], sandbox, error: { kind: 'worker-exit', message: `failed to read the python bootstrap: ${messageOf(error)}` } }
|
||||
}
|
||||
let confined: ConfinedArgv | undefined
|
||||
// Unbuffered native output stays observable before process-group teardown.
|
||||
@@ -1044,7 +1045,7 @@ export class PythonPtcRuntime extends PtcRuntime {
|
||||
return await pending
|
||||
} catch (error: unknown) {
|
||||
return {
|
||||
logs: [], sandbox,
|
||||
output: [], sandbox,
|
||||
error: controller.signal.aborted ? controller.signal.reason as PtcRunFailure
|
||||
: { kind: error instanceof SandboxUnavailableError ? 'sandbox-unavailable' : 'worker-exit', message: messageOf(error) },
|
||||
}
|
||||
@@ -1175,7 +1176,7 @@ export class PythonPtcRuntime extends PtcRuntime {
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
complete()
|
||||
return Promise.resolve({ logs: [], sandbox, error: {
|
||||
return Promise.resolve({ output: [], sandbox, error: {
|
||||
kind: confined !== undefined && isRunnerSpawnFailure(error, argv[0], request.cwd) ? 'sandbox-unavailable' : 'worker-exit',
|
||||
message: `python spawn error: ${messageOf(error)}`,
|
||||
} })
|
||||
@@ -1289,13 +1290,8 @@ export class PythonPtcRuntime extends PtcRuntime {
|
||||
// Stray-byte capture: anything the child writes to its stdout/stderr
|
||||
// (native prints, C-extension writes) still counts against the ledger.
|
||||
//
|
||||
// Output is admitted per LINE, not per transport chunk. `logs` entries
|
||||
// are joined with `\n` downstream (PTC mode), so each entry must be one
|
||||
// line: pushing a raw `data` chunk would turn every arbitrary pipe-read
|
||||
// boundary into a model-visible newline, so a single 200 KiB native write
|
||||
// split across pipe reads would read back with spurious line breaks. The
|
||||
// child's own `log` frames are already line-granular; stray capture
|
||||
// matches them by splitting on `\n`.
|
||||
// Complete lines retain their newline; final residuals retain their
|
||||
// unterminated text. Transport chunk boundaries do not add separators.
|
||||
//
|
||||
// Buffered as raw `Buffer` chunks with a running SERIALIZED-cost counter,
|
||||
// exactly like the fd-3 reader below and for the same reasons: a string
|
||||
@@ -1339,7 +1335,7 @@ export class PythonPtcRuntime extends PtcRuntime {
|
||||
stray.blocks = []
|
||||
let newline: number
|
||||
while ((newline = buffered.indexOf(0x0a)) >= 0) {
|
||||
admit(buffered.subarray(0, newline).toString('utf8'))
|
||||
admit(buffered.subarray(0, newline + 1).toString('utf8'))
|
||||
buffered = buffered.subarray(newline + 1)
|
||||
}
|
||||
// Carry the residual as a fresh right-sized copy, not the subarray view
|
||||
@@ -1445,8 +1441,8 @@ export class PythonPtcRuntime extends PtcRuntime {
|
||||
stray.blocks = []
|
||||
// Do not admit an EMPTY entry: when the whole residual is a single
|
||||
// unfinished multibyte sequence, `full` was drained into `keep` and no
|
||||
// complete byte stream remains to admit. `admit('')` would push a
|
||||
// model-visible bogus empty line (logs are joined with '\n' downstream).
|
||||
// complete byte stream remains to admit. `admit('')` would push an
|
||||
// empty output entry whose wrapper would consume the ledger.
|
||||
if (full.length > 0) admit(full.toString('utf8'))
|
||||
} else {
|
||||
stray.chunks = []
|
||||
@@ -2146,16 +2142,16 @@ export class PythonPtcRuntime extends PtcRuntime {
|
||||
let resolved = false
|
||||
// The decided terminal result for a live child, recorded by finish() and
|
||||
// read by the `close` handler that settles it once the pipes have drained.
|
||||
let decided: Omit<PtcRunResult, 'logs'>
|
||||
let decided: Omit<PtcRunResult, 'output'>
|
||||
|
||||
// The single settlement point: resolve run() with the decided result and
|
||||
// mark the fiber quiescent. Idempotent — the first call wins, so a later
|
||||
// `close` after done/timeout/abort is absorbed as a no-op.
|
||||
const settle = (result: Omit<PtcRunResult, 'logs'>): void => {
|
||||
const settle = (result: Omit<PtcRunResult, 'output'>): void => {
|
||||
if (resolved) return
|
||||
resolved = true
|
||||
if (closeDeadline !== undefined) clearTimeout(closeDeadline)
|
||||
resolve({ ...result, logs, sandbox: { ...sandbox } })
|
||||
resolve({ ...result, output: logs.map(text => ({ type: 'text', text })), sandbox: { ...sandbox } })
|
||||
// Mark the fiber quiescent for THIS run: drop it from `live` and resolve
|
||||
// `finished` (what teardown awaits). Deferred until the process group is
|
||||
// actually empty — dropping from `live` before then would let a
|
||||
@@ -2239,7 +2235,7 @@ export class PythonPtcRuntime extends PtcRuntime {
|
||||
pollGroup()
|
||||
}
|
||||
|
||||
const finish = (result: Omit<PtcRunResult, 'logs'>): void => {
|
||||
const finish = (result: Omit<PtcRunResult, 'output'>): void => {
|
||||
if (settled) return
|
||||
settled = true
|
||||
decided = result
|
||||
|
||||
@@ -88,6 +88,9 @@ describe('PythonPtcRuntime — seam descriptors and misuse', () => {
|
||||
expect(() => runtime.resolve({ ...request, cwd: 'relative' })).toThrow(expect.objectContaining({ name: 'PtcRuntimeError', code: 'PTC_RUNTIME_INVALID_ARGUMENT', message: expect.stringContaining('cwd must be absolute') as string }))
|
||||
expect(() => runtime.resolve({ ...request, timeoutMs: 1 })).toThrow(expect.objectContaining({ name: 'PtcRuntimeError', code: 'PTC_RUNTIME_INVALID_ARGUMENT', message: expect.stringContaining('per-call timeout is unsupported') as string }))
|
||||
expect(() => runtime.resolve({ ...request, timeoutMs: null })).toThrow(expect.objectContaining({ name: 'PtcRuntimeError', code: 'PTC_RUNTIME_INVALID_ARGUMENT', message: expect.stringContaining('per-call timeout is unsupported') as string }))
|
||||
expect(() => runtime.resolve({ ...request, discardCompletion: true })).toThrow(expect.objectContaining({ name: 'PtcRuntimeError', code: 'PTC_RUNTIME_INVALID_ARGUMENT', message: expect.stringContaining('discardCompletion is unsupported') as string }))
|
||||
expect(runtime.resolve({ ...request, discardCompletion: false }).discardCompletion).toBe(false)
|
||||
expect(() => runtime.registerEnvironmentInitializer('helper = {}')).toThrow('environment initialization is unsupported')
|
||||
const sandboxPolicy = { mode: 'danger-full-access' as const, workspaceRoot: cwd }
|
||||
expect(runtime.resolve({ ...request, sandboxPolicy }).sandboxPolicy).toBe(sandboxPolicy)
|
||||
await expect(runtime.run({ ...request, cwd, timeoutMs: 30_000 })).rejects.toThrow(expect.objectContaining({ name: 'PtcRuntimeError', code: 'PTC_RUNTIME_INVALID_ARGUMENT', message: expect.stringContaining('run requires a resolved sandbox policy') as string }))
|
||||
@@ -560,7 +563,7 @@ describe('PythonPtcRuntime — seam descriptors and misuse', () => {
|
||||
const result = await runtime.run(runtime.resolve({ program: 'return 1', bindings: [], signal }))
|
||||
expect(result.error?.kind).toBe('abort')
|
||||
expect(result.error?.message).toContain('already-cancelled')
|
||||
expect(result.logs).toEqual([])
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text)).toEqual([])
|
||||
})
|
||||
|
||||
it('short-circuits on an already-aborted signal whose reason cannot be converted', async () => {
|
||||
@@ -574,7 +577,7 @@ describe('PythonPtcRuntime — seam descriptors and misuse', () => {
|
||||
const result = await runtime.run(runtime.resolve({ program: 'return 1', bindings: [], signal }))
|
||||
expect(result.error?.kind).toBe('abort')
|
||||
expect(result.error?.message).toBe('<unrenderable rejection value>')
|
||||
expect(result.logs).toEqual([])
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text)).toEqual([])
|
||||
})
|
||||
|
||||
it('delivers packaged Python modules without exposing a writable bootstrap file', async () => {
|
||||
@@ -669,7 +672,7 @@ describe('PythonPtcRuntime — seam descriptors and misuse', () => {
|
||||
const result = await runtime.run(runtime.resolve({ program: 'return 42', bindings: [] }))
|
||||
expect(result.error?.kind).toBe('worker-exit')
|
||||
expect(result.error?.message).toContain('failed to read the python bootstrap')
|
||||
expect(result.logs).toEqual([])
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text)).toEqual([])
|
||||
expect(result.value).toBeUndefined()
|
||||
} finally {
|
||||
failNextReadOf.value = undefined
|
||||
@@ -970,7 +973,7 @@ describe('PythonPtcRuntime — programs and bindings', () => {
|
||||
expect(result.value).toEqual({ answer: 42 })
|
||||
// `print` in Python emits: text, ' ', text, '\n'. Concat the captured
|
||||
// fragments and assert the model-visible message survives.
|
||||
expect(result.logs.join('')).toContain('hello 42')
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text).join('')).toContain('hello 42')
|
||||
// 15s: this is usually the suite's first real subprocess — a cold python3
|
||||
// start (interpreter + asyncio import) on a loaded CI runner can exceed
|
||||
// the 5s default alone; later tests reuse the warm page cache.
|
||||
@@ -992,7 +995,7 @@ describe('PythonPtcRuntime — programs and bindings', () => {
|
||||
}))
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(result.value).toEqual({ tmpdir: tmpdir(), path: null, home: null, token: null })
|
||||
expect(result.logs).toEqual([])
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text)).toEqual([])
|
||||
})
|
||||
|
||||
it('bridges binding calls both ways and rejects the program-side call on a host rejection', async () => {
|
||||
@@ -1257,17 +1260,42 @@ describe('PythonPtcRuntime — programs and bindings', () => {
|
||||
expect(result.value).toBeUndefined()
|
||||
})
|
||||
|
||||
it('coalesces print arguments into one log line, not per-write fragments', async () => {
|
||||
// print("a","b") calls write() per arg/sep/newline; the stream must emit
|
||||
// one logical line "a b" so PTC mode's join(newline) does not insert
|
||||
// spurious blank lines. Two prints → exactly two entries, no empties.
|
||||
it.each([
|
||||
['print arguments', 'print("a", "b")', 'a b\n'],
|
||||
['raw writes', 'import sys; sys.stdout.write("a"); sys.stdout.write("b")', 'ab'],
|
||||
['native newlines', 'import os; os.write(1, b"one\\ntwo\\ntail")', 'one\ntwo\ntail'],
|
||||
['blank lines and trailing text', 'import sys; print(); print("a"); print(); sys.stdout.write("tail")', '\na\n\ntail'],
|
||||
])('preserves raw output from %s', async (_name, program, expected) => {
|
||||
const { runtime } = await setup()
|
||||
const result = await runtime.run(runtime.resolve({ program, bindings: [] }))
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text).join('')).toBe(expected)
|
||||
})
|
||||
|
||||
it.each(['python', 'native'])('charges written newlines at the exact output cap for %s writes', async (channel) => {
|
||||
const { runtime } = await setup({ maxLogBytes: 64 })
|
||||
const program = (length: number): string => channel === 'python'
|
||||
? `print("a" * ${length})`
|
||||
: `import os; os.write(1, b"a" * ${length} + b"\\n")`
|
||||
const exact = await runtime.run(runtime.resolve({ program: program(58), bindings: [] }))
|
||||
const text = exact.output.filter(block => block.type === 'text').map(block => block.text)
|
||||
expect(exact.error).toBeUndefined()
|
||||
expect(text).toEqual(['a'.repeat(58) + '\n'])
|
||||
expect(Buffer.byteLength(JSON.stringify(text))).toBe(64)
|
||||
const over = await runtime.run(runtime.resolve({ program: program(59), bindings: [] }))
|
||||
expect(over.error).toBeUndefined()
|
||||
expect(over.output.filter(block => block.type === 'text').map(block => block.text)).toEqual([logTruncationMarker(64)])
|
||||
})
|
||||
|
||||
it('coalesces print arguments and retains each written newline', async () => {
|
||||
// Per-argument writes coalesce without dropping the terminating newline.
|
||||
const { runtime } = await setup()
|
||||
const result = await runtime.run(runtime.resolve({
|
||||
program: ['print("a", "b")', 'print("c")', 'return None'].join('\n'),
|
||||
bindings: [],
|
||||
}))
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(result.logs).toEqual(['a b', 'c'])
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text)).toEqual(['a b\n', 'c\n'])
|
||||
})
|
||||
|
||||
it('flushes a print with no trailing newline', async () => {
|
||||
@@ -1277,14 +1305,12 @@ describe('PythonPtcRuntime — programs and bindings', () => {
|
||||
bindings: [],
|
||||
}))
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(result.logs).toEqual(['partial'])
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text)).toEqual(['partial'])
|
||||
})
|
||||
|
||||
it('aggregates a large newline-free native write into one log entry, not one per pipe chunk', async () => {
|
||||
// A single `os.write` larger than one pipe read arrives as several Node
|
||||
// `data` chunks. `logs` entries are joined with `\n` downstream, so pushing
|
||||
// one entry per transport chunk would insert model-visible newlines at
|
||||
// arbitrary pipe boundaries inside one native write. Stray capture holds a
|
||||
// `data` chunks. Stray capture holds a
|
||||
// per-stream residual and admits only on a real `\n`, so a 200 KiB blast
|
||||
// with no newline reads back as exactly one entry with no interior breaks.
|
||||
const { runtime } = await setup({ maxLogBytes: 300_000 })
|
||||
@@ -1294,7 +1320,7 @@ describe('PythonPtcRuntime — programs and bindings', () => {
|
||||
bindings: [],
|
||||
}))
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(result.logs).toEqual(['A'.repeat(size)])
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text)).toEqual(['A'.repeat(size)])
|
||||
})
|
||||
|
||||
it('splits native output on its own newlines, one entry per line', async () => {
|
||||
@@ -1306,7 +1332,7 @@ describe('PythonPtcRuntime — programs and bindings', () => {
|
||||
bindings: [],
|
||||
}))
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(result.logs).toEqual(['one', 'two', 'three'])
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text)).toEqual(['one\n', 'two\n', 'three'])
|
||||
})
|
||||
|
||||
it('preserves each native stream order while allowing backend-dependent interleaving', async () => {
|
||||
@@ -1323,8 +1349,8 @@ describe('PythonPtcRuntime — programs and bindings', () => {
|
||||
bindings: [],
|
||||
}))
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(result.logs.indexOf('stdout-one')).toBeLessThan(result.logs.indexOf('stdout-two'))
|
||||
expect(result.logs.indexOf('stderr-one')).toBeLessThan(result.logs.indexOf('stderr-two'))
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text).indexOf('stdout-one\n')).toBeLessThan(result.output.filter(block => block.type === 'text').map(block => block.text).indexOf('stdout-two\n'))
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text).indexOf('stderr-one\n')).toBeLessThan(result.output.filter(block => block.type === 'text').map(block => block.text).indexOf('stderr-two\n'))
|
||||
})
|
||||
|
||||
it('bounds a newline-free native flood by the ledger instead of buffering it whole', async () => {
|
||||
@@ -1340,9 +1366,9 @@ describe('PythonPtcRuntime — programs and bindings', () => {
|
||||
bindings: [],
|
||||
}))
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(result.logs.at(-1)).toBe(logTruncationMarker(4096))
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text).at(-1)).toBe(logTruncationMarker(4096))
|
||||
// The retained output is bounded by the budget, not the 2 MB flood.
|
||||
expect(result.logs.join('').length).toBeLessThan(4096)
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text).join('').length).toBeLessThan(4096)
|
||||
})
|
||||
|
||||
it('bounds a newline-free single-character Python write drip by the fragment cap, not OOM', async () => {
|
||||
@@ -1367,7 +1393,7 @@ describe('PythonPtcRuntime — programs and bindings', () => {
|
||||
bindings: [],
|
||||
}))
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(result.logs.at(-1)).toBe(logTruncationMarker(4096))
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text).at(-1)).toBe(logTruncationMarker(4096))
|
||||
})
|
||||
|
||||
it('bounds a control-char-dense native residual by serialized cost, not raw length', async () => {
|
||||
@@ -1385,7 +1411,7 @@ describe('PythonPtcRuntime — programs and bindings', () => {
|
||||
bindings: [],
|
||||
}))
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(result.logs.at(-1)).toBe(logTruncationMarker(4096))
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text).at(-1)).toBe(logTruncationMarker(4096))
|
||||
})
|
||||
|
||||
it('rejects an output budget that could breach addressSpaceMb during encode at load', async () => {
|
||||
@@ -1458,7 +1484,7 @@ describe('PythonPtcRuntime — programs and bindings', () => {
|
||||
bindings: [],
|
||||
}))
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(result.logs.at(-1)).toBe(logTruncationMarker(4096))
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text).at(-1)).toBe(logTruncationMarker(4096))
|
||||
})
|
||||
|
||||
it('drops a second stray line in the same chunk once the first truncated the ledger', async () => {
|
||||
@@ -1477,8 +1503,8 @@ describe('PythonPtcRuntime — programs and bindings', () => {
|
||||
bindings: [],
|
||||
}))
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(result.logs.at(-1)).toBe(logTruncationMarker(64))
|
||||
expect(result.logs.join('\n')).not.toContain('SECOND')
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text).at(-1)).toBe(logTruncationMarker(64))
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text).join('')).not.toContain('SECOND')
|
||||
})
|
||||
|
||||
it('charges a broken multibyte sequence its U+FFFD bytes, split across pipe chunks', async () => {
|
||||
@@ -1500,8 +1526,8 @@ describe('PythonPtcRuntime — programs and bindings', () => {
|
||||
bindings: [],
|
||||
}))
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(result.logs.join('')).toContain('A')
|
||||
expect(result.logs.join('')).toContain('�')
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text).join('')).toContain('A')
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text).join('')).toContain('�')
|
||||
})
|
||||
|
||||
it('charges the exact serialized cost of short-escape and quote/backslash characters', async () => {
|
||||
@@ -1517,7 +1543,7 @@ describe('PythonPtcRuntime — programs and bindings', () => {
|
||||
bindings: [],
|
||||
}))
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(result.logs).toEqual(['\ta"b\\c\x01é'])
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text)).toEqual(['\ta"b\\c\x01é\n'])
|
||||
})
|
||||
|
||||
it('fails a completion dict with a non-string key as invalid-output (no key coercion)', async () => {
|
||||
@@ -2048,11 +2074,7 @@ describe('PythonPtcRuntime — programs and bindings', () => {
|
||||
}, 90_000)
|
||||
|
||||
it('appends a flushed unterminated line to the next entry without a fake newline', async () => {
|
||||
// An explicit flush of an unterminated line (print(..., end='', flush=True))
|
||||
// used to push a full log frame, so the following print() landed in a
|
||||
// SECOND entry and logs.join('\n') rendered 'a\nb' for what the program
|
||||
// printed as one line. The flush frame now carries `open: true` and the
|
||||
// host appends the next frame to the same entry.
|
||||
// Explicitly flushed text and the closing newline share one billed entry.
|
||||
const { runtime } = await setup()
|
||||
const result = await runtime.run(runtime.resolve({
|
||||
program: [
|
||||
@@ -2063,7 +2085,7 @@ describe('PythonPtcRuntime — programs and bindings', () => {
|
||||
bindings: [],
|
||||
}))
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(result.logs).toEqual(['ab'])
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text)).toEqual(['ab\n'])
|
||||
}, 15_000)
|
||||
|
||||
it('keeps a SEALED open hold when the run ends with it still open', async () => {
|
||||
@@ -2082,7 +2104,7 @@ describe('PythonPtcRuntime — programs and bindings', () => {
|
||||
bindings: [],
|
||||
}))
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(result.logs).toEqual(['x' + 'a'.repeat(3000)])
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text)).toEqual(['x' + 'a'.repeat(3000)])
|
||||
}, 15_000)
|
||||
|
||||
it('keeps a flushed unterminated line when the run ends with it still open', async () => {
|
||||
@@ -2098,7 +2120,7 @@ describe('PythonPtcRuntime — programs and bindings', () => {
|
||||
bindings: [],
|
||||
}))
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(result.logs).toEqual(['committed'])
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text)).toEqual(['committed'])
|
||||
}, 15_000)
|
||||
|
||||
it('skips the hold for a zero-content open continuation', async () => {
|
||||
@@ -2118,7 +2140,7 @@ describe('PythonPtcRuntime — programs and bindings', () => {
|
||||
bindings: [],
|
||||
}))
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(result.logs).toEqual(['xy'])
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text)).toEqual(['xy'])
|
||||
}, 15_000)
|
||||
|
||||
it('seals the open hold past MAX_PENDING_CHUNKS without changing the merged entry', async () => {
|
||||
@@ -2140,7 +2162,7 @@ describe('PythonPtcRuntime — programs and bindings', () => {
|
||||
bindings: [],
|
||||
}))
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(result.logs).toEqual(['x' + 'a'.repeat(3000) + 'y'])
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text)).toEqual(['x' + 'a'.repeat(3000) + 'y'])
|
||||
}, 15_000)
|
||||
|
||||
it('bounds a forged open-frame flood against the log budget', async () => {
|
||||
@@ -2160,7 +2182,7 @@ describe('PythonPtcRuntime — programs and bindings', () => {
|
||||
bindings: [],
|
||||
}))
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(result.logs).toEqual(['a'.repeat(60), logTruncationMarker(64)])
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text)).toEqual(['a'.repeat(60), logTruncationMarker(64)])
|
||||
}, 15_000)
|
||||
|
||||
it('commits a sealed open hold before the truncation marker', async () => {
|
||||
@@ -2184,8 +2206,8 @@ describe('PythonPtcRuntime — programs and bindings', () => {
|
||||
bindings: [],
|
||||
}))
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(result.logs[0]).toBe('x' + 'a'.repeat(3000))
|
||||
expect(result.logs[result.logs.length - 1]).toBe(logTruncationMarker(65536))
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text)[0]).toBe('x' + 'a'.repeat(3000))
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text)[result.output.filter(block => block.type === 'text').map(block => block.text).length - 1]).toBe(logTruncationMarker(65536))
|
||||
}, 15_000)
|
||||
|
||||
it('commits a flushed open prefix before the truncation marker', async () => {
|
||||
@@ -2202,7 +2224,7 @@ describe('PythonPtcRuntime — programs and bindings', () => {
|
||||
bindings: [],
|
||||
}))
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(result.logs).toEqual(['committed', logTruncationMarker(64)])
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text)).toEqual(['committed', logTruncationMarker(64)])
|
||||
}, 15_000)
|
||||
|
||||
it('drops a forged fd-3 frame with illegal UTF-8 instead of accepting a mangled value', async () => {
|
||||
@@ -2239,14 +2261,14 @@ describe('PythonPtcRuntime — programs and bindings', () => {
|
||||
bindings: [],
|
||||
}))
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(result.logs).toEqual(['a'.repeat(60), logTruncationMarker(64)])
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text)).toEqual(['a'.repeat(60), logTruncationMarker(64)])
|
||||
}, 15_000)
|
||||
|
||||
it('bills a merged open entry once, not per fragment', async () => {
|
||||
// A merged entry's wire cost is billed ONCE, split across its fragments
|
||||
// (first fragment pays quotes+separator, continuations pay only content).
|
||||
// Under maxLogBytes: 64, 16 single-character flushes merge to one 16-char
|
||||
// entry (2 quotes + 16 content + 1 separator = 19), which fits; per-
|
||||
// entry (2 quotes + 16 content + 2 escaped newline + 1 separator = 21), which fits; per-
|
||||
// fragment billing (each charged quotes+separator, ~4 bytes) would truncate
|
||||
// at 16 x 4 = 64.
|
||||
const { runtime } = await setup({ maxLogBytes: 64 })
|
||||
@@ -2260,15 +2282,11 @@ describe('PythonPtcRuntime — programs and bindings', () => {
|
||||
bindings: [],
|
||||
}))
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(result.logs).toEqual(['x'.repeat(16)])
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text)).toEqual(['x'.repeat(16) + '\n'])
|
||||
}, 15_000)
|
||||
|
||||
it('admits a compliant merged entry whose closing frame fits the remaining budget', async () => {
|
||||
// The review's arithmetic check: print('a'*30, flush); print('b'*25) under
|
||||
// maxLogBytes: 64 has a merged wire cost of 2 quotes + 55 content + 1
|
||||
// separator = 58 <= 63, so it MUST be admitted as one entry. The earlier
|
||||
// cap math (logBudget - openCost) made the closing frame's walk see a
|
||||
// negative cap and truncate a compliant entry.
|
||||
// The merged text and newline cost 60 bytes against the 63-byte ledger.
|
||||
const { runtime } = await setup({ maxLogBytes: 64 })
|
||||
const result = await runtime.run(runtime.resolve({
|
||||
program: [
|
||||
@@ -2279,7 +2297,7 @@ describe('PythonPtcRuntime — programs and bindings', () => {
|
||||
bindings: [],
|
||||
}))
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(result.logs).toEqual(['a'.repeat(30) + 'b'.repeat(25)])
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text)).toEqual(['a'.repeat(30) + 'b'.repeat(25) + '\n'])
|
||||
}, 15_000)
|
||||
|
||||
it('rejects an open frame that would overflow the ledger by one byte', async () => {
|
||||
@@ -2299,50 +2317,41 @@ describe('PythonPtcRuntime — programs and bindings', () => {
|
||||
bindings: [],
|
||||
}))
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(result.logs).toEqual([logTruncationMarker(64)])
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text)).toEqual([logTruncationMarker(64)])
|
||||
}, 15_000)
|
||||
|
||||
it('bills the closing frame as the merged tail under an exact-fit budget', async () => {
|
||||
// The child's split billing: a 30-char open + a 30-char closing frame cost
|
||||
// 2 + 60 + 1 = 63 = ledger 63 exactly; the closing frame must be billed as
|
||||
// the merged tail (content only), not as a fresh entry (which would
|
||||
// double-charge the quotes+separator and truncate an exact-fit entry).
|
||||
// The merged entry costs two quotes, 58 characters, the escaped
|
||||
// newline, and one separator: 63 bytes against the 63-byte ledger.
|
||||
const { runtime } = await setup({ maxLogBytes: 64 })
|
||||
const result = await runtime.run(runtime.resolve({
|
||||
program: [
|
||||
"print('a' * 30, end='', flush=True)",
|
||||
"print('b' * 30)",
|
||||
"print('b' * 28)",
|
||||
'return "done"',
|
||||
].join('\n'),
|
||||
bindings: [],
|
||||
}))
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(result.logs).toEqual(['a'.repeat(30) + 'b'.repeat(30)])
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text)).toEqual(['a'.repeat(30) + 'b'.repeat(28) + '\n'])
|
||||
}, 15_000)
|
||||
|
||||
it('does not over-reject an exact-fit closing line while an open entry accumulates', async () => {
|
||||
// The write-path pre-check's cheap bound used +3 (quotes + separator) even
|
||||
// while an open entry was accumulating, so an exact-fit merged TAIL was
|
||||
// truncated. The recipe below goes through the SCAN pre-check (the
|
||||
// newline-terminated write arrives with an empty pending buffer, so the
|
||||
// buffered-chunks branch is skipped): 'a'*29 flush bills 32 (ledger 31
|
||||
// left), then one write of 'b'*30 + newline merges 30 more chars whose
|
||||
// cheap bound is 30, not 33 — the +3 form saw 30 + 3 = 33 > 31, sliced to
|
||||
// a budget prefix, and pushed past the ledger, emitting the marker for a
|
||||
// line that fits (merged cost 2 + 59 + 1 = 62 <= 63).
|
||||
// A closing tail pays its content and escaped newline; the first
|
||||
// fragment already paid the quotes and separator.
|
||||
const { runtime } = await setup({ maxLogBytes: 64 })
|
||||
const result = await runtime.run(runtime.resolve({
|
||||
program: [
|
||||
'import sys',
|
||||
"sys.stdout.write('a' * 29)",
|
||||
'sys.stdout.flush()',
|
||||
"sys.stdout.write('b' * 30 + chr(10))",
|
||||
"sys.stdout.write('b' * 29 + chr(10))",
|
||||
'return "done"',
|
||||
].join('\n'),
|
||||
bindings: [],
|
||||
}))
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(result.logs).toEqual(['a'.repeat(29) + 'b'.repeat(30)])
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text)).toEqual(['a'.repeat(29) + 'b'.repeat(29) + '\n'])
|
||||
}, 15_000)
|
||||
|
||||
|
||||
@@ -2362,7 +2371,7 @@ describe('PythonPtcRuntime — programs and bindings', () => {
|
||||
bindings: [],
|
||||
}))
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(result.logs).toEqual(['a'.repeat(59), logTruncationMarker(64)])
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text)).toEqual(['a'.repeat(59), logTruncationMarker(64)])
|
||||
}, 15_000)
|
||||
|
||||
it('truncates when the closing frame of a merged entry overflows the budget', async () => {
|
||||
@@ -2380,7 +2389,7 @@ describe('PythonPtcRuntime — programs and bindings', () => {
|
||||
bindings: [],
|
||||
}))
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(result.logs).toEqual(['x'.repeat(40), logTruncationMarker(64)])
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text)).toEqual(['x'.repeat(40), logTruncationMarker(64)])
|
||||
}, 15_000)
|
||||
|
||||
it('keeps a float completion exact when the program mutates the decimal context', async () => {
|
||||
@@ -2485,8 +2494,8 @@ describe('PythonPtcRuntime — programs and bindings', () => {
|
||||
}))
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(result.value).toBe('ok')
|
||||
expect(result.logs).toContain('first')
|
||||
expect(result.logs).toContain('second')
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text)).toContain('first')
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text)).toContain('second')
|
||||
})
|
||||
|
||||
it('raises the declared errorClass with the member name on rejection', async () => {
|
||||
@@ -3471,7 +3480,7 @@ describe('PythonPtcRuntime — budgets, termination, disposal', () => {
|
||||
}))
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(result.value).toBe('escaped')
|
||||
expect(result.logs).toContain('leader-diagnostic-no-newline')
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text)).toContain('leader-diagnostic-no-newline')
|
||||
}, 8000)
|
||||
|
||||
it('closes the child stdin so a program read sees EOF instead of blocking', async () => {
|
||||
@@ -3867,7 +3876,7 @@ describe('PythonPtcRuntime — hostile peer', () => {
|
||||
bindings: [],
|
||||
}))
|
||||
expect(result.error).toBeUndefined()
|
||||
const markers = result.logs.filter(line => line.includes('log capture truncated at 128 bytes'))
|
||||
const markers = result.output.filter(block => block.type === 'text').map(block => block.text).filter(line => line.includes('log capture truncated at 128 bytes'))
|
||||
expect(markers.length).toBeGreaterThanOrEqual(1)
|
||||
})
|
||||
|
||||
@@ -4444,7 +4453,7 @@ describe('PythonPtcRuntime — hostile peer', () => {
|
||||
}))
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(result.value).toBe('done')
|
||||
expect(result.logs.some(line => line.includes('log capture truncated'))).toBe(true)
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text).some(line => line.includes('log capture truncated'))).toBe(true)
|
||||
}, 20_000)
|
||||
|
||||
it('stops host capture at the child ledger truncation, keeping exactly one marker', async () => {
|
||||
@@ -4471,11 +4480,11 @@ describe('PythonPtcRuntime — hostile peer', () => {
|
||||
}))
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(result.value).toBe('done')
|
||||
const markers = result.logs.filter(line => line.includes('log capture truncated'))
|
||||
const markers = result.output.filter(block => block.type === 'text').map(block => block.text).filter(line => line.includes('log capture truncated'))
|
||||
expect(markers).toHaveLength(1)
|
||||
// The marker is the LAST entry: nothing was retained after truncation.
|
||||
expect(result.logs.at(-1)).toBe(markers[0])
|
||||
expect(result.logs.join('\n')).not.toContain('AFTER')
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text).at(-1)).toBe(markers[0])
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text).join('')).not.toContain('AFTER')
|
||||
}, 20_000)
|
||||
|
||||
it('keeps one marker when a program forges repeated truncation frames', async () => {
|
||||
@@ -4498,13 +4507,13 @@ describe('PythonPtcRuntime — hostile peer', () => {
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(result.value).toBe('done')
|
||||
// The non-boolean flag did not truncate, so its text was captured normally.
|
||||
expect(result.logs).toContain('first')
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text)).toContain('first')
|
||||
// The first genuine flag stopped capture and emitted the HOST's own marker;
|
||||
// the frame's own text is discarded, so neither payload appears.
|
||||
expect(result.logs).not.toContain('MARK-A')
|
||||
expect(result.logs).not.toContain('MARK-B')
|
||||
expect(result.logs.at(-1)).toBe(logTruncationMarker(4096))
|
||||
expect(result.logs.filter(line => line.includes('log capture truncated'))).toHaveLength(1)
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text)).not.toContain('MARK-A')
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text)).not.toContain('MARK-B')
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text).at(-1)).toBe(logTruncationMarker(4096))
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text).filter(line => line.includes('log capture truncated'))).toHaveLength(1)
|
||||
}, 20_000)
|
||||
|
||||
it('discards the text of a forged truncation frame instead of retaining it', async () => {
|
||||
@@ -4528,8 +4537,8 @@ describe('PythonPtcRuntime — hostile peer', () => {
|
||||
expect(result.value).toBe('done')
|
||||
// Only the host marker is kept, so the total stays orders of magnitude below
|
||||
// what the forgery carried — and below the cap it was trying to escape.
|
||||
expect(result.logs).toEqual([logTruncationMarker(64)])
|
||||
expect(result.logs.join('').length).toBeLessThan(forgedBytes / 1000)
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text)).toEqual([logTruncationMarker(64)])
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text).join('').length).toBeLessThan(forgedBytes / 1000)
|
||||
}, 30_000)
|
||||
|
||||
it('coalesces unframed fd-3 fragments without recopying the sealed prefix', async () => {
|
||||
@@ -4585,7 +4594,7 @@ describe('PythonPtcRuntime — hostile peer', () => {
|
||||
}
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(result.value).toBe('done')
|
||||
expect(result.logs).toContain('after-trickle')
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text)).toContain('after-trickle\n')
|
||||
// Sealing appends a finished block rather than re-merging everything held, so
|
||||
// each byte is copied once. Re-concatenating the whole buffer at every
|
||||
// threshold made the cumulative copy volume quadratic — 10 MiB trickled a
|
||||
@@ -4652,9 +4661,9 @@ describe('PythonPtcRuntime — hostile peer', () => {
|
||||
}))
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(result.value).toBe('done')
|
||||
expect(result.logs.some(line => line.includes('log capture truncated'))).toBe(true)
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text).some(line => line.includes('log capture truncated'))).toBe(true)
|
||||
// The retained text is bounded by the budget, not the 1 MB the program wrote.
|
||||
expect(result.logs.join('\n').length).toBeLessThan(4096)
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text).join('').length).toBeLessThan(4096)
|
||||
}, 20_000)
|
||||
|
||||
it('discards empty writes instead of buffering one list slot each', async () => {
|
||||
@@ -4677,7 +4686,7 @@ describe('PythonPtcRuntime — hostile peer', () => {
|
||||
}))
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(result.value).toBe('done')
|
||||
expect(result.logs).toEqual([])
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text)).toEqual([])
|
||||
}, 30_000)
|
||||
|
||||
it('stops scanning a single-write newline flood once the log ledger truncates', async () => {
|
||||
@@ -4693,7 +4702,7 @@ describe('PythonPtcRuntime — hostile peer', () => {
|
||||
}))
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(result.value).toBe('done')
|
||||
expect(result.logs.filter(line => line.includes('log capture truncated'))).toHaveLength(1)
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text).filter(line => line.includes('log capture truncated'))).toHaveLength(1)
|
||||
expect(Date.now() - start).toBeLessThan(8_000)
|
||||
}, 15_000)
|
||||
|
||||
@@ -4720,7 +4729,7 @@ describe('PythonPtcRuntime — hostile peer', () => {
|
||||
}))
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(result.value).toBe('done')
|
||||
expect(result.logs).toEqual([logTruncationMarker(256)])
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text)).toEqual([logTruncationMarker(256)])
|
||||
}, 40_000)
|
||||
|
||||
it('bounds a newline-free write against the already-buffered chunks before joining them', async () => {
|
||||
@@ -4751,7 +4760,7 @@ describe('PythonPtcRuntime — hostile peer', () => {
|
||||
}))
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(result.value).toBe('done')
|
||||
expect(result.logs).toEqual([logTruncationMarker(256)])
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text)).toEqual([logTruncationMarker(256)])
|
||||
}, 40_000)
|
||||
|
||||
it('bounds a newline-terminated write against the already-buffered chunks before joining them', async () => {
|
||||
@@ -4778,7 +4787,7 @@ describe('PythonPtcRuntime — hostile peer', () => {
|
||||
}))
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(result.value).toBe('done')
|
||||
expect(result.logs).toEqual([logTruncationMarker(256)])
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text)).toEqual([logTruncationMarker(256)])
|
||||
}, 40_000)
|
||||
|
||||
it('emits pending text on an explicit flush, before the run can be killed', async () => {
|
||||
@@ -4798,59 +4807,39 @@ describe('PythonPtcRuntime — hostile peer', () => {
|
||||
bindings: [],
|
||||
}))
|
||||
expect(result.error?.kind).toBe('timeout')
|
||||
expect(result.logs).toContain('before hang')
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text)).toContain('before hang')
|
||||
}, 15_000)
|
||||
|
||||
it('marks a dropped tail when the ledger lands on exactly zero remaining', async () => {
|
||||
// One 100-character line costs 103 serialized bytes (quotes + separator),
|
||||
// consuming a 104-byte budget minus the 1-byte array-envelope reservation
|
||||
// (104 - 1 = 103) EXACTLY. Landing on zero never trips
|
||||
// LogBuffer's "cost > remaining" branch, so `_truncated` stays unset and the
|
||||
// stream's own `remaining > 0` guard silently discarded the unscanned tail —
|
||||
// the run reported a complete log while dropping text. The tail must be
|
||||
// pushed so the marker is emitted. (This surfaced only after empty writes
|
||||
// stopped being buffered: `print` issues a trailing `write("")` whose
|
||||
// buffered-empty path used to force the marker out incidentally.) A single
|
||||
// wide line is used rather than many narrow ones so the CHILD ledger is the
|
||||
// one that lands on zero: the host's identical ledger truncates first when
|
||||
// many small entries precede the long marker text. `["y"*100]` serializes to
|
||||
// exactly 104 bytes (103 payload + 1 envelope), so 104 is the smallest
|
||||
// budget that admits the entry.
|
||||
const { runtime } = await setup({ maxLogBytes: 104, maxWallMs: 10_000 })
|
||||
// A 100-character line plus its escaped newline consumes a 106-byte
|
||||
// serialized array exactly; an unscanned tail must still report truncation.
|
||||
const { runtime } = await setup({ maxLogBytes: 106, maxWallMs: 10_000 })
|
||||
const result = await runtime.run(runtime.resolve({
|
||||
program: ['print("y" * 100 + "\\n" + "z" * 10, end="")', 'return "done"'].join('\n'),
|
||||
bindings: [],
|
||||
}))
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(result.value).toBe('done')
|
||||
expect(result.logs).toContain('y'.repeat(100))
|
||||
expect(result.logs.filter(line => line.includes('log capture truncated'))).toHaveLength(1)
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text)).toContain('y'.repeat(100) + '\n')
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text).filter(line => line.includes('log capture truncated'))).toHaveLength(1)
|
||||
// The dropped tail is not retained, but its loss is now reported.
|
||||
expect(result.logs.some(line => line.includes('z'))).toBe(false)
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text).some(line => line.includes('z'))).toBe(false)
|
||||
}, 15_000)
|
||||
|
||||
it('keeps an admitted log within the serialized array envelope at the exact limit', async () => {
|
||||
// Each entry is charged its JSON-string cost plus one separator byte, and
|
||||
// the serialized outer logs array adds one more byte of envelope (two
|
||||
// brackets and n-1 commas). The ledgers reserve that byte, so a result that
|
||||
// exactly exhausts the ledger still serializes within the configured cap.
|
||||
// At the 64-byte floor (the smallest admissible maxLogBytes): ledger 63,
|
||||
// a 60-character line serializes as `"aaa...a"` (62 bytes) + 1 separator
|
||||
// = 63, exactly exhausting the ledger and serializing as `["aaa...a"]`
|
||||
// = 64 = the cap; a 61-character line costs 64 > 63 and truncates. The
|
||||
// marker rides envelope, so the serialized logs run to cap + marker.
|
||||
// At the 64-byte floor, 58 characters and their escaped newline
|
||||
// serialize to exactly 64 bytes including the array envelope.
|
||||
const { runtime } = await setup({ maxLogBytes: 64, maxWallMs: 10_000 })
|
||||
const result = await runtime.run(runtime.resolve({
|
||||
program: ['print("a" * 60 + "\\n" + "b" * 61, end="")', 'return "done"'].join('\n'),
|
||||
program: ['print("a" * 58 + "\\n" + "b" * 61, end="")', 'return "done"'].join('\n'),
|
||||
bindings: [],
|
||||
}))
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(result.value).toBe('done')
|
||||
// The 60-character line was admitted; the 61-character line was not (a
|
||||
// single 'b' would also match the marker's "bytes", so check for the line).
|
||||
expect(result.logs).toContain('a'.repeat(60))
|
||||
expect(result.logs.some(line => line.includes('b'.repeat(61)))).toBe(false)
|
||||
expect(result.logs.some(line => line.includes('log capture truncated'))).toBe(true)
|
||||
// Only the first complete line fits before the marker.
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text)).toContain('a'.repeat(58) + '\n')
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text).some(line => line.includes('b'.repeat(61)))).toBe(false)
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text).some(line => line.includes('log capture truncated'))).toBe(true)
|
||||
}, 15_000)
|
||||
|
||||
it('rejects a log budget too small to serialize the truncation marker', async () => {
|
||||
@@ -4875,10 +4864,10 @@ describe('PythonPtcRuntime — hostile peer', () => {
|
||||
bindings: [],
|
||||
}))
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(result.logs.some(line => line.includes('log capture truncated'))).toBe(true)
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text).some(line => line.includes('log capture truncated'))).toBe(true)
|
||||
// Serialized (escaped) size of retained entries stays in the budget's
|
||||
// neighborhood: well under the ~30 kB an uncharged flood would retain.
|
||||
const serialized = Buffer.byteLength(JSON.stringify(result.logs), 'utf8')
|
||||
const serialized = Buffer.byteLength(JSON.stringify(result.output.filter(block => block.type === 'text').map(block => block.text)), 'utf8')
|
||||
expect(serialized).toBeLessThan(1024)
|
||||
})
|
||||
|
||||
@@ -4901,9 +4890,9 @@ describe('PythonPtcRuntime — hostile peer', () => {
|
||||
}))
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(result.value).toBe('done')
|
||||
expect(result.logs.filter(line => line.includes('log capture truncated'))).toHaveLength(1)
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text).filter(line => line.includes('log capture truncated'))).toHaveLength(1)
|
||||
// Nothing of the line itself was retained: the ledger refused the whole entry.
|
||||
expect(result.logs.every(line => !line.includes(String.fromCharCode(0)))).toBe(true)
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text).every(line => !line.includes(String.fromCharCode(0)))).toBe(true)
|
||||
}, 30_000)
|
||||
|
||||
it('bounds a huge unterminated tail after an early newline without copying it whole', async () => {
|
||||
@@ -4931,7 +4920,7 @@ describe('PythonPtcRuntime — hostile peer', () => {
|
||||
}))
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(result.value).toBe('done')
|
||||
expect(result.logs.some(line => line.includes('log capture truncated'))).toBe(true)
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text).some(line => line.includes('log capture truncated'))).toBe(true)
|
||||
}, 30_000)
|
||||
|
||||
it('flushes logs before framing the value so their peaks do not add against RLIMIT_AS', async () => {
|
||||
@@ -5366,8 +5355,8 @@ describe('PythonPtcRuntime — hostile peer', () => {
|
||||
bindings: [],
|
||||
}))
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(result.logs.length).toBeLessThanOrEqual(65)
|
||||
expect(result.logs.some(line => line.includes('log capture truncated'))).toBe(true)
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text).length).toBeLessThanOrEqual(65)
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text).some(line => line.includes('log capture truncated'))).toBe(true)
|
||||
})
|
||||
|
||||
it('reassembles multibyte UTF-8 split across stray-output pipe chunks', async () => {
|
||||
@@ -5397,7 +5386,7 @@ describe('PythonPtcRuntime — hostile peer', () => {
|
||||
bindings: [],
|
||||
}))
|
||||
expect(result.error).toBeUndefined()
|
||||
const text = result.logs.join('')
|
||||
const text = result.output.filter(block => block.type === 'text').map(block => block.text).join('')
|
||||
expect(text).toContain('\u0900\u4f60\u597d\u{1f600}\u{10ffff}')
|
||||
expect(text).not.toContain('\ufffd')
|
||||
})
|
||||
@@ -5419,7 +5408,7 @@ describe('PythonPtcRuntime — hostile peer', () => {
|
||||
bindings: [],
|
||||
}))
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(result.logs.join('')).toContain('�')
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text).join('')).toContain('�')
|
||||
})
|
||||
|
||||
it('rejects reserved words of EITHER backend language as binding globals', async () => {
|
||||
@@ -5450,8 +5439,8 @@ describe('PythonPtcRuntime — hostile peer', () => {
|
||||
bindings: [],
|
||||
}))
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(result.logs.join('')).toContain('stray stdout')
|
||||
expect(result.logs.join('')).toContain('stray stderr')
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text).join('')).toContain('stray stdout')
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text).join('')).toContain('stray stderr')
|
||||
})
|
||||
|
||||
it('flushes bytes written through sys.__stdout__/sys.__stderr__ before the done frame', async () => {
|
||||
@@ -5481,8 +5470,8 @@ describe('PythonPtcRuntime — hostile peer', () => {
|
||||
}))
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(result.value).toBe('done')
|
||||
expect(result.logs.join('')).toContain('orig stdout')
|
||||
expect(result.logs.join('')).toContain('orig stderr')
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text).join('')).toContain('orig stdout')
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text).join('')).toContain('orig stderr')
|
||||
}, 15_000)
|
||||
|
||||
it('escalates to SIGKILL when the program traps SIGTERM and ignores the grace period', async () => {
|
||||
@@ -5575,7 +5564,7 @@ describe('PythonPtcRuntime — hostile peer', () => {
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(result.value).toBe('settled')
|
||||
// The frame was dropped as one truncation marker, not retained.
|
||||
expect(result.logs).toEqual([logTruncationMarker(128)])
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text)).toEqual([logTruncationMarker(128)])
|
||||
// The escaped copy (~144 MiB) was never materialized.
|
||||
expect(process.memoryUsage().heapUsed - before).toBeLessThan(256 * 1024 * 1024)
|
||||
}, 90_000)
|
||||
@@ -5596,7 +5585,7 @@ describe('PythonPtcRuntime — hostile peer', () => {
|
||||
}))
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(result.value).toBe('settled')
|
||||
expect(result.logs).toEqual([logTruncationMarker(64)])
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text)).toEqual([logTruncationMarker(64)])
|
||||
}, 8000)
|
||||
|
||||
it('caps a forged done error.message from its code-unit prefix, never encoding the whole message', async () => {
|
||||
@@ -5833,7 +5822,7 @@ describe('PythonPtcRuntime — hostile peer', () => {
|
||||
}))
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(result.value).toBe('done')
|
||||
expect(result.logs).toContain('after-cap-frames')
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text)).toContain('after-cap-frames')
|
||||
}, 120_000)
|
||||
|
||||
it('rejects an oversized first frame that lands on the sealing threshold with a newline', async () => {
|
||||
|
||||
@@ -45,7 +45,7 @@ it('seals stray fragments without recopying the sealed prefix', async () => {
|
||||
}))
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(result.value).toBe('done')
|
||||
expect(result.logs).toEqual(['x'.repeat(60_000)])
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text)).toEqual(['x'.repeat(60_000) + '\n'])
|
||||
// Sealing copies each byte at most twice; merging every accumulated prefix
|
||||
// instead copies over a megabyte for these 60,001 controlled fragments.
|
||||
expect(maxFragments).toBeLessThanOrEqual(1024)
|
||||
@@ -75,7 +75,7 @@ it.each([
|
||||
bindings: [],
|
||||
}))
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(result.logs.at(-1)).toBe(logTruncationMarker(3072))
|
||||
expect(result.output.filter(block => block.type === 'text').map(block => block.text).at(-1)).toBe(logTruncationMarker(3072))
|
||||
// Each raw byte decodes to U+FFFD (three UTF-8 bytes), so a 3072-byte
|
||||
// budget flushes near 1024 raw bytes. Charging raw or structural widths
|
||||
// instead retains over 2048 bytes before flushing these payloads.
|
||||
|
||||
Reference in new issue
Block a user