bootstrap.py 113 KB

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