Document the two remaining keep-current residuals in the python package README Known Limitations (en + zh), per the review's accepted-resolution path: - A trap-SIGXCPU program can exceed the soft CPU limit during settlement encoding and still report success (containment holds via hard +1s and wall clock; only the classification is degraded, because the recheck cannot meter mid-encode). - The encoder's direct deps (_dump_scalar/_dump_string/json) resolve at call time, so a __main__ rebind after a legit return can downgrade success to exception; the value path's top-level deps are def-time bound, the transitive ones are an accepted residual. Pairing re-recorded and consistent.
10 KiB
description, kind
| description | kind |
|---|---|
| CPython subprocess implementation of the DeepSeek Harness code-execution seam, with fd-3 bindings, resource limits, log capture, and process-group teardown. | package-reference |
@deepseek-ai/dsh-code-runtime-python
English | 中文
CPython-subprocess implementation of the @deepseek-ai/dsh-code-runtime seam. Companion to @deepseek-ai/dsh-code-runtime-worker-thread; trades the Node worker thread for a fresh python3 subprocess so model code is Python instead of TypeScript.
The package owns the wire protocol for that seam: the host-side frame codec and the Python-side mirror of the same message vocabulary. On top of that protocol it ships PythonCodeRuntime (the plugin's default export), which registers as codeRuntime with language: 'python' and isolation: 'process'. Each run() spawns a fresh python3 -I process, sends a boot frame and the program over fd 3, and resolves a CodeRunResult for every program outcome — run() rejects only for seam misuse, such as a malformed binding namespace or a call on a runtime whose fiber was already disposed. Configuration is rejected earlier, when the plugin loads: a non-Unix platform, a non-positive or non-integer budget, a timer value setTimeout would clamp, a budget larger than one fd-3 frame can carry, and an addressSpaceMb/output-budget pair whose worst-case peak would breach RLIMIT_AS all throw from the constructor, so a misconfiguration fails at assembly rather than on a later run. The child runs the program as the body of an async function, so top-level await and return both work; binding calls travel back over fd 3 as JSON-lines. Containment (not a security boundary — model code has bash-equivalent trust) comes from an empty environment, RLIMIT_CPU/RLIMIT_AS, a wall-clock ceiling, and a SIGTERM→grace→SIGKILL teardown on the child's process group.
Wire protocol
The host and the CPython subprocess exchange a versionless, JSON-lines protocol on the child's fd 3 — one JSON object per line, leaving stdout/stderr free for the program's own output. src/protocol.ts is the host side; py/protocol.py mirrors its message shapes and the shared truncation-marker text on the Python side.
- fd 3, not stdout — Node pins the channel positionally with
stdio: ['pipe','pipe','pipe','pipe']; the Python bootstrap reads the samePROTOCOL_FDconstant. JSON-lines framing. - Host treats every inbound frame as hostile — model code has full access to fd 3 and can post anything through it, so
validateChildFrameshape-validates and REBUILDS each frame before the host reads it: forged extra fields never ride along, a non-number call id can never be echoed into a reply, and junk drops toundefinedrather than throwing in the host's message handler. The Python side trusts host replies (the host is not model-controlled). - Lossless-JSON crossing — completion values and binding arguments cross as exact JSON.
encodeJsonPlainserializes aJSON.parse-produced value without recursion, so a deep value below the byte budget crosses intact instead of dying onJSON.stringify's stack limit;checkDoneValuemeters a forged completion value's byte length AND number losslessness in one bounded traversal that rejects an over-budget payload before enqueuing its children;hasUnsafeIntegerTokenreads the raw frame text to catch an integer token thatJSON.parsewould silently round;hasNonLosslessNumberrejects a non-finite or negative-zero number in unboundedcall.args. Beyond-safe-range integral doubles serialize throughBigIntdigits so the exact integer crosses, not the roundedString()form. - Shared truncation marker —
logTruncationMarker(maxBytes)produces byte-identical text on both sides, so a truncated log run reads the same however the cap was hit. Thelogframe'struncatedflag distinguishes the child ledger's own marker from program output.
Configuration
Every cap is a validated Config field with a default, changeable from cordis.yml (no hardcoded tunables). cpuSeconds (default 60) is the RLIMIT_CPU whole-second budget; the child sets the soft limit to cpuSeconds and the hard limit to cpuSeconds + 1, so the kernel's SIGXCPU at the soft limit classifies as a timeout while the +1s hard limit is a SIGKILL backstop. maxWallMs (default 600000) is the wall-clock ceiling that backstops CPU time for a program awaiting a promise nobody resolves. addressSpaceMb (default 512) is the RLIMIT_AS cap, not applied on Darwin (the dyld shared cache mapped into every process exceeds any practical cap there; cpuSeconds and maxWallMs still bound the run). maxLogBytes (default 65536) is the shared captured-log byte budget; maxValueBytes (default 32768) caps the completion value; graceMs (default 3000) is the SIGTERM→SIGKILL grace window; pythonBin (default python3) is the interpreter, resolved against PATH before the child spawns with an empty environment.
Model Experience
Indirectly, through Code Mode in dsh-tools, which renders this backend's exact completion value when it fits (or an explicit invalid-output / output-limit failure), plus the exact [dsh-code-runtime-python] log capture truncated at <maxLogBytes> bytes log marker, into a retained run_code result.
KV Cache effect
No direct invalidation; the named consumer owns any request-prefix changes.
Known Limitations and Deferred Work
- The cross-language guard covers executed values and frame field sets, not field types —
tests/protocol-mirror.e2e.tscomparesPROTOCOL_FD, the log truncation marker, and eachTypedDict's required and optional fields against a realpython3. Comparing field types across TypeScript and Python has no mechanical equivalent here, so review plus the backend's real-subprocess suite owns type-level drift. RLIMIT_ASis not enforced on macOS — the dyld shared cache mapped into every process at exec exceeds any practical address-space cap, and the kernel rejects thesetrlimitcall, soaddressSpaceMbis skipped there.cpuSecondsandmaxWallMsstill bound every run.- A descendant that calls
setsid()/start_new_session=Trueescapes teardown. Termination signals the child's process group withkill(-pid); a descendant that moves itself into a fresh session is no longer in that group and no signal reaches it. If it also releases the inherited stdout/stderr/fd-3 pipes, the leader'sclosestill settles the run, and after thecloseDeadlinebound the fiber goes quiescent while that orphan keeps running. This is the containment boundary, not a security one — model code has bash-equivalent trust, and a bash tool cansetsidaway just the same. Reaching such an orphan would require tracking every descendant pid (as the bash-local backend's process-inspector does) and is deferred; the process-group teardown reaps everything that stays in the group. - A combined log-and-value peak is not modelled by the load gate. Each budget is checked against
addressSpaceMbon its own. A model daemon thread that keeps writing while the completion value is metered and framed can refill the log pending towardmaxLogBytesduring that window, so the two peaks add in a way no gate admits or rejects. A gate over(maxLogBytes + maxValueBytes)was considered and deferred: its discriminating case cannot be scheduled deterministically underRLIMIT_AS, so the gate would only prove its own arithmetic. When the combined peak is reached the run dies asworker-exit-- containment holds and only the failure classification is degraded. - A 1-second dual-limit
ulimit -t 1CPU overrun is reported asworker-exit, not a timeout. When the host starts under a hard CPU limit equal to the soft (ulimit -t Nsets both) and that limit is 1,_clampedcannot lower the soft to 0, so the kernel SIGKILLs the busy loop in the same tick and SIGXCPU is never delivered. The host classifies a CPU overrun only onsignal === 'SIGXCPU', so the overrun is reported asworker-exit. For a dual limit of 2 or more the soft is lowered by one unit, SIGXCPU fires, and the run is a timeout. Containment holds in both cases; only the classification is degraded. - A program that traps SIGXCPU can exceed the soft CPU limit during settlement encoding and still report success. The settlement CPU recheck runs before the completion value is flushed and encoded; a program that traps SIGXCPU (soft limit) and keeps burning past it through the build-and-encode window returns a result before
die_if_cpu_exhaustedre-checks, so the run reports success. Containment holds — the hard limit (soft + 1s) and the wall clock still bound it — and only the classification is degraded. The CPU recheck does not run mid-encode because doing so would have to meter the encode itself, and the encode is the path the budget already bounds. - The encoder's direct dependencies resolve at call time.
_encode_json_plainreaches_dump_scalar/_dump_string/jsonvia module-global lookup, so a program running as__main__that rebinds one of those names (e.g.__main__._dump_scalar = boom) after returning a legitimate value can make the encode throw and downgrade a success toexception. The value path's top-level_check_done_value/_encode_json_plainare bound as def-time defaults, but their transitive deps are not; this is an accepted residual for the same reason the analogous_dump_*helpers are not rebound in practice. - A wide binding REPLY expands host-side state per member. Resolutions cross through
snapshotJsonValuein@deepseek-ai/dsh-session, whosewalkJsonValuepushes one task frame per member, and binding resolution carries no seam-level byte cap. A legitimate reply of several million elements can therefore exhaust the host heap. A cross-thread binding that the program joins with a synchronoust.join()can also deadlock: the joining thread blocks the main coroutine while the binding's reply still needs the pump to deliver it, soawaitnever resumes until the wall clock. The property belongs to that shared walk, not to this backend -- the worker-thread backend consumes the same function -- so the fix belongs inpackages/core/sessionwhere every consumer benefits.