bootstrap.py 93 KB

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