1
0

bootstrap.py 118 KB

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