bootstrap.py 130 KB

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