Skip to content

fix(tsx): count sandbox memory where built-ins allocate by size - #802

Merged
houko merged 2 commits into
mainfrom
feat/tsx-memory-limit
Nov 19, 2026
Merged

houko merged 2 commits into
mainfrom
feat/tsx-memory-limit

Conversation

@houko

@houko houko commented Nov 19, 2026 •

Copy link
Copy Markdown
Collaborator

Part of #760.

Reworked after review: instead of sampling the process heap every millisecond during a call, the sandbox now counts bytes where goja allocates by a size the bundle gives it, without changing goja and without new dependencies.

What is bounded

tsx.Limits.Memory (bytes, memory= in -limits) stays off by default. When set, Sandbox.start replaces these built-ins before hardening (tsx/memory_goja.go):

  • ArrayBuffer and the eleven typed array constructors (number, array-like, iterable and typed-array sources; a view of a buffer allocates nothing), ArrayBuffer.prototype.slice, transfer, transferToFixedLength, and %TypedArray%.prototype slice, map, filter, toReversed, toSorted, with, join, toLocaleString
  • String.prototype.repeat, padStart, padEnd, String.raw
  • Array.from, Array.prototype.join, toLocaleString, fill, sort, toSorted, toReversed, toSpliced, with
  • the argument lists of Function.prototype.apply, Reflect.apply, Reflect.construct (goja preallocates them from an array-like's length)
  • JSON.stringify, which checks the strings and keys it writes as it reaches them through a replacer of its own around the bundle's

Each wrapper converts size arguments once (so a valueOf cannot report one size to the check and another to the original), checks the remaining budget before calling the original, so what would not fit is never allocated, then charges what the original made. The charge is tied to the allocation's own memory by a weak pointer and released by a runtime.AddCleanup once the collector frees it, so the budget is what the bundle holds across calls, not what one call adds. join and toLocaleString stringify each element first and then let the original join the strings, so the total is checked before the result is built. Past the budget the runtime stops with ERR_NSH_QUOTA_EXCEEDED (resource memory), as past the node quota: JS cannot catch it and the host keeps running. Constructors are wrapped in a tiny JS shim, since goja's Go constructors cannot tell new from a call; the shim takes the original's statics, prototype and prototype chain so instanceof, subclasses, species and Uint8Array.from keep working.

Host allocations and other sandboxes' allocations are never counted, and the 1 ms polling and the timer locking it needed are gone.

What is not bounded

What the bundle's JS makes as it runs: objects, closures, arrays filled element by element or spread, strings concatenated with + or template literals (goja keeps them as ropes, and reading one flattens it at once), keys listed with Object.keys/for…in, what replace/split make, and the web APIs' copies (Blob, TextEncoder). Nothing on the web target, whose page's engine keeps its own heap. Allocations under 1 KiB are not charged. The architecture doc keeps the line that a package's root is still trusted not to exhaust memory, now "past" what is bounded, and the roadmap row says what is left.

Tests

  • TestSandboxMemoryStopsOneLargeAllocation, TestSandboxMemoryCountsWhatCallsKeep, TestSandboxMemoryIgnoresTheHostsAllocations: the three cases from the review, end to end through tsx.Sandboxed, the first including the issue's new ArrayBuffer(2 ** 32). All three fail on the previous head (177faa9) and pass now.
  • TestMemoryStopsWhatWouldNotFit: one case or more per wrapped built-in, each allocating past a 1 MiB budget at once (up to exabytes), inside try/catch; each must stop with the quota and hold at most the budget.
  • TestMemoryKeepsTheBuiltinsBehavior: scripts run with and without the wrappers must agree (constructor identity, subclasses, species, errors for bad sizes and missing new, cycles in join, replacers, frozen built-ins, names and lengths).
  • TestMemoryKeepsWhatFits, TestMemoryReleasesWhatIsCollected: kept allocations stay charged; 40 calls allocating 12 MiB each under a 32 MiB budget never stop once collected.

Checks: go test ./tsx/... ./internal/moduletest/ (also -race on the sandbox and memory tests), go tool nsgo check -target linux,web,android,windows.

Screenshots

None.

@github-actions github-actions Bot added conflict Conflicts with the base branch; resolve it first bug Something isn't working size/M documentation Improvements or additions to documentation tsx cli labels Nov 19, 2026
@houko

houko commented Nov 19, 2026

Copy link
Copy Markdown
Collaborator Author

Not merging yet: the approach needs a design decision before it can meet #760's acceptance ("a bundle that allocates past Limits.Memory stops with a quota error and the host process keeps running").

The watcher in runtime.within (tsx/sandbox.go) samples the process-wide runtime.MemStats.HeapAlloc every millisecond and compares it with the value at the start of the outermost call. I ran three small tests against this head on Linux (go test ./tsx -run Repro, test file below):

  • A single allocation is not bounded. onPress={() => kept.push(new ArrayBuffer(512 * 1024 * 1024))} with Memory: 1 << 20 allocates 512 MiB and the call returns normally with no quota error: goja's ArrayBuffer constructor (builtin_typedarrays.go:91, allocByteSlice) and String.prototype.repeat allocate in one step, before the next sample, and the watcher stops when the call ends. new ArrayBuffer(2 ** 32) is the exhaustion pattern the issue names, and it still takes the process down.
  • Retained memory across calls is not bounded. kept.push(new Array(200_000).fill(1)) pressed 60 times with Memory: 32 << 20 keeps 203 MiB with no quota error, since each call's base is the heap at its start. Timers and events let a plugin grow without limit; the roadmap row this PR marks as done says "keeps or allocates past Limits.Memory".
  • Innocent plugins are stopped. A plugin that only spins for 300 ms while the host allocates 100 MiB on another goroutine is stopped with the sandbox's quota of 67108864 memory is used up. The same happens to every sandbox calling while another sandbox allocates, and, because HeapAlloc counts garbage not yet collected, to any call in an app whose live heap is above about 256 MiB (the heap grows to GOGC% over live before a collection) even if the plugin keeps nothing. With DefaultLimits.Memory on, this turns into random ERR_NSH_QUOTA_EXCEEDED failures in large apps.

Smaller points: runtime.ReadMemStats stops the world, so every sandboxed call now stops the world once per millisecond (runtime/metrics reads /memory/classes/heap/objects:bytes without that); a stop the watcher raises after the call returned sets stopped but nothing panics into the core.Catch until the next call; the test only covers the incremental Array.fill case, which is the one the sampling can catch; and the architecture doc drops "a store of untrusted modules needs a heap limit ... until then a package's root is trusted not to exhaust memory" although that still holds.

A heap sample of the shared Go heap cannot attribute memory to one sandbox, so I think the bound needs to be counted rather than sampled: charge the sandbox's own budget at the places goja allocates by size (ArrayBuffer/typed array constructors, Array length growth, String repeat/padStart/padEnd/concatenation, Array.prototype.join, JSON.stringify, the bridge's strings and bodies) before allocating, cumulatively across calls and released as the runtime is disposed, and document what it does not count, as the issue's proposal allows. That likely means a hook in goja or wrapping those built-ins, which is a choice for you. Until then I would leave Memory off by default rather than ship a default that stops plugins for allocations they did not make.

