Skip to content

fix(codemode): give errors a stack - #64939

Merged
rekram1-node merged 4 commits into
devfrom
error-stack
Nov 19, 2026
Merged

rekram1-node merged 4 commits into
devfrom
error-stack

Conversation

@rekram1-node

@rekram1-node rekram1-node commented Nov 19, 2026 •

Copy link
Copy Markdown
Member

Summary

Errors in Code Mode had no stack (a documented gap), so common error handling like e.stack.split("\n") threw a TypeError inside the catch, and console.log(e.stack) printed undefined. Now every Error has an own, non-enumerable stack string in V8's format.

function inner() { return new Error("boom") }
const outer = () => inner()
outer().stack
try { null.x } catch (e) { e.stack }
try { await tools.host.call({}) } catch (e) { e.stack }
Node 24.22 Bun 1.4.4 Before After
new Error Error: boom\n at inner (/path/s.js:1:27)\n at outer (/path/s.js:2:21)\n at … Error: boom\n at /path/s.js:3:1 undefined Error: boom\n at inner (<program>:1:27)\n at outer (<program>:2:21)\n at <program>:3:1
null.x TypeError: Cannot read properties of null (reading 'x')\n at … TypeError: null is not an object …\n at … undefined TypeError: Cannot read properties of null (reading 'x').\n at <program>:4:7
tool failure — — undefined Error: <tool message>\n at <program>:5:7
subclass sets this.name in its constructor MyErr: x MyErr: x — MyErr: x
e.name = "Late" before the first read Late: y Late: y — Late: y
e.name changed after the first read unchanged unchanged — unchanged
Object.keys(e) / JSON.stringify(e) unchanged unchanged unchanged
stack descriptor accessor { get, set } data { writable, configurable } data { writable, configurable }, non-enumerable
program getter on name runs it not run (Error: …) not run (Error: …)
  • new Error(...) (and every error constructor, called with or without new) records up to 10 program frames, innermost first. Built-in frames are skipped, and top-level code shows as a bare at <program>:line:col. This only walks the VM's frame array and does a binary search per frame. It runs when an error is constructed, not on every throw.
  • As in V8, only the frames are taken at construction. The name: message header is formatted the first time stack is read, using the error's name and message at that moment (the Error.prototype.toString rules: name defaults to Error, and an empty side is dropped). After that the value is fixed, and assigning e.stack = … replaces it. So a subclass that sets this.name in its constructor gets its own name in the header, which matches Node and Bun. The header reads name and message the same way display does, without running a program getter (one reads as undefined). Bun does the same; Node runs the getter.
  • Built-in failures are still turned into Error objects only when a handler catches them. Their stack has one line at the expression that raised them. Host and tool failures have no site of their own, so theirs points at the await or try frame that caught them.
  • stack is an own data slot that formats itself on first read (StackSlot). A snapshot keeps a stack nobody has read yet unformatted, so a name set after resuming still shows up in it. A stack that has already been read is saved as a plain string. structuredClone reads it. Locations are 1-based line and column in the submitted source, with <program> as the file name, so no host or internal path appears. A host Error's own stack still never crosses: a converted error gets only its header line.
  • I updated interpreter-support.md: the "Errors have no stack" note is gone, the new behavior is checked off with the Node/Bun differences above, and Error.captureStackTrace, Error.stackTraceLimit and at async frames are listed as open gaps.

Testing

  • bun test test/errors.test.ts test/codemode.test.ts test/extensions.test.ts test/snapshot.test.ts. New tests cover: frame names and order, the single-frame stack for built-in failures, the 10-frame limit, non-enumerability with JSON.stringify and Object.keys unchanged, a caught tool failure, a subclass name in the header, name/message changed before the first read, the value staying fixed after it, assignment before and after the first read, and snapshot round trips both before and after the first read. I checked that the unread-stack round trip fails if the codec formats the stack early.
  • Full packages/codemode suite: 1870/1870 passed.
  • bun typecheck in packages/codemode, and bun run check at the repo root.

Visual

<svg xmlns="http://www.w3.org/2000/svg" width="240" height="72" viewBox="0 0 240 72" fill="none" font-family="ui-monospace,monospace" font-size="10">
  <style>
    .l{fill:currentColor;opacity:0}
    .a{animation:in 4s infinite}
    .b{animation-delay:.5s}.c{animation-delay:1s}.d{animation-delay:1.5s}
    @keyframes in{0%,8%{opacity:0;transform:translateX(-6px)}18%,85%{opacity:1;transform:none}100%{opacity:0}}
    @media (prefers-reduced-motion:reduce){.a{animation:none;opacity:1}}
  </style>
  <rect x="1" y="1" width="238" height="70" rx="6" stroke="currentColor" opacity=".25"/>
  <text x="10" y="17" class="l a" style="opacity:1;animation:none">Error: boom</text>
  <text x="10" y="32" class="l a b">  at inner (&lt;program&gt;:1:27)</text>
  <text x="10" y="47" class="l a c">  at outer (&lt;program&gt;:2:21)</text>
  <text x="10" y="62" class="l a d" opacity=".6">  at &lt;program&gt;:3:1</text>
</svg>

@opencodejr opencodejr Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The change looks sound. I ran the same probe programs on the base and on this branch. On the base, e.stack is undefined, so e.stack.split("\n") throws inside the catch. With this change:

  • Errors made with new Error get named program frames, innermost first.
  • Callbacks show as <anonymous>.
  • Built-in failures and caught tool failures get a single at <program>:line:col line.
  • Assigning e.stack keeps the new value, and it survives structuredClone.
  • What the host sees for uncaught or returned errors is unchanged.

The targeted test files pass, including in round-trip mode, and tsc --noEmit is clean.

Public API: unchanged. stack exists only inside the sandboxed program; no SDK, server, plugin, config or CLI surface changes.

@opencodejr opencodejr Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The new commit looks sound. It cuts frame names at 200 characters and caps the whole stack at the program's longest string, so a long function name can no longer push the stack past the normal string limit. My earlier review had no open points. The targeted test files pass (172/172, including the new ones), tsc --noEmit is clean, and ordinary stack output is unchanged in my probes. Public API: unchanged.

@rekram1-node

Copy link
Copy Markdown
Member Author

Removed the size caps from this PR at the maintainer's request.

@opencodejr opencodejr Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This revert takes away the cap on stack length that the previous commit added. Without it, a program can build an error stack far past the sandbox's string limit and use a lot of host memory doing it. Details are in the inline comment.

The targeted test files pass (169/169) and tsc --noEmit is clean. Public API: unchanged.

export const createErrorValue = (prototype: Obj, message: string | undefined, trace = ""): ErrorObj => {
const value = new ErrorObj(prototype)
if (message !== undefined) define(value, "message", message, hidden)
define(value, "stack", value.toString() + trace, hidden)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Without the cap from the reverted commit, stack can grow past the sandbox's string limit. With a function name of 2²⁴ characters (const o = { ["m".repeat(2 ** 24)](n) { … } }) recursing 12 deep, new Error().stack.length is 167,772,418, about 10× MAX_STRING_LENGTH. Every other string operation rejects that length (s + s throws RangeError: Invalid string length). Keeping 10 such stacks (forcing each with an indexOf call) took the host process to about 1.8 GB of memory in about 1 s. Could the cap on frame names or on the whole stack come back, or is there a reason the revert is safe?

@rekram1-node

Copy link
Copy Markdown
Member Author

Pushed: the stack header is now formatted on first read, as in V8, so a subclass's this.name and a late name/message show up, and a snapshot keeps an unread stack unformatted.

@opencodejr opencodejr Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The new commit, which fills in the stack's first line (name: message) on first read, works as described. A subclass that sets this.name in its constructor gets its own name in the stack. A name changed before the first read shows up, and the stack stays the same after that. Assigning stack, defineProperty, Object.freeze, structuredClone and snapshot round trips (unread and already read) all behave correctly. The targeted test files pass, including in round-trip mode, and tsc --noEmit is clean.

Public API: unchanged. The snapshot codec's new flag for unread stacks is internal.

The earlier point about capping the length of stack is not addressed yet; that thread stays open.

@rekram1-node rekram1-node changed the title fix(codemode): give errors a V8-style stack fix(codemode): give errors a stack Nov 19, 2026
@rekram1-node
rekram1-node merged commit 1626bbc into dev Nov 19, 2026
18 of 19 checks passed
@rekram1-node
rekram1-node deleted the error-stack branch November 19, 2026 23:07
jlongster added a commit to anomalyco/psychoscript that referenced this pull request Nov 20, 2026
Ported from anomalyco/opencode#64939

User decisions:
- psychoscript holds only the language, nothing tool-specific
@amrkmn amrkmn mentioned this pull request Nov 23, 2026
1 task
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant