bootstrap.py 125 KB

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