Repro test (tsx/zz_repro_test.go)
package tsx_test

import (
	"runtime"
	"testing"
	"testing/fstest"

	"github.com/nsgo-dev/nsgo/core"
	"github.com/nsgo-dev/nsgo/nsgotest"
	"github.com/nsgo-dev/nsgo/tsx"
	"github.com/nsgo-dev/nsgo/tsx/bundler"
)

func reproApp(t *testing.T, body string, limit int, host func()) (*nsgotest.App, *error) {
	code, err := bundler.Compile(fstest.MapFS{"App.tsx": {Data: []byte(`import { mount, Text } from "nsgo";
const kept = [];
mount(() => <Text testID="go" onPress={() => { ` + body + ` }}>ok</Text>);`)}}, "App.tsx")
	if err != nil {
		t.Fatal(err)
	}
	limits := tsx.DefaultLimits
	limits.Memory = limit
	var failed error
	app := nsgotest.Start(t, func(cx *core.Scope) core.Node {
		return core.Catch{Try: tsx.Sandboxed("App.tsx", code, tsx.Sandbox{Limits: &limits}), Fallback: func(cx *core.Scope, err error, _ func()) core.Node {
			failed = err
			return core.Text{Content: "cut"}
		}}
	})
	return app, &failed
}

// Retained memory across calls is never bounded: each call's base is reset.
func TestReproRetainedAcrossCalls(t *testing.T) {
	app, failed := reproApp(t, `kept.push(new Array(200_000).fill(1));`, 32<<20, nil)
	var before runtime.MemStats
	runtime.GC()
	runtime.ReadMemStats(&before)
	for range 60 {
		app.Press("id:go")
	}
	var after runtime.MemStats
	runtime.GC()
	runtime.ReadMemStats(&after)
	t.Logf("retained growth %d MiB with a 32 MiB limit, failed=%v", (after.HeapAlloc-before.HeapAlloc)>>20, *failed)
}

// One allocation completes before the watcher can sample.
func TestReproSingleAllocation(t *testing.T) {
	app, failed := reproApp(t, `kept.push(new ArrayBuffer(512 * 1024 * 1024));`, 1<<20, nil)
	app.Press("id:go")
	var after runtime.MemStats
	runtime.ReadMemStats(&after)
	t.Logf("heap after %d MiB with a 1 MiB limit, failed=%v", after.HeapAlloc>>20, *failed)
}

// Host allocations on another goroutine stop an innocent plugin.
var sink [][]byte

func TestReproHostAllocation(t *testing.T) {
	app, failed := reproApp(t, `const end = Date.now() + 300; while (Date.now() < end) {}`, 64<<20, nil)
	go func() {
		for range 100 {
			sink = append(sink, make([]byte, 1<<20))
		}
	}()
	app.Press("id:go")
	t.Logf("plugin allocating nothing, host 100 MiB, limit 64 MiB: failed=%v", *failed)
}

@houko
houko force-pushed the feat/tsx-memory-limit branch from 185e9cd to 177faa9 Compare November 19, 2026 08:28
@github-actions github-actions Bot removed the conflict Conflicts with the base branch; resolve it first label Nov 19, 2026
@houko
houko force-pushed the feat/tsx-memory-limit branch from 177faa9 to 4194ef0 Compare November 19, 2026 09:57
@github-actions github-actions Bot added size/L and removed size/M labels Nov 19, 2026
@houko houko changed the title fix(tsx): bound sandbox heap growth fix(tsx): count sandbox memory where built-ins allocate by size Nov 19, 2026
@github-actions github-actions Bot added the conflict Conflicts with the base branch; resolve it first label Nov 19, 2026
Add tsx.Limits.Memory, off by default, and memory= in -limits. A sandbox with one replaces, before hardening, the goja built-ins that allocate by a size the bundle gives them (ArrayBuffer and the typed arrays with their copying, transfer and join methods, String repeat/padStart/padEnd/raw, Array.from, Array join/toLocaleString/fill/sort/toSorted/toReversed/toSpliced/with, the argument lists of apply, Reflect.apply and Reflect.construct, and JSON.stringify) with wrappers that check the sandbox's budget before calling the original and charge what it made, by a weak pointer to its memory, until a cleanup sees the collector free it. Past the budget the runtime stops with ERR_NSH_QUOTA_EXCEEDED, as past its node quota.

This replaces sampling the process heap during each call, which missed a single large allocation, reset across calls, and stopped bundles for the host's allocations.

Refs #760
…at JSON.stringify and String.raw write

A getter, a proxy or a valueOf on a length could read 0 for the wrapper's check and then a huge length for the original (typed array constructors, Array.from, sort, fill, toSorted, toReversed, toSpliced, with, apply, Reflect.apply, Reflect.construct, String.raw and JSON.stringify's property list), letting one call allocate gigabytes under a 1 MiB budget. The wrappers now read the size once and hand the original a value, a copy or a proxy that answers it.

JSON.stringify now counts the indentation of deep output, escapes, numbers and raw JSON, and counts a property list too, through a proxy per object with just the listed keys. String.raw counts the strings it joins. Strings JSON.stringify returns as imported strings are held like the others.

The docs say plainly that copies, concatenations, spreads and replace are not counted, and that they allocate at the speed of memory.
@houko
houko force-pushed the feat/tsx-memory-limit branch from 4194ef0 to 7b86bfb Compare November 19, 2026 12:04
@github-actions github-actions Bot added size/XL and removed size/L conflict Conflicts with the base branch; resolve it first labels Nov 19, 2026
@houko

houko commented Nov 19, 2026

Copy link
Copy Markdown
Collaborator Author

Reviewed. Adversarial pass found that the wrappers checked a size and the original read it again: a length getter, a proxy or a valueOf reading 0 then 2^24 let new Uint8Array(o), Array.from, sort, fill, toSorted/toReversed/toSpliced/with, apply/Reflect.apply/Reflect.construct and JSON.stringify's property list allocate 100 MiB to 3.6 GiB under a 1 MiB budget, and String.raw (segment sizes), JSON.stringify (deep indentation, a property-list replacer, raw JSON) and non-ASCII stringify results (imported strings, never held) were uncounted. The added commit reads each size once and hands the original a value, a copy or a proxy pinned to it, counts what stringify and String.raw write, holds imported strings, adds TestMemoryReadsSizesOnce, TestMemoryStopsWhatAddsUp (both measure allocation, and failed before the fix) and equivalence cases (property-list order, private-field iterables, setter this, gaps), and says plainly in the docs that copies, concatenations, spreads, flat and replace still allocate past the budget at memory speed. Subclassing, Reflect.construct with another newTarget and species all go through the wrappers; no path to the unwrapped constructors was found.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working cli documentation Improvements or additions to documentation size/XL tsx

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant