bootstrap.py 103 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061
  1. """CPython bootstrap for dsh-code-runtime-python.
  2. Reads a :class:`BootMessage` on fd 3, applies resource limits and log capture,
  3. reads a :class:`RunMessage`, runs the model program as the body of an async
  4. function (top-level ``await`` and ``return`` both work; the returned value is
  5. the completion), and posts a terminal :class:`DoneMessage`. The program calls
  6. host functions through the ``tools`` (or other namespace) proxy, whose attribute
  7. and subscript access return awaitables that ride binding messages over fd 3.
  8. This module runs under ``python3 -I`` with an empty environment and
  9. ``sys.path`` containing only its own directory.
  10. """
  11. from __future__ import annotations
  12. import asyncio
  13. import ast
  14. import io
  15. import json
  16. import math
  17. import os
  18. import re
  19. import resource
  20. import signal
  21. import sys
  22. import threading
  23. import traceback
  24. from decimal import Decimal
  25. from pathlib import Path
  26. from typing import Any
  27. # ``python3 -I`` (isolated) drops the script directory from ``sys.path`` so
  28. # the sibling ``protocol.py`` is invisible by default. Restore it explicitly
  29. # before importing.
  30. sys.path.insert(0, str(Path(__file__).resolve().parent))
  31. from protocol import PROTOCOL_FD, log_truncation_marker # noqa: E402
  32. # Read size for the async fd-3 reader. One `os.read` returns whatever the pipe
  33. # holds, so this only bounds a single syscall's copy, not a frame: a larger frame
  34. # simply takes more reads. 64 KiB matches the usual pipe capacity.
  35. _READ_CHUNK_BYTES = 65536
  36. # Code-unit ceiling on the exception class name interpolated into the LAST-resort
  37. # failure diagnostic. A metaclass `__name__` property can return any length, and
  38. # that construction runs outside the guard that would otherwise absorb a
  39. # MemoryError, so the name is sliced before it is copied. Generous enough that no
  40. # real class name is touched.
  41. _MAX_FALLBACK_NAME_CHARS = 200
  42. # Mirror of the host's output-budget/address-space gate (src/index.ts's
  43. # OUTPUT_BUDGET_WORST_CASE_ADDRESS_SPACE_MULTIPLE and INTERPRETER_BASELINE_BYTES),
  44. # re-applied against the EFFECTIVE RLIMIT_AS after inheritance clamping. An astral
  45. # character is one character but ~4 bytes of str storage and ~4 UTF-8 bytes, and
  46. # three such copies are live at the peak — the caller's write argument, the line
  47. # slice or joined pending handed to push, and the encode copy push takes — so a
  48. # budget's worst-case peak is twelve times its byte count; the interpreter's own
  49. # footprint is reserved on top. Kept in sync with the host constants by the shared
  50. # reasoning, not a wire field.
  51. _OUTPUT_BUDGET_WORST_CASE_MULTIPLE = 12
  52. _INTERPRETER_BASELINE_BYTES = 64 * 1024 * 1024
  53. # ---------------------------------------------------------------------------
  54. # Log buffer — Python-side ledger for captured text.
  55. # ---------------------------------------------------------------------------
  56. class LogBuffer:
  57. """Ordered text capture under one shared byte budget.
  58. Once the budget is exhausted the buffer emits exactly one in-band
  59. truncation marker via ``sink`` and silently drops everything after. The
  60. cap is a blast-radius bound; "how much was lost" intentionally stays
  61. unmeasured.
  62. """
  63. def __init__(self, max_bytes: int, sink) -> None:
  64. self._max_bytes = max_bytes
  65. self._remaining = max_bytes
  66. self._truncated = False
  67. # Re-entrant so a caller may hold it across a compound read-modify-write
  68. # (``_LogStream.write`` reads ``remaining`` several times and then calls
  69. # ``push`` while still holding it). One lock is shared by this buffer and
  70. # every stream that funnels into it: model code may start daemon threads
  71. # that keep calling ``print`` after the program body returns, and the
  72. # settlement ``flush_line`` on the main coroutine reads and mutates the
  73. # same ``_pending``/ledger state. Without a shared lock the flush could
  74. # interleave with a concurrent ``write`` — dropping or double-counting a
  75. # line, or costing the ``done`` frame on a mangled ledger. Fixing which
  76. # callable runs (binding ``out_stream.flush_line``) does not fix what it
  77. # reads.
  78. self._lock = threading.RLock()
  79. # ``sink(text, truncated=False)``. The marker is emitted with
  80. # ``truncated=True`` so the host can stop its own capture at the same
  81. # point rather than treating the marker as ordinary program output: the
  82. # two ledgers exhaust independently, and one entry larger than
  83. # ``max_bytes`` sends only the marker while the host budget is still
  84. # nearly empty.
  85. self._sink = sink
  86. @property
  87. def lock(self) -> "threading.RLock":
  88. """The shared re-entrant lock guarding this ledger and its streams' buffers."""
  89. return self._lock
  90. @property
  91. def remaining(self) -> int:
  92. """Serialized bytes still admissible; zero once truncated (streams use this to bound their own buffering, where a character count is a valid lower bound)."""
  93. return 0 if self._truncated else self._remaining
  94. def push(self, text: str) -> None:
  95. with self._lock:
  96. self._push_locked(text)
  97. def _push_locked(self, text: str) -> None:
  98. if self._truncated:
  99. return
  100. # Cheap lower bound FIRST: one char is at least one UTF-8 byte and the
  101. # JSON form adds two quotes plus the separator, so a single print() far
  102. # above the budget truncates without ever encoding it — the full encode
  103. # would allocate a second equally large string and could turn a
  104. # truncatable log into an RLIMIT_AS death.
  105. if len(text) + 3 > self._remaining:
  106. self._truncated = True
  107. self._sink(log_truncation_marker(self._max_bytes), truncated=True)
  108. return
  109. # A model print() can emit a lone surrogate; strict UTF-8 throws on it
  110. # here. Replace it rather than escaping it the way :func:`_dump_string`
  111. # preserves one inside a completion VALUE: log text is already a
  112. # truncatable, substituting channel (the byte cap replaces the tail with
  113. # a marker), and the ledger below charges the RAW UTF-8 bytes, which
  114. # would undercharge the six-byte escape by half. Bounded: the text
  115. # passed the length check, so this encodes at most ~4x remaining.
  116. try:
  117. raw = text.encode("utf-8")
  118. except UnicodeEncodeError:
  119. raw = text.encode("utf-8", errors="replace")
  120. text = raw.decode("utf-8")
  121. # Charge the SERIALIZED cost — the JSON string form's bytes plus one
  122. # separator byte — exactly as the host ledger does. Charging the raw
  123. # UTF-8 length instead undercharges control-heavy text, whose JSON
  124. # escaping expands it up to sixfold (a NUL costs one raw byte but six
  125. # as its ``\uXXXX`` escape): a NUL flood sized to fit ``maxLogBytes``
  126. # raw would serialize to roughly six times the shared cap, and the child
  127. # could then die on RLIMIT_AS (reported host-side as ``worker-exit``)
  128. # instead of emitting the truncation marker. The +1 also floors an empty
  129. # entry above zero, so a flood of blank ``print()`` lines exhausts the
  130. # budget instead of emitting unbounded zero-cost log frames.
  131. cost = _json_string_cost(raw) + 1
  132. if cost > self._remaining:
  133. self._truncated = True
  134. self._sink(log_truncation_marker(self._max_bytes), truncated=True)
  135. return
  136. self._remaining -= cost
  137. self._sink(text)
  138. class _LogStream(io.TextIOBase):
  139. """A newline-coalescing text stream backed by a :class:`LogBuffer`.
  140. Installed as ``sys.stdout`` / ``sys.stderr`` before executing the model
  141. program. ``print(...)`` calls ``write`` once per argument, separator, and
  142. newline, so a raw one-push-per-write stream would emit
  143. ``["a", " ", "b", "\\n"]`` for ``print("a", "b")`` — and Code Mode renders
  144. ``logs`` with ``join('\\n')``, turning that into spurious blank lines. This
  145. stream instead buffers writes and pushes one LogBuffer entry per completed
  146. LINE (the text up to each ``\\n``, newline stripped), so the rendered join
  147. reproduces ``a b``. Any unterminated tail is flushed by :meth:`flush_line`
  148. after the program settles.
  149. """
  150. def __init__(self, logs: LogBuffer) -> None:
  151. super().__init__()
  152. self._logs = logs
  153. # list-of-chunks, joined only at a newline or flush: repeated
  154. # ``print("x", end="")`` must not concatenate quadratically.
  155. self._pending: list[str] = []
  156. self._pending_chars = 0
  157. def writable(self) -> bool: # noqa: D401 -- inherited contract
  158. return True
  159. def write(self, text: str) -> int: # noqa: D401 -- inherited contract
  160. # Serialize the whole read-modify-write against the settlement flush and
  161. # any other thread's write: model code may spawn daemon threads that keep
  162. # printing after the program body returns, and this method reads
  163. # ``remaining`` and mutates ``_pending``/the ledger across many steps. The
  164. # lock is the buffer's and is re-entrant, so the ``push`` calls below
  165. # (which re-acquire it) do not deadlock.
  166. with self._logs.lock:
  167. return self._write_locked(text)
  168. def _write_locked(self, text: str) -> int:
  169. # Drop an empty write instead of buffering it. An empty chunk adds no
  170. # character, so the budget check below can never fire on it:
  171. # ``while True: sys.stdout.write("")`` would append one list slot per
  172. # call with `_pending_chars` pinned at 0, growing unbounded long after
  173. # the log ledger was exhausted (about 3.7 M slots per CPU second here)
  174. # until RLIMIT_AS turned the allocation into a MemoryError — reported as
  175. # the program's own exception rather than the intended bounded-log
  176. # behavior. Returning here also keeps `flush_line` from pushing a
  177. # spurious empty log entry for a program whose only writes were empty.
  178. if not text:
  179. return 0
  180. if "\n" in text:
  181. # Scan `text` in place; the buffered chunks are joined ONLY into the
  182. # first line. Joining the pending chunks with the whole write first
  183. # made a second copy of that write, which an over-budget write
  184. # cannot afford (measured under a 400 MiB addressSpaceMb: one
  185. # buffered character followed by a 340 MiB write died on MemoryError
  186. # inside the join, reported as the program's own exception, and the
  187. # retained chunks made the settlement `flush_line` fail the same way
  188. # — costing the `done` frame and turning the run into a wall-clock
  189. # timeout instead of the promised truncation marker).
  190. length = len(text)
  191. pos = 0
  192. if self._pending:
  193. newline = text.index("\n")
  194. if self._pending_chars + newline + 3 > self._logs.remaining:
  195. # The reconstructed first line cannot fit the ledger, so
  196. # LogBuffer would reject it whole: copy only the prefix that
  197. # fails its cheap bound and drop the chunks. The slice is
  198. # bounded HERE, not inside the helper: `text[:newline]` on a
  199. # 340 MiB newline-terminated write is the same full copy the
  200. # join was (measured: MemoryError inside `sys.stdout.write`
  201. # under a 400 MiB addressSpaceMb), and `remaining + 4`
  202. # characters are all the helper can use.
  203. self._push_bounded_prefix(text[: min(newline, self._logs.remaining + 4)])
  204. else:
  205. self._pending.append(text[:newline])
  206. line = "".join(self._pending)
  207. self._pending = []
  208. self._pending_chars = 0
  209. self._logs.push(line)
  210. pos = newline + 1
  211. # Scan by offset and STOP once the ledger is exhausted: a single
  212. # write of many newlines (``print("\n" * 1000000)``) would otherwise
  213. # re-slice the tail once per line and keep pushing long after
  214. # LogBuffer truncated, burning the CPU budget on discarded lines.
  215. # `remaining` reads 0 the instant the buffer truncates, so the loop
  216. # exits immediately; the unscanned tail is simply dropped.
  217. while pos < length and self._logs.remaining > 0:
  218. newline = text.find("\n", pos)
  219. if newline < 0:
  220. break
  221. # Bound the SLICE the same way LogBuffer bounds the encode: a
  222. # first line far above the ledger would be copied whole before
  223. # push could reject it, and that copy is the allocation an
  224. # over-budget write cannot afford. Copy only a budget-sized
  225. # prefix, which push still rejects on its own cheap bound (the
  226. # prefix is longer than `remaining`), so the marker is emitted
  227. # and the oversized line is never materialized.
  228. if newline - pos + 3 > self._logs.remaining:
  229. self._logs.push(text[pos:pos + self._logs.remaining + 4])
  230. break
  231. self._logs.push(text[pos:newline])
  232. pos = newline + 1
  233. if pos < length:
  234. if self._logs.remaining > 0:
  235. # Buffer only a budget-sized PREFIX of the tail, not the whole
  236. # `text[pos:]`: an early newline followed by a huge unterminated
  237. # tail (`"\n" + "A" * 30 MiB`) would otherwise copy the entire
  238. # tail into `_pending` here — a second full copy of the model's
  239. # own string, the RLIMIT_AS death this path exists to avoid —
  240. # before the newline-free trigger below could bound it. Anything
  241. # past `remaining` characters cannot be admitted (the char count
  242. # is a lower bound on the serialized cost), so a
  243. # `remaining + 4`-character prefix is all that can ever survive;
  244. # the flush trigger below rejects it and emits the marker.
  245. tail = text[pos:pos + self._logs.remaining + 4]
  246. self._pending.append(tail)
  247. self._pending_chars = len(tail)
  248. else:
  249. # The ledger ran out with text still unscanned, so that text
  250. # IS being dropped and the run must say so. One push is
  251. # enough and is bounded: `remaining` is 0, so LogBuffer's
  252. # cheap length lower bound rejects immediately, emits the
  253. # marker, and never encodes the tail — and a push after the
  254. # marker is already out returns without emitting a second.
  255. # Reaching 0 EXACTLY (65 one-character lines against the
  256. # default 3-byte-per-entry serialized charge) leaves
  257. # `_truncated` unset, so without this the tail vanished with
  258. # no marker at all. Sliced to a budget-sized prefix, not the
  259. # whole tail: the tail can be hundreds of megabytes and the
  260. # copy would be the RLIMIT_AS death this bound exists to
  261. # avoid, while push only needs enough characters to fail its
  262. # own cheap length check.
  263. self._logs.push(text[pos:pos + self._logs.remaining + 4])
  264. else:
  265. self._pending.append(text)
  266. self._pending_chars += len(text)
  267. # A newline-free flood must hit the budget while running, not at
  268. # settlement: once the buffered tail alone can no longer fit the
  269. # ledger (chars lower-bound the serialized cost), push it through — LogBuffer
  270. # truncates, emits the marker once, and swallows everything after.
  271. if self._pending_chars > self._logs.remaining:
  272. self._push_bounded_prefix()
  273. return len(text)
  274. def _push_bounded_prefix(self, extra: str = "") -> None:
  275. # Reached only when the buffered characters already exceed what the
  276. # ledger admits, so LogBuffer is certain to reject on its cheap length
  277. # bound and emit the marker. Copy a budget-sized PREFIX rather than the
  278. # joined whole: ``sys.stdout.write("x")`` followed by one newline-free
  279. # 340 MiB write leaves two chunks whose join is a second copy of the
  280. # payload, and under a tight addressSpaceMb that join raises MemoryError
  281. # from inside `write` — surfacing as the program's own exception, or,
  282. # while the oversized chunks stayed retained, again from `flush_line`
  283. # after the program settled, which cost the `done` frame and turned the
  284. # run into a wall-clock timeout instead of the promised truncation
  285. # marker.
  286. #
  287. # The chunks are dropped BEFORE the push so neither this call nor the
  288. # settlement flush can repeat the allocation, and dropping the text is
  289. # exactly what the marker reports. `remaining + 4` is the shortest
  290. # prefix that still fails LogBuffer's ``len(text) + 3 > remaining``
  291. # check; the accumulation stops there, so the copy is bounded by the log
  292. # budget however large the pending chunks are.
  293. limit = self._logs.remaining + 4
  294. parts: list[str] = []
  295. total = 0
  296. for chunk in (*self._pending, extra):
  297. parts.append(chunk[: limit - total])
  298. total += len(parts[-1])
  299. if total >= limit:
  300. break
  301. self._pending = []
  302. self._pending_chars = 0
  303. self._logs.push("".join(parts))
  304. def flush(self) -> None: # noqa: D401 -- inherited contract
  305. # ``TextIOBase.flush`` is a no-op, so without this override an explicit
  306. # ``print(..., flush=True)`` or ``sys.stdout.flush()`` left the text in
  307. # `_pending` with nothing to drain it except `flush_line` after the
  308. # program settles. A run that then hangs or is killed never reaches that
  309. # call: ``print("before hang", end="", flush=True)`` followed by an
  310. # infinite loop returned `logs: []`, losing the one diagnostic the
  311. # program deliberately committed. Forwarding makes an explicit flush emit
  312. # the pending entry immediately, which is what the caller asked for; a
  313. # newline-terminated write already emitted on its own.
  314. self.flush_line()
  315. def flush_line(self) -> None:
  316. """Push any buffered text not terminated by a newline (also serves explicit flushes)."""
  317. # Same shared, re-entrant lock as ``write``: the settlement flush on the
  318. # main coroutine and a daemon thread's concurrent ``write`` both touch
  319. # ``_pending`` and the ledger, so this read-and-clear must be atomic
  320. # against them.
  321. with self._logs.lock:
  322. if self._pending:
  323. # Join, drop the chunks, THEN push — the same order the newline
  324. # path uses (:232-235). Pushing before the clear would keep the
  325. # pending chunks alive through `_push_locked`'s `text.encode`, so
  326. # the chunks, their join, and the encode copy would all be live at
  327. # once; dropping the chunks first leaves only the join and its
  328. # encode, matching that path's peak.
  329. line = "".join(self._pending)
  330. self._pending = []
  331. self._pending_chars = 0
  332. self._logs.push(line)
  333. # ---------------------------------------------------------------------------
  334. # Fd-3 channel — line-framed JSON.
  335. # ---------------------------------------------------------------------------
  336. class ProtocolChannel:
  337. """Blocking readers and synchronous writers over the fd-3 protocol pipe.
  338. Writes are unbuffered and go straight to the fd, so ``send_sync`` is safe
  339. from inside model code (which may run outside an asyncio task) and from
  340. background tasks alike. Concurrent writers are serialized by ``_write_lock``
  341. around a full-write loop (see ``send_sync``): ``os.write`` releases the GIL,
  342. a frame may exceed ``PIPE_BUF`` (logs up to ``maxLogBytes``, completions up
  343. to ``maxValueBytes``, uncapped ``call`` args), and one ``os.write`` may
  344. consume only part of a frame — so neither the GIL nor per-frame atomicity is
  345. relied on for framing.
  346. """
  347. def __init__(self, fd: int) -> None:
  348. self._fd = fd
  349. # Residual bytes read past a frame's newline, shared by the blocking and
  350. # async readers. Held here, not in the reading coroutine: the reply pump
  351. # is cancelled once `done` is posted, and read-ahead sitting in a local
  352. # would be lost with it. Both readers use `os.read(self._fd, ...)`
  353. # directly, so no buffered file object wraps the fd.
  354. self._pending = bytearray()
  355. # Serializes writers: os.write releases the GIL, and a frame larger
  356. # than PIPE_BUF is neither atomic nor guaranteed fully consumed by one
  357. # call — without the lock, model-created threads printing while a big
  358. # completion frame drains could interleave bytes mid-frame.
  359. self._write_lock = threading.Lock()
  360. def read_frame(self) -> dict[str, Any] | None:
  361. """Read one JSON-line frame (iteratively decoded). ``None`` on EOF.
  362. Blocking. Used for the two frames read BEFORE the model program starts
  363. (``boot`` and ``run``), where blocking is what the handshake wants. Reply
  364. frames arriving during the program go through :meth:`read_frame_async`,
  365. which must not occupy a thread.
  366. Reads in CHUNKS into the shared ``_pending`` buffer rather than through
  367. ``FileIO.readline()``: the fd is unbuffered (``buffering=0``), so
  368. ``readline`` issues one ``os.read(1)`` per byte, and a multi-megabyte
  369. ``run`` frame — RLIMIT_CPU already in force by then — would burn the
  370. budget in millions of syscalls before ``ast.parse`` even runs. The chunk
  371. reads and the same residual buffer the async path uses keep read-ahead
  372. past a newline for the next frame.
  373. """
  374. # Scan only the bytes not yet examined: `find` from a running offset so a
  375. # frame arriving in N chunks costs one linear pass total, not one rescan
  376. # of the whole buffer per chunk (which is quadratic in the frame size).
  377. scanned = 0
  378. while True:
  379. newline = self._pending.find(b"\n", scanned)
  380. if newline >= 0:
  381. line = bytes(self._pending[:newline])
  382. del self._pending[: newline + 1]
  383. return _decode_json_plain(line.decode("utf-8"))
  384. scanned = len(self._pending)
  385. chunk = os.read(self._fd, _READ_CHUNK_BYTES)
  386. if not chunk:
  387. # EOF before a newline: drop the partial line, as the host drops
  388. # a frame that never completed.
  389. return None
  390. self._pending.extend(chunk)
  391. async def read_frame_async(self) -> dict[str, Any] | None:
  392. """Await one JSON-line frame without occupying a thread. ``None`` on EOF.
  393. ``loop.run_in_executor(None, read_frame)`` was the obvious spelling and
  394. the wrong one: the default executor spins up its first thread the moment
  395. the program awaits a binding, and on Linux/glibc that thread's 8 MiB
  396. stack plus a 64 MiB per-thread malloc arena reservation are charged to
  397. ``RLIMIT_AS`` — measured, the child's mappings went from 30.34 MiB to
  398. 102.39 MiB across one ``await tools.*``. Since the limit is already in
  399. force, that ~72 MiB comes straight out of the run's ``addressSpaceMb``:
  400. under a small limit the thread cannot start at all and a legitimate
  401. binding call hangs to ``maxWallMs``, and under a larger one an allocation
  402. that should have fit dies as ``MemoryError``. This is the same accounting
  403. the settlement-time CPU recheck was designed around, where a sampling
  404. thread cost the same 72 MiB.
  405. `loop.add_reader` watches the fd instead, so no thread exists.
  406. Bytes past a frame's newline belong to the next frame, so the residual
  407. lives on the CHANNEL rather than in this coroutine: the pump is cancelled
  408. once ``done`` is posted, and a local buffer would discard whatever it had
  409. read ahead.
  410. """
  411. loop = asyncio.get_event_loop()
  412. # Scan only the not-yet-examined bytes (running offset), so a frame
  413. # arriving across many reads costs one linear pass, not a quadratic
  414. # rescan of the whole buffer per read.
  415. scanned = 0
  416. while True:
  417. newline = self._pending.find(b"\n", scanned)
  418. if newline >= 0:
  419. line = bytes(self._pending[:newline])
  420. del self._pending[: newline + 1]
  421. return _decode_json_plain(line.decode("utf-8"))
  422. scanned = len(self._pending)
  423. ready = loop.create_future()
  424. # `add_reader` only reports readability; the read itself happens here,
  425. # and `os.read` returns whatever is buffered without waiting for more.
  426. loop.add_reader(self._fd, lambda: ready.done() or ready.set_result(None))
  427. try:
  428. await ready
  429. finally:
  430. loop.remove_reader(self._fd)
  431. chunk = os.read(self._fd, _READ_CHUNK_BYTES)
  432. if not chunk:
  433. # EOF. Any partial line is dropped, matching how the host drops a
  434. # frame that never completed.
  435. return None
  436. self._pending.extend(chunk)
  437. def send_sync(self, message: dict[str, Any]) -> None:
  438. """Post one frame synchronously.
  439. Encoded with the iterative :func:`_encode_json_plain` (not
  440. ``json.dumps``, whose per-level recursion would raise
  441. ``RecursionError`` on a deeply nested completion or call argument the
  442. depth-unbounded ``CodeJsonValue`` contract admits). NaN/Infinity still
  443. raise ``ValueError`` — they would serialize as non-standard tokens
  444. that Node's ``JSON.parse`` rejects, silently dropping the frame, and a
  445. call would then hang until the wall clock instead of failing fast.
  446. Callers turn the ``ValueError`` into their own contract error
  447. (dispatch raises the lossless-JSON message).
  448. """
  449. payload = (_encode_json_plain(message) + "\n").encode("utf-8")
  450. # Full-write loop under the writer lock: one os.write may consume only
  451. # part of a frame beyond PIPE_BUF (64 KiB logs / 32 KiB completions /
  452. # uncapped call args exceed it), and a partial or interleaved frame is
  453. # dropped host-side as malformed JSON — the run would then hang to the
  454. # wall clock.
  455. with self._write_lock:
  456. view = memoryview(payload)
  457. while view:
  458. view = view[os.write(self._fd, view):]
  459. # ---------------------------------------------------------------------------
  460. # Tools proxy — turns ``await tools.name(args)`` into a fd-3 call frame.
  461. # ---------------------------------------------------------------------------
  462. class _Namespace:
  463. """A proxy for one binding namespace: every declared name routes to the bridge.
  464. Names arrive from :class:`BootMessage.namespaces`. Both attribute access
  465. (``tools.name``) and subscript access (``tools["my-tool"]`` — the SDK's
  466. escape hatch for exotic or reserved names, which are legal function names
  467. on the wire) return a coroutine factory that posts a ``call`` frame and
  468. awaits the matching ``reply``. An undeclared name raises ``AttributeError``
  469. (attribute) or ``KeyError`` (subscript), matching the worker backend's
  470. own-property discipline.
  471. ``__getattribute__`` (not ``__getattr__``) intercepts attribute access so a
  472. declared name ALWAYS reaches the bridge — even one that collides with an
  473. inherited attribute like ``__class__``, which ordinary lookup would resolve
  474. on ``object`` before ``__getattr__`` ever ran. Internal state lives under
  475. name-mangled ``_Namespace__*`` attributes; a declared binding with such a
  476. name still wins (declared-names check runs first).
  477. """
  478. def __init__(self, global_name: str, names: list[str], dispatch) -> None:
  479. self.__global = global_name
  480. self.__names = set(names)
  481. self.__dispatch = dispatch
  482. def __call_for(self, name: str):
  483. dispatch = object.__getattribute__(self, "_Namespace__dispatch")
  484. global_name = object.__getattribute__(self, "_Namespace__global")
  485. async def call(args: Any) -> Any:
  486. return await dispatch(global_name, name, args)
  487. return call
  488. def __getattribute__(self, name: str):
  489. # Declared names route to the bridge unconditionally — before Python
  490. # can resolve an inherited attribute (``__class__``) or our own
  491. # internals. Everything else falls through to normal lookup so the
  492. # proxy machinery itself keeps working.
  493. names = object.__getattribute__(self, "_Namespace__names")
  494. if name in names:
  495. return object.__getattribute__(self, "_Namespace__call_for")(name)
  496. return object.__getattribute__(self, name)
  497. def __getattr__(self, name: str):
  498. # Reached only when normal lookup found nothing (declared names were
  499. # already intercepted above), so this is always an undeclared tool.
  500. raise AttributeError(
  501. f"tool {name!r} is not declared in namespace "
  502. f"{object.__getattribute__(self, '_Namespace__global')!r}"
  503. )
  504. def __getitem__(self, name: str):
  505. names = object.__getattribute__(self, "_Namespace__names")
  506. if name not in names:
  507. raise KeyError(
  508. f"tool {name!r} is not declared in namespace "
  509. f"{object.__getattribute__(self, '_Namespace__global')!r}"
  510. )
  511. return object.__getattribute__(self, "_Namespace__call_for")(name)
  512. class _BindingRejection(Exception):
  513. """Internal reply-pump rejection, converted by ``dispatch`` into the
  514. namespace's declared error class (or ``RuntimeError``) so the marker type
  515. itself never reaches model code."""
  516. def _make_error_class(name: str, member_name_property: str) -> type:
  517. """Mint one program-visible rejection class per the seam's
  518. ``CodeBindingErrorClass`` contract: instances carry the failed member name
  519. under ``member_name_property`` and render as their message."""
  520. def __init__(self, member_name: str, message: str) -> None: # noqa: N807
  521. Exception.__init__(self, message)
  522. setattr(self, member_name_property, member_name)
  523. return type(name, (Exception,), {"__init__": __init__})
  524. def _clamped(which: int, soft: int, hard: int) -> tuple[int, int]:
  525. """Bound a requested (soft, hard) rlimit pair by BOTH inherited limits.
  526. An unprivileged process may lower a hard limit but never raise it, so a
  527. harness already started under a tighter ceiling (``ulimit -v`` below
  528. ``addressSpaceBytes``, or a CPU cap below ``cpuSeconds`` + 1) would make
  529. ``setrlimit`` raise ``ValueError`` and fail every run — despite the
  530. inherited limit being STRONGER than the one requested. Clamping keeps the
  531. stricter of the two, which still satisfies the containment contract.
  532. Both inherited bounds matter, not just the hard one. A deployment that
  533. inherited a soft limit BELOW what is requested (e.g. inherited ``(100, 200)``,
  534. requested ``(150, 160)``) must keep the stricter soft — returning the
  535. requested ``150`` would RAISE the effective soft limit, loosening RLIMIT_AS
  536. memory or deferring the RLIMIT_CPU SIGXCPU, the opposite of "strictest of
  537. configured and inherited". So each side is clamped against its inherited
  538. counterpart. ``RLIM_INFINITY`` compares as -1, so an infinite inherited bound
  539. imposes no ceiling and the requested value stands.
  540. """
  541. inherited_soft, inherited_hard = resource.getrlimit(which)
  542. clamped_soft = soft if inherited_soft == resource.RLIM_INFINITY else min(soft, inherited_soft)
  543. clamped_hard = hard if inherited_hard == resource.RLIM_INFINITY else min(hard, inherited_hard)
  544. # setrlimit requires soft <= hard. Clamping the two sides independently can
  545. # invert them (a finite inherited soft below the clamped hard is fine, but a
  546. # requested hard below the inherited soft would leave soft > hard), so pin
  547. # soft under hard as the final step; the stricter hard ceiling wins.
  548. return (min(clamped_soft, clamped_hard), clamped_hard)
  549. # ---------------------------------------------------------------------------
  550. # Main.
  551. # ---------------------------------------------------------------------------
  552. async def _run(channel: ProtocolChannel) -> None:
  553. # 1. Boot handshake.
  554. boot = channel.read_frame()
  555. if boot is None or boot.get("type") != "boot":
  556. raise RuntimeError("bootstrap: expected boot frame on fd 3")
  557. # A limit that cannot be applied must fail the run as a diagnosable done
  558. # frame, not a bare traceback + exit(1): running the program UNCAPPED would
  559. # silently void the containment contract, and the host can only relay what
  560. # rides the protocol.
  561. try:
  562. # SIGXCPU's default disposition (how the soft CPU limit stops the child)
  563. # dumps core, and the child inherits the host's RLIMIT_CORE — a CPU
  564. # timeout would otherwise write a large memory-bearing core file into
  565. # the workspace. Forbid core dumps first so the timeout path leaves none.
  566. resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
  567. # Soft limit at cpuSeconds fires SIGXCPU (its default disposition
  568. # terminates the child; the host classifies that close as a timeout).
  569. # Hard limit at +1s is a SIGKILL backstop for a program that traps
  570. # SIGXCPU and keeps burning CPU.
  571. cpu_soft, cpu_hard = _clamped(
  572. resource.RLIMIT_CPU, boot["cpuSeconds"], boot["cpuSeconds"] + 1
  573. )
  574. resource.setrlimit(resource.RLIMIT_CPU, (cpu_soft, cpu_hard))
  575. # Darwin maps the multi-GB dyld shared cache into every process at
  576. # exec, so any practical RLIMIT_AS cap sits below current usage and
  577. # the kernel rejects it — the child would die here on every run. Skip
  578. # the address-space cap there; RLIMIT_CPU and the host's wall-clock
  579. # ceiling still bound the run.
  580. if sys.platform != "darwin":
  581. addr_bytes = int(boot["addressSpaceBytes"])
  582. effective_as = _clamped(resource.RLIMIT_AS, addr_bytes, addr_bytes)
  583. resource.setrlimit(resource.RLIMIT_AS, effective_as)
  584. # The host rejected an output budget too large for the CONFIGURED
  585. # addressSpaceMb, but a launch environment can inherit a STRICTER
  586. # RLIMIT_AS (e.g. a `ulimit -v` wrapper below addressSpaceMb), which
  587. # `_clamped` correctly lowers the effective limit to — leaving the
  588. # budgets validated against a ceiling the child never gets. Re-check
  589. # both budgets against the EFFECTIVE soft limit here, mirroring the
  590. # host gate (each budget times the worst-case Unicode multiple must
  591. # fit the room left after the interpreter baseline), and fail loud at
  592. # boot rather than letting a near-budget output OOM mid-run. The
  593. # constants match src/index.ts's OUTPUT_BUDGET_WORST_CASE_ADDRESS_
  594. # SPACE_MULTIPLE and INTERPRETER_BASELINE_BYTES.
  595. effective_soft = effective_as[0]
  596. if effective_soft != resource.RLIM_INFINITY:
  597. budgetable = effective_soft - _INTERPRETER_BASELINE_BYTES
  598. for _budget_key in ("maxLogBytes", "maxValueBytes"):
  599. if int(boot[_budget_key]) * _OUTPUT_BUDGET_WORST_CASE_MULTIPLE >= budgetable:
  600. raise ValueError(
  601. "config.%s is too large for the inherited RLIMIT_AS of %d bytes "
  602. "(a near-budget output would breach it during encode); "
  603. "lower the budget or raise the inherited address-space limit"
  604. % (_budget_key, effective_soft)
  605. )
  606. except BaseException as exc: # noqa: BLE001 -- report every failure to host
  607. channel.send_sync(
  608. {
  609. "type": "done",
  610. "error": {
  611. "kind": "exception",
  612. # Exception-only rendering: format_exc() would embed the
  613. # absolute installed bootstrap.py path in model-visible
  614. # durable output, leaking host paths into transcripts.
  615. "message": "bootstrap: applying resource limits failed\n"
  616. + "".join(
  617. traceback.format_exception_only(type(exc), exc)
  618. ),
  619. },
  620. }
  621. )
  622. return
  623. logs = LogBuffer(
  624. int(boot["maxLogBytes"]),
  625. sink=lambda text, truncated=False: channel.send_sync(
  626. {"type": "log", "text": text, **({"truncated": True} if truncated else {})}
  627. ),
  628. )
  629. # 2. Wire the tools proxies and the ack.
  630. #
  631. # Each entry records the reply Future AND the loop it was created on. Model
  632. # code may call a binding from a THREAD it started, spelled
  633. # ``asyncio.run(tools.x(...))`` or its own new loop in that thread, so a
  634. # Future here can belong to a loop other than the one ``_pump_replies`` runs
  635. # on. ``asyncio.Future`` is not thread-safe: completing it from another
  636. # thread does not wake its own loop, so the pump schedules the completion on
  637. # the owning loop via ``call_soon_threadsafe`` (see ``_pump_replies``) rather
  638. # than calling ``set_result`` directly.
  639. pending: dict[int, tuple[asyncio.AbstractEventLoop, asyncio.Future[Any]]] = {}
  640. next_id = 0
  641. # Serializes the id claim + write + counter advance in ``dispatch`` against
  642. # both other binding-calling threads and the pump's ``pop``. ``dispatch`` may
  643. # run concurrently on several loops/threads, and the host answers a ``call``
  644. # only when its id is the exact successor of the last one — so ids must reach
  645. # the wire in the order they are claimed. Holding this lock across the write
  646. # (not just the counter arithmetic) is what keeps two threads' frames from
  647. # interleaving on fd 3 out of id order, which the host would reject.
  648. pending_lock = threading.Lock()
  649. error_classes: dict[str, type] = {}
  650. async def dispatch(global_name: str, name: str, args: Any) -> Any:
  651. nonlocal next_id
  652. error_class = error_classes.get(global_name)
  653. def call_failure(message: str) -> BaseException:
  654. # The namespace's declared rejection contract (e.g. Code Mode's
  655. # ToolCallError with .toolName) when present; RuntimeError keeps
  656. # the pre-errorClass behavior for namespaces that declared none.
  657. if error_class is not None:
  658. return error_class(name, message)
  659. return RuntimeError(message)
  660. # Validate the argument shape before claiming an id, so a rejected call
  661. # leaves no gap in the sequence the host checks. json.dumps would coerce
  662. # a non-string dict key or non-finite float rather than raise (allow_nan
  663. # is off, but key coercion still slips through), silently corrupting what
  664. # the tool receives. Reject up front through the call's error contract.
  665. violation = _lossless_json_violation(args)
  666. if violation is not None:
  667. raise call_failure(f"binding arguments must be lossless JSON ({violation})")
  668. # Ids are consecutive from 0 with NO gaps: the host answers a `call` only
  669. # when its id is the exact successor of the last one, which bounds the
  670. # state it retains to a single number. A frame that never reaches the
  671. # host must therefore not consume an id, so the counter advances only
  672. # once the write has succeeded.
  673. #
  674. # The whole claim-write-advance runs under ``pending_lock`` because a
  675. # binding may be called from more than one thread/loop at once (the model
  676. # can start a thread that runs ``asyncio.run(tools.x(...))``). Without
  677. # the lock two callers could claim the same id, or write their frames to
  678. # fd 3 in an order that does not match their ids — either of which the
  679. # host rejects as an out-of-sequence call. The Future's own loop is
  680. # captured here so ``_pump_replies`` can complete it thread-safely.
  681. loop = asyncio.get_event_loop()
  682. with pending_lock:
  683. call_id = next_id
  684. fut: asyncio.Future[Any] = loop.create_future()
  685. pending[call_id] = (loop, fut)
  686. try:
  687. channel.send_sync(
  688. {
  689. "type": "call",
  690. "id": call_id,
  691. "global": global_name,
  692. "name": name,
  693. "args": args,
  694. }
  695. )
  696. except (TypeError, ValueError) as exc:
  697. pending.pop(call_id, None)
  698. raise call_failure(
  699. f"binding arguments must be lossless JSON: {exc}"
  700. ) from exc
  701. next_id += 1
  702. try:
  703. return await fut
  704. except _BindingRejection as exc:
  705. raise call_failure(str(exc)) from None
  706. namespaces: dict[str, Any] = {}
  707. for entry in boot["namespaces"]:
  708. namespaces[entry["global"]] = _Namespace(
  709. entry["global"], entry["names"], dispatch
  710. )
  711. declared = entry.get("errorClass")
  712. if declared:
  713. error_class = _make_error_class(
  714. declared["name"], declared["memberNameProperty"]
  715. )
  716. error_classes[entry["global"]] = error_class
  717. # The class is program-visible under its own name so model code
  718. # can `except ToolCallError as e:` and read the member property.
  719. namespaces[declared["name"]] = error_class
  720. channel.send_sync({"type": "boot-ack"})
  721. # 3. Start a reply-pump task before the run message: replies can arrive
  722. # interleaved with the run's own binding traffic.
  723. reply_task = asyncio.get_event_loop().create_task(
  724. _pump_replies(channel, pending, pending_lock)
  725. )
  726. # 4. Read the run message.
  727. run = channel.read_frame()
  728. if run is None or run.get("type") != "run":
  729. reply_task.cancel()
  730. raise RuntimeError("bootstrap: expected run frame on fd 3")
  731. program: str = run["program"]
  732. # 5. Install log capture — ``print``, tracebacks, and ordinary ``sys.stdout``
  733. # writes funnel into the LogBuffer. The real fds stay open (host uses
  734. # stderr for stray-byte accounting) but the Python-visible streams point
  735. # at the buffer.
  736. sys.stdout = _LogStream(logs) # type: ignore[assignment]
  737. sys.stderr = _LogStream(logs) # type: ignore[assignment]
  738. out_stream, err_stream = sys.stdout, sys.stderr
  739. # 6. Compile the program as the body of an async function, matching the
  740. # seam contract (`CodeRunRequest.program` is an async-function body: top-level
  741. # `await` and `return` both work, and the returned value is the completion).
  742. # AST-splicing the parsed body into an `async def` keeps every statement's
  743. # original line number, so a traceback points at the model's own source.
  744. ns: dict[str, Any] = {
  745. "__name__": "__main__",
  746. "__builtins__": __builtins__,
  747. **namespaces,
  748. }
  749. # Read the enforcement callable and its budget into this frame's locals
  750. # BEFORE the program runs: model code can rebind this module's globals
  751. # (the bootstrap IS ``__main__``), and a frame local is not a module
  752. # attribute, so a later ``__main__._DIE_IF_CPU_EXHAUSTED = ...`` cannot
  753. # change which callable the post-check below invokes. This defeats the
  754. # one-line rebind, not a determined `sys._getframe` walk; the unforgeable
  755. # bounds are the RLIMIT_CPU hard limit and the host wall clock
  756. # (see _make_cpu_enforcer).
  757. die_if_cpu_exhausted = _DIE_IF_CPU_EXHAUSTED
  758. # The settlement recheck compares against the EFFECTIVE soft CPU limit
  759. # (`cpu_soft`, clamped to any stricter inherited limit above), NOT the
  760. # configured `cpuSeconds`. When the deployment inherited a soft limit below
  761. # the configured value, a program that traps SIGXCPU, burns past the
  762. # inherited soft, and returns inside the soft-to-hard gap must be reported as
  763. # a timeout — checking the configured value would falsely pass it and bypass
  764. # the inherited limit.
  765. cpu_seconds = cpu_soft
  766. # Same capture, same reason, for the failure path and the send that follows
  767. # it. The reporter was a module-global lookup inside the `except` block, so
  768. # ``import __main__; __main__._SAFE_MODEL_TRACEBACK = ...`` put model code
  769. # there with no guard around it; the flush and send were attribute lookups
  770. # on the stream and channel CLASSES, which ``__main__._LogStream.flush_line
  771. # = ...`` rebinds just as easily. All four run AFTER the handler, where a
  772. # throw costs the `done` frame and the host reports a wall-clock timeout
  773. # instead of the model's exception. Binding the callables now fixes what
  774. # runs; what they in turn reach is closed over in _make_failure_reporter.
  775. safe_model_traceback = _SAFE_MODEL_TRACEBACK
  776. flush_out = out_stream.flush_line
  777. flush_err = err_stream.flush_line
  778. send_done = channel.send_sync
  779. max_value_bytes = int(boot["maxValueBytes"])
  780. done: dict[str, Any]
  781. try:
  782. module = ast.parse(program)
  783. wrapper = ast.AsyncFunctionDef(
  784. name="__dsh_main__",
  785. args=ast.arguments(
  786. posonlyargs=[], args=[], vararg=None,
  787. kwonlyargs=[], kw_defaults=[], kwarg=None, defaults=[],
  788. ),
  789. body=module.body or [ast.Pass()],
  790. decorator_list=[],
  791. returns=None,
  792. )
  793. # Anchor the synthetic wrapper on the first real statement (or line 1 for
  794. # an empty program) so fix_missing_locations does not stamp it at 0.
  795. anchor = module.body[0] if module.body else ast.parse("pass").body[0]
  796. ast.copy_location(wrapper, anchor)
  797. wrapped = ast.Module(body=[wrapper], type_ignores=[])
  798. ast.fix_missing_locations(wrapped)
  799. code = compile(wrapped, "<model>", "exec")
  800. exec(code, ns) # noqa: S102 -- defines __dsh_main__; executing model code is the point
  801. value = await ns["__dsh_main__"]()
  802. die_if_cpu_exhausted(cpu_seconds)
  803. # Flush the log buffers BEFORE metering and framing the completion value.
  804. # `_done_with_value` materializes the value's escaped JSON form to meter
  805. # it, and `send_done` encodes the frame — several copies of a near-budget
  806. # value live at once (see OUTPUT_BUDGET_WORST_CASE_ADDRESS_SPACE_MULTIPLE).
  807. # Any unflushed log pending would add its own bytes to that peak, so a
  808. # `maxLogBytes` and a `maxValueBytes` each admitted alone by the load gate
  809. # could together breach RLIMIT_AS. Flushing first frees the log pending so
  810. # the value frame's peak stands alone against the address space.
  811. flush_out()
  812. flush_err()
  813. done = _done_with_value(value, max_value_bytes)
  814. except BaseException as exc: # noqa: BLE001 -- report every failure to host
  815. done = {
  816. "type": "done",
  817. "error": {
  818. "kind": "exception",
  819. # Cap the diagnostic BEFORE it crosses the wire: a program can
  820. # raise with a gigabytes-long message, and formatting/sending
  821. # it whole would allocate on both sides before the host's own
  822. # cap runs. Byte-cap at maxValueBytes with the host's marker
  823. # text so the truncated diagnostic reads identically wherever
  824. # the cap was applied. The rendering is wrapped because the
  825. # `done` send below sits outside this handler: a throw while
  826. # formatting would skip it and strand the host on fd 3 until
  827. # maxWallMs (see _make_failure_reporter).
  828. "message": safe_model_traceback(exc, max_value_bytes),
  829. },
  830. }
  831. # Flush any print output not terminated by a newline (a traceback always
  832. # ends in one, but `print(x, end="")` or a bare write may not), so the
  833. # final partial line is not silently dropped. The success path already
  834. # flushed before framing the value; this is an idempotent no-op there and
  835. # the flush the exception path needs.
  836. flush_out()
  837. flush_err()
  838. reply_task.cancel()
  839. send_done(done)
  840. async def _pump_replies(
  841. channel: ProtocolChannel,
  842. pending: dict[int, tuple[asyncio.AbstractEventLoop, asyncio.Future[Any]]],
  843. pending_lock: "threading.Lock",
  844. ) -> None:
  845. """Background task: read reply frames and settle pending futures.
  846. Cancelled after ``done`` is posted. Unknown ids and post-settlement replies
  847. are ignored (mirrors the worker backend's hostile-peer stance, though here
  848. the host is the trusted side; the guards defend against races).
  849. A pending Future may belong to a loop other than this pump's — the model can
  850. call a binding from a thread running its own loop (``asyncio.run(tools.x())``).
  851. ``asyncio.Future`` is not thread-safe, so the completion is scheduled on the
  852. Future's OWN loop via ``call_soon_threadsafe`` rather than mutated here; a
  853. direct ``set_result`` would never wake the waiting loop and the call would
  854. hang to the wall clock. The ``pop`` shares ``pending_lock`` with ``dispatch``
  855. so a reply cannot race the claim that registers its id.
  856. """
  857. def complete(fut: asyncio.Future[Any], ok: bool, value: Any, message: Any) -> None:
  858. # Runs on the Future's own loop. `done()` re-checked here because
  859. # cancellation or a duplicate reply may have settled it between the pop
  860. # and this callback.
  861. if fut.done():
  862. return
  863. if ok:
  864. fut.set_result(value)
  865. else:
  866. fut.set_exception(_BindingRejection(str(message)))
  867. while True:
  868. frame = await channel.read_frame_async()
  869. if frame is None:
  870. return
  871. if frame.get("type") != "reply":
  872. continue
  873. with pending_lock:
  874. entry = pending.pop(frame.get("id"), None)
  875. if entry is None:
  876. continue
  877. loop, fut = entry
  878. ok = bool(frame.get("ok"))
  879. value = frame.get("value")
  880. message = frame.get("message")
  881. try:
  882. loop.call_soon_threadsafe(complete, fut, ok, value, message)
  883. except RuntimeError:
  884. # The Future's loop has already closed — the thread that ran
  885. # `asyncio.run(tools.x(...))` finished (its coroutine was cancelled
  886. # or it exited) before this reply arrived, so nothing awaits the
  887. # Future and the reply is moot. Drop it; scheduling onto a closed
  888. # loop raises RuntimeError, and letting that escape would kill the
  889. # pump and strand every later reply — the exact failure class this
  890. # cross-loop delivery exists to prevent. An abandoned call's pending
  891. # entry is not leaked: it is popped here when its reply arrives
  892. # (dispatch's cancellation does not remove it), so stranded entries
  893. # are bounded by the number of calls THIS run itself issued.
  894. continue
  895. # Non-string scalars only. The string form is scanned by hand in
  896. # :func:`_decode_json_plain` because a ``(?:[^"\\]|\\.)*`` repetition makes
  897. # CPython's backtracking engine retain per-repetition state proportional to the
  898. # string's WIDTH: measured at ~146 MiB of engine state for a 1 MiB string and
  899. # ~558 MiB for 4 MiB, so a legitimate multi-megabyte binding reply raised
  900. # MemoryError out of ``_pump_replies``, leaving its future unsettled until the
  901. # wall clock reported a timeout.
  902. _SCALAR_RE = re.compile(
  903. r'-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null'
  904. )
  905. # A run of ordinary string body characters. The star applies to a CHARACTER
  906. # CLASS, which the engine matches in one linear pass with no backtracking state,
  907. # so the scanner's cost is the number of escapes, not the string's width.
  908. _STRING_CHUNK_RE = re.compile(r'[^"\\]*')
  909. def _decode_json_plain(text: str) -> Any:
  910. """Parse one JSON document iteratively (no per-level recursion).
  911. ``json.loads`` recurses per nesting level and raises ``RecursionError``
  912. around ~10k levels, but a binding reply is depth-unbounded by the seam
  913. contract — the host's iterative encoder happily produces documents
  914. ``json.loads`` cannot read back. Scalars (numbers, strings with escapes)
  915. are delegated to ``json.loads`` one token at a time, so their grammar and
  916. semantics stay CPython's own; only the container structure is parsed here
  917. with an explicit stack. Raises ``ValueError`` on malformed input; frames
  918. come from the TRUSTED host, so strictness mirrors ``json.loads`` without
  919. extra hostile-input hardening.
  920. """
  921. length = len(text)
  922. def skip_ws(i: int) -> int:
  923. while i < length and text[i] in " \t\n\r":
  924. i += 1
  925. return i
  926. def scan_string(i: int) -> int:
  927. # Walk chunk by chunk: each match consumes every character up to the next
  928. # quote or backslash, so an escape costs one extra step and a plain body
  929. # costs one pass. Returns the offset just past the closing quote.
  930. j = i + 1
  931. while True:
  932. j = _STRING_CHUNK_RE.match(text, j).end()
  933. if j >= length:
  934. raise ValueError(f"unterminated string at offset {i}")
  935. char = text[j]
  936. if char == '"':
  937. return j + 1
  938. # text[j] is a backslash: skip it and the character it escapes. A
  939. # trailing backslash runs j past `length`, caught on the next pass.
  940. j += 2
  941. def scalar(i: int):
  942. if i < length and text[i] == '"':
  943. end = scan_string(i)
  944. return json.loads(text[i:end]), end
  945. match = _SCALAR_RE.match(text, i)
  946. if match is None:
  947. raise ValueError(f"invalid JSON at offset {i}")
  948. return json.loads(match.group(0)), match.end()
  949. def string_key(i: int):
  950. key, end = scalar(i)
  951. if not isinstance(key, str):
  952. raise ValueError(f"object key must be a string at offset {i}")
  953. end = skip_ws(end)
  954. if end >= length or text[end] != ":":
  955. raise ValueError(f"expected ':' at offset {end}")
  956. return key, skip_ws(end + 1)
  957. # Frames: a list, or (dict, pending key). `value`/`have_value` carry each
  958. # completed value up to its parent frame.
  959. stack: list[Any] = []
  960. value: Any = None
  961. have_value = False
  962. i = skip_ws(0)
  963. while True:
  964. if not have_value:
  965. ch = text[i] if i < length else ""
  966. if ch == "[":
  967. i = skip_ws(i + 1)
  968. if i < length and text[i] == "]":
  969. i += 1
  970. value, have_value = [], True
  971. else:
  972. stack.append([])
  973. continue
  974. elif ch == "{":
  975. i = skip_ws(i + 1)
  976. if i < length and text[i] == "}":
  977. i += 1
  978. value, have_value = {}, True
  979. else:
  980. key, i = string_key(i)
  981. stack.append(({}, key))
  982. continue
  983. else:
  984. value, i = scalar(i)
  985. have_value = True
  986. if not stack:
  987. i = skip_ws(i)
  988. if i != length:
  989. raise ValueError(f"trailing data at offset {i}")
  990. return value
  991. top = stack[-1]
  992. i = skip_ws(i)
  993. ch = text[i] if i < length else ""
  994. if isinstance(top, list):
  995. top.append(value)
  996. if ch == ",":
  997. i = skip_ws(i + 1)
  998. have_value = False
  999. elif ch == "]":
  1000. i += 1
  1001. stack.pop()
  1002. value = top
  1003. else:
  1004. raise ValueError(f"expected ',' or ']' at offset {i}")
  1005. else:
  1006. container, key = top
  1007. container[key] = value
  1008. if ch == ",":
  1009. key, i = string_key(skip_ws(i + 1))
  1010. stack[-1] = (container, key)
  1011. have_value = False
  1012. elif ch == "}":
  1013. i += 1
  1014. stack.pop()
  1015. value = container
  1016. else:
  1017. raise ValueError(f"expected ',' or '}}' at offset {i}")
  1018. def _encode_json_plain(value: Any) -> str:
  1019. """Encode JSON-plain data iteratively, byte-identical to compact ``json.dumps``.
  1020. ``json.dumps`` recurses one Python frame per nesting level and raises
  1021. ``RecursionError`` a few thousand levels deep, but the seam's
  1022. ``CodeJsonValue`` has no depth limit — a valid deeply nested completion or
  1023. call argument below the byte budget must cross intact (the host uses the
  1024. same iterative idiom in ``protocol.ts``). Accepts what the callers already
  1025. validated or constructed: ``None``/``bool``/``int``/finite ``float``/
  1026. ``str``, exact ``list``/``tuple``, and exact ``dict`` with ``str`` keys.
  1027. Scalar encoding delegates to ``json.dumps`` (string escaping, float repr)
  1028. so the bytes match; non-finite floats still raise ``ValueError`` exactly
  1029. like ``allow_nan=False``.
  1030. Containers are classified by EXACT type and traversed through the unbound
  1031. built-in methods rather than the instance's own: a ``dict``/``list``
  1032. subclass can override ``items``, ``keys``, ``__iter__``, ``__len__``, or
  1033. ``__getitem__``, and the validators only see the container it subclasses,
  1034. so an instance-method call here could emit different data than the walk
  1035. that metered and approved it. ``_check_done_value`` and
  1036. ``_lossless_json_violation`` reject subclasses outright, so this path only
  1037. ever sees exact containers; classifying on exact type keeps that agreement
  1038. checkable at one glance instead of resting on the caller.
  1039. """
  1040. # O(DEPTH) auxiliary space, not O(width). A container pushes ONE cursor frame
  1041. # that pulls its children one at a time and writes each into the shared buffer,
  1042. # rather than one stack entry (plus a separator marker) per child: a flat
  1043. # `[0] * 6_000_000` encodes to ~12 MB but per-element frames are ~400 MB — an
  1044. # RLIMIT_AS death on a value `_check_done_value` already admitted (which now
  1045. # walks in O(depth) too). The output string is the only width-proportional
  1046. # allocation, and its size the caller metered within budget. `io.StringIO`
  1047. # accumulates without the intermediate `"".join(chunks)` second copy. A cursor
  1048. # frame is [kind, iterator, wrote_any]; a visit frame is (VISIT, value).
  1049. buffer = io.StringIO()
  1050. exhausted = object()
  1051. visit, list_cursor, dict_cursor = 0, 1, 2
  1052. stack: list[Any] = [(visit, value)]
  1053. while stack:
  1054. frame = stack.pop()
  1055. kind = frame[0]
  1056. if kind == list_cursor:
  1057. iterator, wrote_any = frame[1], frame[2]
  1058. child = next(iterator, exhausted)
  1059. if child is exhausted:
  1060. buffer.write("]")
  1061. continue
  1062. if wrote_any:
  1063. buffer.write(",")
  1064. else:
  1065. frame[2] = True
  1066. stack.append(frame)
  1067. stack.append((visit, child))
  1068. continue
  1069. if kind == dict_cursor:
  1070. iterator, wrote_any = frame[1], frame[2]
  1071. entry = next(iterator, exhausted)
  1072. if entry is exhausted:
  1073. buffer.write("}")
  1074. continue
  1075. key, item = entry
  1076. if wrote_any:
  1077. buffer.write(",")
  1078. else:
  1079. frame[2] = True
  1080. buffer.write(_dump_scalar(key))
  1081. buffer.write(":")
  1082. stack.append(frame)
  1083. stack.append((visit, item))
  1084. continue
  1085. current = frame[1]
  1086. current_type = type(current)
  1087. if current_type is list or current_type is tuple:
  1088. buffer.write("[")
  1089. stack.append([list_cursor, iter(current), False])
  1090. elif current_type is dict:
  1091. buffer.write("{")
  1092. stack.append([dict_cursor, iter(dict.items(current)), False])
  1093. else:
  1094. buffer.write(_dump_scalar(current))
  1095. return buffer.getvalue()
  1096. def _dump_scalar(value: Any) -> str:
  1097. """One scalar as compact JSON, byte-compatible with the host's encoder.
  1098. ``ensure_ascii=False`` keeps non-ASCII text as raw UTF-8 — the default
  1099. backslash-u escaping would make the child count ``"é"`` as 8 bytes where
  1100. the host meter (and the worker backend) count its UTF-8 JSON form as 4,
  1101. splitting the budget the two sides are supposed to share. Strings route
  1102. through :func:`_dump_string`, which restores the escaping for the one class
  1103. of character UTF-8 cannot hold. Floats route through :func:`_dump_float`
  1104. because CPython's ``repr`` and ECMAScript's Number-to-String disagree on
  1105. spelling.
  1106. Dispatch is on EXACT type, matching the validators: a ``float`` subclass
  1107. reaching :func:`_dump_float` would have its overridden ``__repr__`` read as
  1108. the number's digits, so ``F(2.5)`` whose ``__repr__`` returns ``"1.0"``
  1109. would serialize as ``1``. ``json.dumps`` then refuses any subclass by
  1110. ``TypeError`` instead of emitting a value nothing validated; the callers
  1111. reject subclasses first, so this is the encoder refusing to be the place a
  1112. validation gap turns into corrupted output.
  1113. """
  1114. if type(value) is float:
  1115. return _dump_float(value)
  1116. if type(value) is str:
  1117. return _dump_string(value)
  1118. if value is None or type(value) is bool or type(value) is int:
  1119. return json.dumps(value, ensure_ascii=False, allow_nan=False)
  1120. raise TypeError(f"unsupported type ({type(value).__name__})")
  1121. # A surrogate code unit, and an adjacent high-low pair. Python stores an astral
  1122. # character as ONE code point, so a surrogate reaching these patterns is either
  1123. # lone or half of a pair the program spelled out code unit by code unit.
  1124. _SURROGATE = re.compile("[\ud800-\udfff]")
  1125. _SURROGATE_PAIR = re.compile("[\ud800-\udbff][\udc00-\udfff]")
  1126. def _combine_surrogate_pair(match: re.Match[str]) -> str:
  1127. """Fold one spelled-out high-low pair into the astral code point it names."""
  1128. high, low = match.group(0)
  1129. return chr(0x10000 + ((ord(high) - 0xD800) << 10) + (ord(low) - 0xDC00))
  1130. def _dump_string(text: str) -> str:
  1131. """One string as compact JSON, byte-identical to the host's ``JSON.stringify``.
  1132. ``ensure_ascii=False`` cannot render a surrogate code unit: UTF-8 has no
  1133. encoding for one, so the frame write would raise and the run would strand
  1134. until the wall clock. JSON carries it as the ASCII escape ``\\ud800``, which
  1135. the host's ``JSON.parse`` reads back as the same UTF-16 code unit and its
  1136. ``JSON.stringify`` re-emits identically — so the shared seam
  1137. (``CodeJsonValue``, ``snapshotJsonValue``, the worker backend) keeps a
  1138. lone-surrogate string instead of failing the value. An adjacent high-low
  1139. pair is folded into its astral code point FIRST: the host holds strings as
  1140. UTF-16, where those two code units and the single character are the same
  1141. string, and the raw 4-byte form is what the host would emit — escaping the
  1142. halves separately would charge 12 bytes against a budget the host meters at
  1143. 4. Every remaining surrogate is lone and becomes six ASCII bytes, matching
  1144. the host exactly.
  1145. @param text: the string to encode.
  1146. @return: its compact JSON form, always UTF-8-encodable.
  1147. """
  1148. rendered = json.dumps(text, ensure_ascii=False)
  1149. if _SURROGATE.search(rendered) is None:
  1150. return rendered
  1151. return _SURROGATE.sub(
  1152. lambda match: "\\u%04x" % ord(match.group(0)),
  1153. _SURROGATE_PAIR.sub(_combine_surrogate_pair, rendered),
  1154. )
  1155. # How many bytes each byte that needs escaping adds beyond its raw self, as a
  1156. # ready-made (byte, surcharge) list so :func:`_json_string_cost` walks no
  1157. # branches per pass. ``"`` and ``\\`` take a one-character prefix; the five C0
  1158. # controls with a shorthand (``\\b\\f\\n\\r\\t``) likewise; every other C0
  1159. # control becomes a six-character ``\\uXXXX``.
  1160. _JSON_ESCAPE_SURCHARGES = [
  1161. (bytes((byte,)), 1 if byte in b'"\\\b\f\n\r\t' else 5)
  1162. for byte in [*range(0x20), ord('"'), ord("\\")]
  1163. ]
  1164. # Per-byte JSON-string serialized cost (the byte itself plus its escape
  1165. # surcharge), indexed by byte value. Lets :func:`_cap_message` accumulate the
  1166. # serialized cost of a growing prefix in one O(1) step per byte without building
  1167. # the escaped form. A non-ASCII byte stays raw (cost 1); a C0 control or ``"``/
  1168. # ``\\`` carries its surcharge from :data:`_JSON_ESCAPE_SURCHARGES`.
  1169. _JSON_BYTE_COST = [1] * 256
  1170. for _escaped_byte, _surcharge in _JSON_ESCAPE_SURCHARGES:
  1171. _JSON_BYTE_COST[_escaped_byte[0]] = 1 + _surcharge
  1172. def _json_str_cost(text: str) -> int:
  1173. """Byte length of ``text``'s JSON string form, WITHOUT building that form.
  1174. The str-side twin of :func:`_json_string_cost`, for the completion-value
  1175. meter. Measuring by materializing ``_dump_string(text).encode()`` allocates
  1176. the escaped copy plus its encode -- for a NUL-heavy string that is ~6x the
  1177. original each, so metering a value the budget would have REJECTED could
  1178. itself breach ``RLIMIT_AS`` and report ``exception`` where the contract
  1179. promises ``output-limit``.
  1180. The common case encodes once (~1x, well inside the load gate's envelope) and
  1181. counts escapes with the same C-level passes :func:`_json_string_cost` uses.
  1182. A string carrying surrogate code units has no UTF-8 form at all, so it takes
  1183. the exact path :func:`_dump_string` defines: fold each spelled-out high-low
  1184. pair into its astral character first (the host meters that as its raw 4-byte
  1185. form), then charge six ASCII bytes for every surviving lone surrogate and
  1186. count the rest from its encodable remainder.
  1187. @param text: the string to measure.
  1188. @return: the byte length of its JSON string form, quotes included.
  1189. """
  1190. try:
  1191. return _json_string_cost(text.encode("utf-8"))
  1192. except UnicodeEncodeError:
  1193. pass
  1194. folded = _SURROGATE_PAIR.sub(_combine_surrogate_pair, text)
  1195. lone = len(_SURROGATE.findall(folded))
  1196. # Six ASCII bytes per lone surrogate; the remainder is ordinary text whose
  1197. # own quotes are dropped here because the outer call adds them once.
  1198. without = _SURROGATE.sub("", folded)
  1199. return _json_string_cost(without.encode("utf-8")) + lone * 6
  1200. def _json_string_cost(raw: bytes) -> int:
  1201. """UTF-8 byte length of one string's JSON form, WITHOUT building that form.
  1202. Used by :class:`LogBuffer` to charge a log entry what it will actually cost
  1203. on the wire. Building ``json.dumps(text)`` to measure it would allocate a
  1204. second copy up to six times the original — the very allocation the ledger's
  1205. cheap pre-check exists to avoid, and enough to breach ``RLIMIT_AS`` on a
  1206. large control-heavy line. Counts exactly what :func:`_dump_scalar`'s
  1207. ``ensure_ascii=False`` output holds: the two quotes, each escaped byte's
  1208. surcharge from :data:`_JSON_ESCAPE_SURCHARGES`, and the raw bytes themselves
  1209. (non-ASCII stays raw, so its UTF-8 length already counts). Uses a fixed
  1210. number of C-level ``count`` passes — allocating nothing, unlike a
  1211. ``translate`` filter — because the caller admits up to ~4x the remaining
  1212. budget of bytes here and a per-byte Python loop over it would cost more than
  1213. the encode being avoided.
  1214. @param raw: the entry's UTF-8 bytes.
  1215. @return: the byte length of its JSON string form, quotes included.
  1216. """
  1217. extra = 0
  1218. for byte, surcharge in _JSON_ESCAPE_SURCHARGES:
  1219. extra += raw.count(byte) * surcharge
  1220. return len(raw) + 2 + extra
  1221. def _dump_float(value: float) -> str:
  1222. """One finite float in ECMAScript ``Number::toString`` spelling.
  1223. CPython's ``repr`` and the host's ``String(number)`` name the same double
  1224. differently: ``1.0`` is ``"1.0"`` here but ``"1"`` there, ``1e-07`` pads the
  1225. exponent the host writes as ``1e-7``, and ``1e+21``/``2**60`` differ again.
  1226. Since the child meters the completion value against ``maxValueBytes`` and
  1227. the host re-meters the frame it parses, any spelling difference splits the
  1228. shared budget: ``return 1.0`` under ``maxValueBytes: 1`` used to be reported
  1229. as ``output-limit`` by the child while the host would have counted the
  1230. one-byte ``1`` it actually receives. Both sides also emit these bytes (the
  1231. child through :func:`_encode_json_plain`, the host through
  1232. ``encodeJsonPlain``), so the fix has to be in the shared speller, not in the
  1233. meter.
  1234. Implements ECMA-262 ``Number::toString`` radix 10 directly: ``repr``
  1235. already yields the shortest round-tripping decimal digits, and ``Decimal``
  1236. splits them into the significand ``s`` (``digits``, ``k`` of them) and
  1237. decimal exponent ``n`` the spec's cases select on. The integral values above
  1238. the JS safe range take the host's BigInt branch, whose exact digits differ
  1239. from the shortest-round-trip form (``2**60`` prints ``...846976``, not
  1240. ``...847000``).
  1241. """
  1242. if value != value or value in (float("inf"), float("-inf")):
  1243. # json.dumps(allow_nan=False) raises the same way; the callers reject
  1244. # non-finite floats before metering, so this is unreachable defense.
  1245. raise ValueError("Out of range float values are not JSON compliant")
  1246. if value == 0.0:
  1247. # Covers -0.0 too; callers reject it as non-lossless before this point.
  1248. return "0"
  1249. if value < 0:
  1250. return "-" + _dump_float(-value)
  1251. if value.is_integer() and value > float(2**53 - 1):
  1252. # The host's BigInt branch: exact digits, not shortest-round-trip.
  1253. return str(int(value))
  1254. parts = Decimal(repr(value)).normalize().as_tuple()
  1255. digits = "".join(str(digit) for digit in parts.digits)
  1256. k = len(digits)
  1257. n = parts.exponent + k
  1258. if k <= n <= 21:
  1259. return digits + "0" * (n - k)
  1260. if 0 < n <= 21:
  1261. return digits[:n] + "." + digits[n:]
  1262. if -6 < n <= 0:
  1263. return "0." + "0" * -n + digits
  1264. exponent = ("+" if n - 1 >= 0 else "-") + str(abs(n - 1))
  1265. return (digits if k == 1 else digits[0] + "." + digits[1:]) + "e" + exponent
  1266. def _check_done_value(value: Any, max_bytes: int):
  1267. """Meter a completion value's JSON byte size AND validate its lossless-JSON
  1268. shape in one bounded post-order walk; return ``None`` when it passes.
  1269. Folds what was formerly a losslessness walk followed by a separate byte
  1270. meter into one pass. Running the losslessness walk first materialized one
  1271. traversal tuple per element before any size cap: ``return [0] * 2000000``
  1272. under ``maxValueBytes: 64`` allocated millions of frames (an RLIMIT_AS
  1273. death) before the meter could reject it. Folding the byte bound into the
  1274. walk rejects over-budget BEFORE enqueuing a container's children — every
  1275. element is at least one JSON byte — so the walk stays O(cap). Same
  1276. JS-double-exact integer boundary, cycle detection (a leave marker pops each
  1277. container off ``on_path``), and type rejections as
  1278. :func:`_lossless_json_violation`, and the same byte accounting as
  1279. :func:`_encode_json_plain`. :func:`_lossless_json_violation` stays for the
  1280. binding-argument path, which carries no size cap.
  1281. EVERY type here is matched EXACTLY, containers and scalars alike, so a
  1282. subclass is rejected as an unsupported type rather than admitted by
  1283. ``isinstance``. A subclass can override the operators and methods this walk
  1284. and the encoder call, and they need not agree: a populated ``dict``
  1285. subclass whose ``items()`` returns ``[]`` would meter as ``{}``; a ``float``
  1286. subclass overriding ``__repr__`` passes the non-finite and negative-zero
  1287. checks by its real value but serializes as whatever the override says, since
  1288. :func:`_dump_float` reads ``repr``; an ``int`` subclass overriding ``__gt__``
  1289. and ``__lt__`` slips past the JS-safe-range bound while ``json.dumps``
  1290. emits its true C-level digits, so ``2**53 + 1`` reaches the host as
  1291. ``...992``; a ``str`` subclass overriding ``__len__`` returns 0 from the
  1292. pre-encode lower bound and admits an arbitrarily large string. In each case
  1293. the value the host receives differs from the one this walk approved. The
  1294. worker backend rejects the equivalent shapes by prototype identity and
  1295. ``typeof`` (``hasPlainObjectPrototype`` in ``worker-json.ts``); a ``bool``
  1296. is checked before ``int`` because it is an ``int`` subclass that IS
  1297. lossless JSON.
  1298. Returns ``("invalid-output", message)`` for a non-lossless value,
  1299. ``("output-limit", message)`` once the size crosses ``max_bytes``, or
  1300. ``None`` when the value is lossless JSON within budget.
  1301. """
  1302. js_safe = 2**53 - 1
  1303. def invalid(reason: str):
  1304. return ("invalid-output", f"program completion must be lossless JSON ({reason})")
  1305. over_budget = ("output-limit", f"completion value exceeded {max_bytes} bytes")
  1306. total = 0
  1307. on_path: set[int] = set()
  1308. # The walk uses O(DEPTH) space, not O(width). A container pushes ONE cursor
  1309. # frame that pulls its children one at a time, rather than one traversal
  1310. # frame per child: a flat `[0] * 6_000_000` serializes to ~12 MB (well within
  1311. # a modest budget) but one tuple per element is ~380 MB — an RLIMIT_AS death
  1312. # on a value the byte meter would admit, the very inversion this meter exists
  1313. # to prevent. A cursor frame is (kind, container, iterator); a visit frame is
  1314. # (VISIT, value, None). The upfront structural bound still rejects a wide
  1315. # forgery before any iteration begins.
  1316. exhausted = object()
  1317. visit, list_cursor, dict_cursor = 0, 1, 2
  1318. stack: list[tuple[int, Any, Any]] = [(visit, value, None)]
  1319. while stack:
  1320. frame = stack.pop()
  1321. kind = frame[0]
  1322. if kind == list_cursor:
  1323. container, iterator = frame[1], frame[2]
  1324. child = next(iterator, exhausted)
  1325. if child is exhausted:
  1326. on_path.discard(id(container))
  1327. continue
  1328. # Resume this cursor after the child is fully walked; the child goes
  1329. # on top so it is visited next (order does not affect the byte total).
  1330. stack.append(frame)
  1331. stack.append((visit, child, None))
  1332. continue
  1333. if kind == dict_cursor:
  1334. container, iterator = frame[1], frame[2]
  1335. entry = next(iterator, exhausted)
  1336. if entry is exhausted:
  1337. on_path.discard(id(container))
  1338. continue
  1339. key, item = entry
  1340. # Only an EXACT str key survives: bool and int coerce or raise, and a
  1341. # str SUBCLASS can override the ``__len__`` the bound below reads while
  1342. # the encoder emits its real characters.
  1343. if type(key) is not str:
  1344. return invalid(f"non-string dict key ({type(key).__name__})")
  1345. # The same string lower bound, before escaping the key.
  1346. if total + len(key) + 3 > max_bytes:
  1347. return over_budget
  1348. # Same counting rule as the string branch: a control-heavy KEY
  1349. # expands just as far, and `_dump_scalar` on a str is `_dump_string`.
  1350. total += _json_str_cost(key) + 1
  1351. if total > max_bytes:
  1352. return over_budget
  1353. stack.append(frame)
  1354. stack.append((visit, item, None))
  1355. continue
  1356. current = frame[1]
  1357. if current is None or type(current) is bool:
  1358. total += len(_dump_scalar(current).encode("utf-8"))
  1359. elif type(current) is str:
  1360. # Lower-bound BEFORE materializing the escaped form: every character
  1361. # is at least one UTF-8 byte plus the two quotes, so a huge or
  1362. # control-heavy string (whose escaped copy expands severalfold) is
  1363. # rejected without allocating that copy.
  1364. if total + len(current) + 2 > max_bytes:
  1365. return over_budget
  1366. # A lone surrogate has no UTF-8 form but a lossless JSON one — the
  1367. # ASCII ``\uXXXX`` escape :func:`_dump_string` emits — so it is
  1368. # metered, not rejected, matching the shared seam. Metered by
  1369. # COUNTING, not by building the escaped form: that copy plus its
  1370. # encode is ~6x the original for a control-heavy string, so measuring
  1371. # a value the budget rejects could breach RLIMIT_AS and surface as
  1372. # `exception` instead of the promised `output-limit`.
  1373. total += _json_str_cost(current)
  1374. elif type(current) is int:
  1375. # The canonical boundary accepts every JS-double-exact value: an int
  1376. # outside +-2**53-1 is fine IFF the double round-trip is exact.
  1377. if current > js_safe or current < -js_safe:
  1378. try:
  1379. exact = int(float(current)) == current
  1380. except OverflowError:
  1381. exact = False
  1382. if not exact:
  1383. return invalid("integer not exactly representable as a JavaScript number")
  1384. total += len(_dump_scalar(current).encode("utf-8"))
  1385. elif type(current) is float:
  1386. if current != current or current in (float("inf"), float("-inf")):
  1387. return invalid("non-finite float")
  1388. # JSON turns -0.0 into a sign the host parses back to JS -0; the
  1389. # canonical boundary rejects it, so this side must too.
  1390. if current == 0.0 and math.copysign(1.0, current) < 0:
  1391. return invalid("negative zero")
  1392. total += len(_dump_scalar(current).encode("utf-8"))
  1393. elif type(current) is list:
  1394. if id(current) in on_path:
  1395. return invalid("circular reference")
  1396. count = len(current)
  1397. total += 2 + (count - 1 if count > 1 else 0)
  1398. # Reject over-budget BEFORE iterating: every element serializes to at
  1399. # least one byte, so a wide flat forgery fails here without pulling a
  1400. # single child.
  1401. if total + count > max_bytes:
  1402. return over_budget
  1403. on_path.add(id(current))
  1404. stack.append((list_cursor, current, iter(current)))
  1405. elif type(current) is dict:
  1406. if id(current) in on_path:
  1407. return invalid("circular reference")
  1408. # ``len`` without materializing ``current.items()``: that list
  1409. # allocates one tuple per member before the bound below could run,
  1410. # recreating the spike the bound exists to stop.
  1411. count = len(current)
  1412. total += 2 + (count - 1 if count > 1 else 0)
  1413. # Same pre-iterate bound: each entry contributes a quoted key
  1414. # (>= 2 bytes), a colon, and a >= 1-byte value. ``iter`` on the items
  1415. # view is O(1); the cursor meters each key as it is pulled.
  1416. if total + count * 4 > max_bytes:
  1417. return over_budget
  1418. on_path.add(id(current))
  1419. stack.append((dict_cursor, current, iter(current.items())))
  1420. else:
  1421. # tuple, set, or any other type: not round-trippable JSON.
  1422. return invalid(f"unsupported type ({type(current).__name__})")
  1423. if total > max_bytes:
  1424. return over_budget
  1425. return None
  1426. def _lossless_json_violation(value: Any) -> str | None:
  1427. """Return why ``value`` is not lossless JSON, or ``None`` when it is.
  1428. ``json.dumps`` succeeding is NOT proof of losslessness: it coerces a
  1429. non-string ``dict`` key to its string form (``{1: "a", "1": "b"}`` collapses
  1430. to one key, silently dropping data), emits non-standard ``NaN``/``Infinity``
  1431. tokens without ``allow_nan=False``, and accepts integers outside JavaScript's
  1432. safe range (``9007199254740993`` becomes ``...992`` once the host parses the
  1433. frame into a JS number). Validate the shape up front so a coercive or lossy
  1434. value fails as ``invalid-output`` instead of round-tripping to something the
  1435. program did not compute. Iterative so deep nesting cannot overflow the stack,
  1436. and it tracks the container ancestry on the current path so a cyclic value is
  1437. reported at once rather than spinning until the CPU budget. Only JSON-plain
  1438. types survive: ``None``/``bool``/JS-safe ``int``/finite ``float``/``str``,
  1439. exact ``list``, and exact ``dict`` with ``str`` keys. Every type matches
  1440. EXACTLY, containers and scalars alike, for the reason
  1441. :func:`_check_done_value` documents: a subclass can override the operators
  1442. and methods a traversal calls, so an ``isinstance`` admission here would
  1443. approve one shape and let the encoder emit another.
  1444. """
  1445. # The canonical boundary accepts every JS-double-exact value: an int
  1446. # outside +-2**53-1 is fine IFF the double round-trip is exact (2**53 or
  1447. # 2**60 survive; 2**53+1 rounds), matching the worker backend.
  1448. js_safe = 2**53 - 1
  1449. # Post-order walk with an explicit "leave" marker: a container's id is added
  1450. # to `on_path` when entered and removed when left, so a back-edge to an
  1451. # ancestor (a cycle) is detected without rejecting a legitimately shared
  1452. # acyclic subtree.
  1453. on_path: set[int] = set()
  1454. # O(DEPTH) auxiliary space, not O(width), for the reason
  1455. # :func:`_check_done_value` documents: this walk runs in ``dispatch`` on
  1456. # MODEL-CONSTRUCTED binding arguments, which no child-side byte budget
  1457. # bounds first (the frame ceiling is the host's, and it applies after this
  1458. # returns). Enqueueing one frame per member would let a legitimate
  1459. # ``[0] * 6_000_000`` argument -- ~17 MB of JSON -- allocate ~366 MB of
  1460. # traversal tuples and die as the program's own MemoryError instead of
  1461. # round-tripping. A container therefore pushes ONE cursor frame holding its
  1462. # iterator; children are pulled one at a time.
  1463. exhausted = object()
  1464. visit, container_cursor = 0, 1
  1465. # A visit frame is (visit, value); a cursor frame is (cursor, container, iterator).
  1466. stack: list[tuple[int, Any, Any]] = [(visit, value, None)]
  1467. while stack:
  1468. kind = stack[-1][0]
  1469. if kind == container_cursor:
  1470. _, container, iterator = stack[-1]
  1471. child = next(iterator, exhausted)
  1472. if child is exhausted:
  1473. # Leaving the container: it is no longer on the current path, so
  1474. # a legitimately shared acyclic subtree is not mistaken for a cycle.
  1475. on_path.discard(id(container))
  1476. stack.pop()
  1477. continue
  1478. if type(container) is dict:
  1479. # The dict cursor yields (key, value): check the key as it is
  1480. # pulled. Only an EXACT str key survives -- int, float, None, and
  1481. # tuple keys coerce or raise, and a str subclass can carry
  1482. # overrides the encoder does not honor.
  1483. key, child = child
  1484. if type(key) is not str:
  1485. return f"non-string dict key ({type(key).__name__})"
  1486. stack.append((visit, child, None))
  1487. continue
  1488. _, current, _unused = stack.pop()
  1489. if current is None or type(current) is bool:
  1490. continue
  1491. if type(current) is str:
  1492. # Every string is lossless JSON. A lone surrogate has no UTF-8 form,
  1493. # but JSON carries the code unit as its ASCII ``\uXXXX`` escape and
  1494. # :func:`_dump_string` emits exactly that, so the host receives the
  1495. # same code unit the program passed — the same acceptance
  1496. # ``CodeJsonValue``, ``snapshotJsonValue``, and the worker backend
  1497. # already give it.
  1498. continue
  1499. if type(current) is int:
  1500. if current > js_safe or current < -js_safe:
  1501. try:
  1502. exact = int(float(current)) == current
  1503. except OverflowError:
  1504. exact = False
  1505. if not exact:
  1506. return "integer not exactly representable as a JavaScript number"
  1507. continue
  1508. if type(current) is float:
  1509. if current != current or current in (float("inf"), float("-inf")):
  1510. return "non-finite float"
  1511. # JSON serialization turns -0.0 into 0 (or "-0.0" text that the
  1512. # host parses to JS -0), silently changing the sign bit either
  1513. # way; the repository's canonical lossless-JSON boundary and the
  1514. # worker backend both reject it, so this side must too.
  1515. if current == 0.0 and math.copysign(1.0, current) < 0:
  1516. return "negative zero"
  1517. continue
  1518. if type(current) is list or type(current) is dict:
  1519. if id(current) in on_path:
  1520. return "circular reference"
  1521. on_path.add(id(current))
  1522. if type(current) is dict:
  1523. # Keys are checked as the cursor pulls each entry, not in a
  1524. # separate pass: ``current.values()`` would need a second walk,
  1525. # and materializing ``items()`` up front allocates one tuple per
  1526. # member -- the very spike the cursor removes.
  1527. stack.append((container_cursor, current, iter(current.items())))
  1528. else:
  1529. stack.append((container_cursor, current, iter(current)))
  1530. continue
  1531. return f"unsupported type ({type(current).__name__})"
  1532. return None
  1533. def _make_cpu_enforcer() -> Any:
  1534. """Build the CPU post-check over closure-held primitives.
  1535. This bootstrap IS ``__main__``, so model code can reach every one of its
  1536. module globals: ``import __main__; __main__._X = ...`` rebinds the name the
  1537. enforcement would otherwise read at call time, which a plain module-level
  1538. function plus module-level captures made a one-line defeat. The primitives
  1539. therefore live in this factory's locals, which become closure cells of the
  1540. returned function, and :func:`_run` binds the returned function into a
  1541. local of its own frame BEFORE executing the program, so no assignment to
  1542. ``__main__`` changes which callable runs or what it calls. Capture happens
  1543. at import time, before model code runs, so the captured
  1544. ``resource.getrusage``/``signal.signal``/``os.kill`` are the real builtins.
  1545. This raises the cost of defeating the check; it does not make it
  1546. unreachable, and nothing in-process could. A cell is writable through
  1547. ``fn.__closure__[i].cell_contents``, and ``sys._getframe`` walks to
  1548. :func:`_run`'s frame and reads its locals, so a program determined to
  1549. tamper still can — consistent with this backend's documented posture, where
  1550. the in-process interpreter is containment rather than a security boundary
  1551. (§Trust posture in the Code Mode RFC). The bounds that model code cannot
  1552. forge are outside the interpreter: the RLIMIT_CPU HARD limit at
  1553. ``cpuSeconds + 1``, whose SIGKILL is undeliverable to a handler and
  1554. unraisable by a process that cannot raise its own hard limit, and the
  1555. host's wall-clock ceiling. This check exists to convert the two cases those
  1556. miss — a program that traps SIGXCPU and settles inside the soft-to-hard
  1557. gap, and a program that spends the budget in DESCENDANTS the kernel never
  1558. charged to this process — from a reported SUCCESS into the same `timeout`
  1559. an untrapped program gets.
  1560. @returns The one-argument enforcement callable, taking `cpuSeconds`.
  1561. """
  1562. getrusage = resource.getrusage
  1563. rusage_self = resource.RUSAGE_SELF
  1564. rusage_children = resource.RUSAGE_CHILDREN
  1565. set_signal = signal.signal
  1566. sig_dfl = signal.SIG_DFL
  1567. sigxcpu = signal.SIGXCPU
  1568. kill = os.kill
  1569. getpid = os.getpid
  1570. def die_if_cpu_exhausted(cpu_seconds: int) -> None:
  1571. """Die by re-delivered SIGXCPU when the CPU budget is already spent.
  1572. Two cases reach here as a would-be SUCCESS. A model program can trap
  1573. SIGXCPU and return during the one-second soft-to-hard gap. And
  1574. ``RLIMIT_CPU`` is PER-PROCESS, inherited fresh by every child, so a
  1575. program calling ``subprocess`` or ``os.fork`` multiplies the run's CPU
  1576. budget by the number of descendants it starts: measured with
  1577. ``cpuSeconds: 1``, two sequential busy children burned 2.0
  1578. CPU-seconds and the parent, which had accrued almost no CPU of its own
  1579. while blocked in ``subprocess.wait``, still returned a completion.
  1580. The meter is therefore ``RUSAGE_SELF + RUSAGE_CHILDREN``, the kernel's
  1581. own aggregate, which accumulates the CPU of every REAPED descendant
  1582. (grandchildren included, verified).
  1583. ``getrusage`` is the kernel's own meter (unforgeable from model code),
  1584. and dying by SIGXCPU with the default disposition restored gives the
  1585. host the same kernel-authoritative close signal as the untrapped soft
  1586. limit — classified as `timeout`, after which the host's process-group
  1587. SIGTERM/SIGKILL teardown reaches any surviving descendants. Runs AFTER
  1588. the model program settled, so a program can re-trap SIGXCPU between
  1589. this SIG_DFL and the kill only by running more code, which it no longer
  1590. does. A program that tampers with this callable instead (see
  1591. :func:`_make_cpu_enforcer` on why in-process state cannot be hidden)
  1592. buys at most the remaining soft-to-hard gap: one more CPU second, after
  1593. which the hard limit's SIGKILL lands with no handler possible.
  1594. Checking at settle time rather than sampling mid-run is deliberate:
  1595. both mid-run designs perturb the run they measure. A sampling thread
  1596. cost 72 MiB of virtual address space in the child (8 MiB stack plus a
  1597. 64 MiB glibc per-thread malloc arena reservation; measured 30.23 MiB of
  1598. mappings without it against 102.37 MiB with it), and ``RLIMIT_AS``
  1599. counts reserved space, so it silently shrank every run's
  1600. `addressSpaceMb`. A ``SIGALRM`` interval timer costs no mappings but
  1601. makes the program's own syscalls return short under PEP 475 — measured
  1602. a 64 MiB ``os.write`` returning 65536 — which corrupts fd-3 framing.
  1603. The cost of checking only at settle time is that a descendant's CPU is
  1604. detected after it is spent, not while it runs; the host's wall-clock
  1605. ceiling bounds that interval, and a program that never reaps its child
  1606. is bounded by the wall clock alone, since ``RUSAGE_CHILDREN`` counts
  1607. only reaped descendants (verified: a still-running child contributes
  1608. 0.0).
  1609. @param cpu_seconds The `cpuSeconds` budget the soft RLIMIT_CPU used.
  1610. """
  1611. own = getrusage(rusage_self)
  1612. kids = getrusage(rusage_children)
  1613. spent = own.ru_utime + own.ru_stime + kids.ru_utime + kids.ru_stime
  1614. if spent >= cpu_seconds:
  1615. set_signal(sigxcpu, sig_dfl)
  1616. kill(getpid(), sigxcpu)
  1617. return die_if_cpu_exhausted
  1618. _DIE_IF_CPU_EXHAUSTED = _make_cpu_enforcer()
  1619. _TRUNCATION_MARKER = "… [truncated]"
  1620. # The marker's own UTF-8 size, reserved out of the cap rather than added on top
  1621. # of it. Byte-identical to the host's TRUNCATION_MARKER_BYTES; the ellipsis is
  1622. # three bytes, so this is 15, not the string's 13 characters.
  1623. _TRUNCATION_MARKER_BYTES = len(_TRUNCATION_MARKER.encode("utf-8"))
  1624. def _cap_message(message: str, max_bytes: int) -> str:
  1625. """Cap a diagnostic by its SERIALIZED cost, appending the host's marker.
  1626. Metered by the JSON-string cost the ``done`` frame will actually carry, not
  1627. by raw UTF-8 length: the message crosses fd 3 inside a JSON frame where
  1628. control characters escape up to sixfold (a NUL is one raw byte but six as
  1629. ``\\u0000``), so a raw-length cap of ``maxValueBytes`` could serialize to
  1630. roughly six times that and breach the 256 MiB frame ceiling — the silent
  1631. ``worker-exit`` inversion the load-time cap check exists to prevent, and a
  1632. several-hundred-MiB escape allocation besides. The seam's load bound admits
  1633. ``maxValueBytes`` up to ``ceiling - envelope`` on the premise that both the
  1634. completion value and the diagnostic are metered in serialized bytes, so this
  1635. honors that premise for the diagnostic.
  1636. Encoded with ``errors="replace"`` first: a model exception message can
  1637. contain an unpaired surrogate (``raise Exception("\\ud800")``), and a strict
  1638. encode would throw while BUILDING the failure frame — the run would then
  1639. strand until the wall clock instead of reporting the exception. The marker's
  1640. serialized cost comes OUT of ``max_bytes``, so the returned string's own
  1641. frame form honors the cap; the host meters the same field again on arrival.
  1642. A ``max_bytes`` below the marker's cost yields the marker alone.
  1643. This is the PRODUCING-side cap. The host's receive-side ``capMessage``
  1644. (``src/index.ts``) bills the same field by RAW bytes instead, because its
  1645. output goes into ``CodeRunResult.error.message`` and never re-crosses a
  1646. frame-bounded channel — see that function's JSDoc for the split.
  1647. """
  1648. raw = message.encode("utf-8", errors="replace")
  1649. if _json_string_cost(raw) <= max_bytes:
  1650. return raw.decode("utf-8")
  1651. # Truncating: the result is `prefix + marker`, whose serialized cost is
  1652. # `2 (quotes) + sum(prefix byte costs) + marker cost`. The marker is
  1653. # escape-free, so its cost is its UTF-8 length. Reserve that and the quotes,
  1654. # then take the longest raw prefix whose accumulated per-byte cost fits.
  1655. # `_JSON_BYTE_COST` is per-byte and additive, so the scan is exact and walks
  1656. # at most a budget's worth of bytes, allocating nothing (unlike building the
  1657. # escaped form). `max(0, ...)` handles a `max_bytes` below the marker's own
  1658. # cost, yielding the marker alone.
  1659. content_budget = max(0, max_bytes - 2 - _TRUNCATION_MARKER_BYTES)
  1660. cost = 0
  1661. end = 0
  1662. for end in range(len(raw)):
  1663. cost += _JSON_BYTE_COST[raw[end]]
  1664. if cost > content_budget:
  1665. break
  1666. else:
  1667. end = len(raw)
  1668. # Drop a trailing partial UTF-8 sequence the slice may have cut (continuation
  1669. # bytes are 0b10xxxxxx); `errors="ignore"` renders the clean prefix.
  1670. return raw[:end].decode("utf-8", errors="ignore") + _TRUNCATION_MARKER
  1671. # Fixed safety/liveness bound, not a tunable: a model can raise an exception
  1672. # with an arbitrarily deep __cause__/__context__ chain, and both the rendering
  1673. # walk and format() are linear in chain length. Capping how many links get
  1674. # RENDERED keeps traceback formatting from consuming the whole wall budget.
  1675. # 100 links is far beyond any legible human traceback.
  1676. _MAX_TRACEBACK_CHAIN = 100
  1677. # Diagnostic used when rendering the failure itself fails. Built from a fixed
  1678. # literal plus the exception CLASS name, never from the exception's own str.
  1679. _UNRENDERABLE_DIAGNOSTIC = "<diagnostic rendering failed>"
  1680. def _model_traceback(exc: BaseException, max_bytes: int) -> str:
  1681. """Format a model-program failure with only the MODEL's own frames.
  1682. Bootstrap frames carry host-absolute paths — meaningless to the model and
  1683. unstable across machines, so transcripts pinning them cannot replay. They
  1684. appear not only as a leading prefix (the bootstrap's ``exec``/``await``)
  1685. but also interleaved and trailing: an uncaught binding rejection re-raised
  1686. by ``dispatch`` puts bootstrap frames AFTER the model's, and chained
  1687. ``__cause__``/``__context__`` exceptions carry their own stacks. Filter
  1688. every non-``<model>`` frame across the whole chain rather than trimming a
  1689. prefix. A failure with no model frame anywhere (e.g. a SyntaxError raised
  1690. by ``compile``) keeps the standard exception-only rendering.
  1691. Rendering is bounded to ``_MAX_TRACEBACK_CHAIN`` links, cut on the
  1692. ``TracebackException`` COPY, and a marker line announces the truncation.
  1693. Nothing here touches the live exception: an exception class overriding
  1694. ``__setattr__`` would run MODEL code from inside the caller's failure
  1695. handler, and a throw there costs the ``done`` frame (see
  1696. ``_safe_model_traceback``). ``TracebackException`` instances hold no such
  1697. hooks, so clearing their links runs no model code. The walk is iterative,
  1698. so a deep chain cannot overflow the recursion limit.
  1699. ``from_exception`` still copies the WHOLE live chain, at a higher per-link
  1700. cost than building it took. That is bounded by the child's ``RLIMIT_AS``:
  1701. the model must materialize every link (exception object plus traceback)
  1702. before raising, so a chain long enough for the copy to matter is already
  1703. near the address-space cap, and a ``MemoryError`` in the copy lands in the
  1704. caller's fallback rather than stranding the run.
  1705. """
  1706. te = traceback.TracebackException.from_exception(exc)
  1707. # One iterative pass over the copy does both jobs: keep only <model> frames
  1708. # on every linked exception and group member, and cut the chain at the cap.
  1709. found = False
  1710. truncated = False
  1711. pending = [(te, 1)]
  1712. while pending:
  1713. entry, depth = pending.pop()
  1714. kept = [f for f in entry.stack if f.filename == "<model>"]
  1715. entry.stack = traceback.StackSummary.from_list(kept)
  1716. found = found or bool(kept)
  1717. # 3.11+ exception groups (a binding failure inside asyncio.TaskGroup)
  1718. # carry member stacks under `exceptions`, not the dunder links; a group
  1719. # member counts as a link so the cap bounds nesting through both edges.
  1720. members = getattr(entry, "exceptions", None) or ()
  1721. if depth >= _MAX_TRACEBACK_CHAIN:
  1722. if entry.__cause__ is not None or entry.__context__ is not None or members:
  1723. truncated = True
  1724. entry.__cause__ = None
  1725. entry.__context__ = None
  1726. if members:
  1727. entry.exceptions = None
  1728. continue
  1729. for linked in (entry.__cause__, entry.__context__):
  1730. if linked is not None:
  1731. pending.append((linked, depth + 1))
  1732. for member in members:
  1733. pending.append((member, depth + 1))
  1734. def emit():
  1735. if found:
  1736. yield from te.format()
  1737. else:
  1738. yield from traceback.format_exception_only(type(exc), exc)
  1739. if truncated:
  1740. yield f"[dsh-code-runtime-python] exception chain truncated at {_MAX_TRACEBACK_CHAIN} links\n"
  1741. return _join_bounded(emit(), max_bytes)
  1742. def _make_failure_reporter() -> Any:
  1743. """Build the failure-diagnostic renderer over closure-held primitives.
  1744. The returned callable renders a model failure diagnostic that cannot itself
  1745. raise. The caller sends the ``done`` frame AFTER its ``except BaseException``
  1746. block, so anything thrown while rendering the diagnostic skips the send
  1747. entirely: the host then blocks on fd 3 until ``maxWallMs`` and reports a
  1748. timeout instead of the exception that actually happened. Rendering runs
  1749. model code by design (``format()`` reaches ``__str__``, ``__repr__`` and
  1750. ``__notes__``) and allocates under ``RLIMIT_AS``, so it must be treated as
  1751. able to throw.
  1752. The fallback names the exception CLASS and a fixed literal — no ``str(exc)``
  1753. and no ``format_exception_only``, both of which reach the model's
  1754. ``__str__``. A ``__name__`` that is not exactly ``str`` (a metaclass
  1755. property can return anything, or raise) is discarded rather than
  1756. formatted, so no override runs on this path either.
  1757. The factory exists for the same reason :func:`_make_cpu_enforcer` does: this
  1758. bootstrap IS ``__main__``, so ``import __main__; __main__._X = ...`` rebinds
  1759. any module global a call-time lookup would read. On this path a rebind is
  1760. worst — the handler's own reporter, and everything the reporter reaches,
  1761. would run model code outside any guard, and a throw there costs the ``done``
  1762. frame. The traceback formatter, the byte cap and the fallback literal
  1763. therefore become closure cells captured at import time, before model code
  1764. runs, and :func:`_run` binds the returned callable into a local of its own
  1765. frame. A frame local is not a module attribute, so no assignment to
  1766. ``__main__`` changes which callable runs or what it calls. This defeats the
  1767. one-line rebind, not a determined ``sys._getframe`` walk; the unforgeable
  1768. bound is the host wall clock.
  1769. """
  1770. cap_message = _cap_message
  1771. model_traceback = _model_traceback
  1772. unrenderable = _UNRENDERABLE_DIAGNOSTIC
  1773. def safe_model_traceback(exc: BaseException, max_bytes: int) -> str:
  1774. try:
  1775. return cap_message(model_traceback(exc, max_bytes), max_bytes)
  1776. except BaseException: # noqa: BLE001 -- a throw here would cost the done frame
  1777. pass
  1778. try:
  1779. raw_name = type(exc).__name__
  1780. # Slice BEFORE interpolating. A metaclass `__name__` property can
  1781. # return an arbitrarily long string, and both the f-string and
  1782. # `cap_message`'s encode would copy it whole — under a tight
  1783. # RLIMIT_AS either allocation can raise MemoryError, and this is the
  1784. # LAST fallback, so a throw here costs the `done` frame outright and
  1785. # the run misreports as an exit or a timeout. The slice is a
  1786. # code-unit prefix, which bounds the bytes at 4x, and the following
  1787. # `cap_message` still applies the exact byte cap.
  1788. name = raw_name[:_MAX_FALLBACK_NAME_CHARS] if type(raw_name) is str else "<unknown>"
  1789. except BaseException: # noqa: BLE001 -- a raising __name__ must not cost the done frame
  1790. name = "<unknown>"
  1791. # Wrapped for the same reason: `cap_message` encodes, and its allocation
  1792. # is the only step left that can still fail. The fixed literal needs no
  1793. # budget, so it can always be delivered.
  1794. try:
  1795. return cap_message(f"{name}: {unrenderable}", max_bytes)
  1796. except BaseException: # noqa: BLE001 -- the done frame outranks the diagnostic's detail
  1797. return unrenderable
  1798. return safe_model_traceback
  1799. _SAFE_MODEL_TRACEBACK = _make_failure_reporter()
  1800. def _join_bounded(lines, max_bytes: int) -> str:
  1801. """Join formatter output, stopping once the budget is comfortably passed.
  1802. ``format()`` yields lines lazily; consuming it whole for an exception
  1803. carrying a huge message would materialize the full text only for
  1804. ``_cap_message`` to throw it away — enough over-shoot to exhaust
  1805. ``RLIMIT_AS``. Stop after the accumulated CHARACTER count passes the byte
  1806. budget (chars lower-bound UTF-8 bytes); the caller's ``_cap_message``
  1807. does the exact byte-level cut.
  1808. """
  1809. chunks: list[str] = []
  1810. total = 0
  1811. for line in lines:
  1812. # A single yielded line can itself dwarf the budget (the exception
  1813. # message rides in one line): keep only the prefix it can ever need.
  1814. if len(line) > max_bytes + 1:
  1815. line = line[: max_bytes + 1]
  1816. chunks.append(line)
  1817. total += len(line)
  1818. if total > max_bytes:
  1819. break
  1820. return "".join(chunks)
  1821. def _done_with_value(value: Any, max_value_bytes: int) -> dict[str, Any]:
  1822. """Build the terminal done frame under the seam's lossless-JSON contract.
  1823. A completion value returned by the program (``None`` when it returns
  1824. nothing) that is not lossless JSON fails the run as ``invalid-output``; a
  1825. serialized value beyond ``max_value_bytes`` fails as ``output-limit``.
  1826. Substituting a ``repr`` or truncated string would be a silent lie about
  1827. what the program computed, so both paths refuse instead (mirroring the
  1828. worker backend's contract). ``None`` crosses as an exact JSON ``null``.
  1829. """
  1830. # One bounded walk folds the losslessness check and the byte meter (mirrors
  1831. # the host's checkDoneValue): the former split ran the full losslessness
  1832. # walk first, materializing one tuple per element for a wide completion
  1833. # before the size cap could reject it — an RLIMIT_AS death on a value the
  1834. # meter would have refused. send_sync later encodes the admitted value,
  1835. # whose size the walk proved within budget. Iterative like the encoder, so a
  1836. # valid completion deeper than the recursion limit still checks.
  1837. rejection = _check_done_value(value, max_value_bytes)
  1838. if rejection is not None:
  1839. kind, message = rejection
  1840. return {"type": "done", "error": {"kind": kind, "message": message}}
  1841. return {"type": "done", "value": value}
  1842. def main() -> None:
  1843. channel = ProtocolChannel(PROTOCOL_FD)
  1844. asyncio.run(_run(channel))
  1845. if __name__ == "__main__":
  1846. main()