1
0

bootstrap.py 91 KB

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