Skip to content

Worker runtime performance and typed shared memory - #15

Draft
Qard wants to merge 59 commits into
mainfrom
perf/worker-runtime
Draft

Qard wants to merge 59 commits into
mainfrom
perf/worker-runtime

Conversation

@Qard

@Qard Qard commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Draft. Stream: Worker performance in isolation, before any parallel-compiler work.

Landing bar: this lands only when every operation it touches is at or below Node 26.13.1 on macOS arm64 and Linux arm64. Remaining gaps and what bounds them are listed below.

  • Design: docs/design-worker-runtime.md; typed shared memory in §5, "Typed buffers"; shared string bodies in §5, "Shared string bodies".
  • Evidence:
    • docs/results/worker-runtime-baseline-v1.md, -phase2-v1.md, -linux-v1.md
    • docs/results/worker-runtime-transport-v1.md
    • docs/results/worker-runtime-nursery-v1.md
    • docs/results/worker-runtime-detach-v1.md
    • docs/results/worker-runtime-large-objects-v1.md (parked; code on perf/large-objects-wip)
    • docs/results/worker-runtime-first-minor-v1.md
    • docs/results/worker-runtime-zero-copy-v1.md
    • docs/results/worker-runtime-release-window-v1.md

What it does

Benchmarks. tools/worker-bench/ runs every workload under native Tint and under Node 26.13.1.

  • Native images run under LLDB, which must report the stop at entry and exit 42.
  • measure.ts runs paired, rotated sets of 15+ rounds and records the load average.

Worker execution.

  • Each arm64 Worker isolate gets its own generational heap and keeps the whole-program analyses.
  • Worker entry modules compile through the typed pipeline.
  • Inlining is classed by interruptibility, and stop polls sit at loop headers.
  • An isolate's collector pool starts with its heap and is joined when the isolate exits. arm64 now sends the allocator's shutdown request as x86-64 did; before this, arm64 never joined the pool.

Result: code in a Worker program runs at 0.98–1.04× the same code without Workers.

Transport.

  • Fixed-width clone counts and numbers; linear packet assembly.
  • Recycled port packet blocks, coalesced signals, and polling before parking.
  • A lone primitive skips the clone tables.
  • Packet references are reserved per segment, and atomic-wait checkpoints return at once when nothing is pending.
  • When postMessage is still the intrinsic one, the typed worker_threads facade sends without a realm call (672ce5d74).
  • Shared string bodies. Strings of at least 32,768 units travel as bodies of a process-wide arena (a5856ceaf).
    • The receiver uses the sender's flat string object directly.
    • The sender copies it at most once: an ephemeron cache reuses the body for the same string, and a string already in the arena needs no copy.
    • Each isolate's collectors hold a body while the isolate can reach its string. That covers cheney, the parallel evacuator, the compactor (serial and parallel marking) and the copying runtime.
    • A full arena or hold queue falls back to the copy, and the fallback is counted.

Memory release (da16bafc2). On both backends, memory-release returns pages only inside the context's managed mapping or inside the one releasable window the isolate's identity page records: the shared string arena, recorded by the Worker host. Any other range returns -1. Before, x86-64 checked the managed mapping only and arm64 checked nothing. A refused release is counted and is never the normal path.

Typed shared memory.

  • Typed Atomics run inline on native Uint8, Uint16 and Uint32 arrays (IR array-atomic).
  • Typed SharedArrayBuffers come from the isolate's shared blocks.
  • Posting a typed SAB, or a view of one, shares its block. A typed program's other typed arrays clone as realm typed arrays.
  • A realm typed array passed to a typed parameter, or narrowed by instanceof, is viewed natively.
  • A projected view over an ordinary buffer observes the buffer's detachment as V8 does, instead of pinning it:
    • length becomes 0, reads give undefined and writes are ignored;
    • Atomics and validating methods throw TypeError.

Regression fixed: e55e9f7d0 made the codec test every value as a native typed array before viewing it as a realm object. That made clones and round trips up to 2.2× slower; 3934a2cec restores them.

Against Node (macOS arm64)

Untyped rows are at 3934a2cec, except where noted; typed rows are at 672ce5d74.

At or below Node:

Operation / Node
Startup, terminate 0.25–0.59× (04e2d721c)
Round trip 0.77×
Port round trip 0.52×
Clone 1,024 / 65,536 numbers 0.86× / 0.72×
Clone 1 KiB string 0.96×
Clone 1 MiB string, in the suite 0.07× (a5856ceaf)
Clone 1 MiB string, isolated samples 16–22 µs against Node's 155–270 µs (a5856ceaf)
Transfers 0.95×
Batch 0.76×
waitAsync 0.99×
Typed round trip 0.39×
Typed batch 0.85×
Typed 1 KiB string 0.50×
Typed counter 0.69×

Still above Node, with what bounds each:

Operation / Node Bound by
Clone records (16 / 1,024) 2.75× / 4.19× untyped object model and call floor (PR #12); then a record/tree shape cache here
Clone trees (depth 4 / 10) 4.24× / 5.54× as above
Counters (1 / 4 Workers) 40× / 7.3× untyped builtin call floor (PR #12)
wait/notify 1.27× untyped builtin call floor (PR #12)

The Linux arm64 rotation will be rerun at the final head.

Gates

  • Frozen v7, 15 rounds: neutral at a5856ceaf (paired wall 1.0023, cycles 0.998, peak RSS 1.0000) and at da16bafc2 (wall 1.0015, cycles 1.0000, peak RSS 0.9999). Instructions are +0.27%: the arena range check on the collectors' non-moving reference paths.

  • Self-build: stage2 == stage3.

  • Test262 at e503b7ee8: Atomics 778/778 and SharedArrayBuffer 208/208, unchanged.

  • Fixtures under LLDB:

    • shared string fixture and stress (tools/build-worker-shared-strings-fixture.ts), with no refused page release and no resident granule at the end;
    • tools/build-memory-release-fixture.ts.

    Both pass on macOS arm64 and Linux arm64 (serial, parallel and copying collectors) and on Linux x86-64 (serial and parallel; the copying runtime is not supported there yet).

Known gaps

  • Projection of resizable buffers and length-tracking views still throws the explicit TypeError.
  • Typed code cannot yet narrow an unknown to the typed SharedArrayBuffer type itself, only to a typed array over it.
  • On x86-64 there is no program realm runtime for the projection fixture's instanceof (skipped there).
  • Each use of a realm typed array as a typed parameter pays a projection lookup (cached per buffer, element kind and window).
  • The typed facade still reads postMessage on every send, so an override would be honoured. Today, mixed programs that use Workers lower wholly as general, so no override can reach the facade. PR Propose general runtime re-architecture from Octane diagnostics #12's shapes can make the lookup cheap.

Notes for PR #17 (typed codegen) and PR #18 (one-byte strings)

  • New IR operations:
    • array-atomic (codec 87; its effects read and write the whole heap);
    • array-view and array-buffer-byte-length from bb24c5a91;
    • the host operations native-array-detach, string-address, string-at and string-copy.
  • string-copy copies a flat string by its header's extent and returns -1 for anything not flat. One-byte (Latin-1) string representation #18 adds each flat marker's extent there; slices are flattened through memory-write-string.
  • memory-release has one documented range contract on both backends (IR host.ts, @tint/abi nativeIdentityReleasable*Offset).
  • arm64 fixes:
    • array-byte-offset and array-byte-length were classed as booleans (bb24c5a91);
    • array-byte-offset converted as unsigned 32-bit and now converts signed 64-bit (c207bdcf1).
  • Narrowed Atomics calls lower to the atomics-uint8/16/32 builtins from the checked kind.
  • Methods on native typed arrays test length 0 before rejecting a detached view.
  • LICM keeps array lengths in loops that may run code.

Before ready

  • Merge main after PR Propose general runtime re-architecture from Octane diagnostics #12 and perf/one-byte-strings land, then add:
    • the record/tree shape cache;
    • a one-byte wire encoding.
  • Final validation at the final head:
    • Test262 Atomics and SharedArrayBuffer;
    • no-Worker image attribution;
    • stage2 == stage3;
    • Worker fixtures on all three targets;
    • 15-round rotations on both hosts, including startup with the x86-64 identity-page mapping.

🤖 Generated with Claude Code

Kernels (allocation, numeric, calls, strings, a compiler-like record and
Map workload, and a node:zlib raw-memory round trip) run in a program
without Workers, the same program with the copying collector, a program
that uses raw memory, on the main thread of a program that starts a
Worker, and inside a Worker. A transport workload covers startup,
terminate, round trips, structured clone payloads, transfers, batches,
MessageChannel ports, wait/notify, waitAsync and contended counters.
Every workload also runs under Node 26.13.1, and measure.ts rotates the
native (LLDB) and Node runs for paired comparisons.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@Qard
Qard marked this pull request as draft November 22, 2026 14:27
Qard and others added 20 commits November 22, 2026 23:16
Worker and helper-thread isolates re-enter the image's own hosted entry
with a fresh heap and module instances, and they exchange only bytes in
non-heap mappings. thread-start/join, hosted-thread-entry, word-park/wake,
shared-* and memory-unmap therefore neither write managed memory nor admit
code outside the closed root, so classify them as closed-world.

Images that start Workers (or a helper pool, as node:crypto does) keep the
interprocedural analyses, and the arm64 generational gate accepts them:
Worker fixtures now initialize a generational heap in every isolate on
both architectures. Collector helper entries, permanent code addresses and
executable capabilities still leave the closed world.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Worker entry modules were guest modules with JavaScript semantics even when
typed, so typed code ran 57-340x slower inside a Worker. A typed program
now compiles each Worker entry as a typed start function: the entry, the
modules of its graph that use the Worker bindings and the modules only it
imports evaluate in one deferred scope that the host calls in that
Worker's isolate. The linker accepts any top-level statement in deferred
modules, since they run inside a function. Entries that cannot compose
(an imported entry, or a Worker-dependent module shared by two entries)
keep the guest path, which is now reported as a general fallback.

Worker images also inline again: calls inline only when caller and callee
share an interruptibility class, so runtime helpers never gain Worker stop
polls and application code never loses them.

The typed Worker entry fixture covers per-isolate module instances, a
Worker-only module that evaluates once, top-level control flow, mutable
state, error events and abrupt exit; its Node reference runs the same
sources.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The placements set times every kernel placement in one rotation once
Workers no longer tax their code. Transport images can select one
operation by prefix for profiles, and the string payload setup is linear.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The isolated suite ran 15 rotated rounds per set on macOS arm64 against
Node 26.13.1. Typed kernels ran 1.1-13.5x slower on the main thread of a
Worker program and 45-264x slower inside a Worker than without Workers;
raw memory (node:zlib) cost nothing. Worker startup and terminate were
about twice as fast as Node, while round trips, transfers, batches and
structured clones were 2-918x slower. Profiles attribute the costs, and
the design covers per-isolate generational heaps, per-entry closed-world
analyses, typed Worker entries and the message path.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The Worker clone packet wrote every length, count and number as decimal
text: serializing formatted each number shortest-round-trip and
deserializing parsed it back exactly, which took 85% of decoding a number
array. Counts are now four UTF-16 units (a safe integer's two 32-bit
words), int32 numbers other than -0 two units, and every other number its
binary64 words, so neither side formats or parses text.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The clone serializer, the packet envelope and the receiving mailbox built
strings through a binary-counter builder, and the mailbox appended one
single-unit string per code unit. They now collect parts and join once,
which the typed pipeline sizes and writes in one pass; the mailbox reads
eight units per string.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The typed transport runs round trips, batches and 1 KiB strings between a
typed main program and a typed Worker entry with callbacks, measuring the
runtime's messaging cost without the untyped await path. Typed code cannot
create a SharedArrayBuffer yet, so shared memory stays in transport.mjs.
The transport-steps set pairs successive transport images in one rotation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The mailbox and waiter-registry locks woke their word on every release,
so each Worker message paid wake system calls even without a sleeper.
Their lock words are now three-state (free, held, held with sleepers):
uncontended acquire and release are one compare-exchange each, and only a
release after a sleeper marked the word contended wakes it. The bounded
park still guards against a lost wake.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Every MessagePort packet mapped a fresh 16 KiB block and unmapped it on
receipt, the pair lock woke its word on every release, and every send
wrote the receiver's signal pipe. Port mailboxes now keep up to 32
consumed single-quantum blocks on a free stack for the next send (the
final owner unmaps them with the mailbox), the pair lock uses the
three-state registry lock, and a sender writes the signal pipe only when
the receiver is not already signaled; the receiver clears the flag before
it drains, so no send is left unsignaled.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A recycled block keeps its free-stack link in the header word the message
queue uses as its next pointer, while a fresh mapping is zero-filled. When
a recycled block was the last message, the receiver followed the stale
link, corrupting the queue until blocks were reused and unmapped twice (the
native transport benchmark crashed at Worker exit). Preparing a packet in
a recycled block now clears that word; the mailbox test reuses several
blocks in one burst and fails without the fix.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Worker application functions polled their stop word before every call and
allocation, which cost up to 47% on call- and allocation-heavy kernels
once shared modules became Worker code. They now poll at each natural
loop header and, when they call, on entry: every unbounded execution
passes one of those (a cycle or a recursion) and straight-line code needs
none. Allocation-free, call-free loops, a documented termination gap, can
now be stopped too. A function whose loops exceed the analysis budget
keeps the per-call polls. The fast path uses a plain load: a stop request
is a monotonic signal, and the observation is still a release store.

The safepoint fixture adds a Worker spinning in such a loop; it exits 42
on AArch64 and x86-64, and the baseline compiler stalls on it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Shared modules became Worker code, so the interruptibility class rule kept
every runtime helper call in them out of line. With polls only at loop
headers and calling entries, an inlined leaf helper without a loop brings
no poll site, so it may now inline into Worker code. Worker code still never
inlines into runtime code, and runtime helpers with loops still stay calls.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The Phase 2 report pairs each fix with its rotation: typed kernels in a
Worker program now run at 0.98-1.04x the program without Workers on the
main thread and inside a Worker (from up to 13.5x and 264x), and messaging
moved from 2-918x Node toward 1.9-30x on macOS. It keeps the two rotations
that ran the recycled-block defect, and records the native fixtures,
Test262 host smoke and Atomics (778/778) evidence. The Linux arm64 report
covers the baseline and after runs, and the design records what is done
and the revised message-path plan.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
tsc -p tsconfig.tests.json rejected the widened "branch" literal, which
failed the macOS gate on e30ac39.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Whole-program optimization of threaded images must not reorder shared
accesses, and per-isolate heaps must keep buffers outside both heaps.

- worker-memory-model: Worker litmus tests over SharedArrayBuffer (ping-pong
  spins on Atomics.load, store buffering with Atomics and a plain control,
  contended Atomics and spinlock-guarded plain counters at four widths,
  wait/notify ordering). Every spin is counter-bounded, so a hoisted load
  fails instead of hanging.
- shared-ordering-litmus: store buffering and message passing directly on
  the shared access leaves from two native threads; seq-cst phases must
  show no forbidden outcome, unordered phases show hardware reordering.
- worker-transfer-stress: transfers and clones in both directions while
  both isolates churn their generational heaps; retained buffers are
  re-verified after hundreds of collections.
- worker-zlib-stress: typed main and Worker entries run node:zlib under
  the same churn and keep zlib output across collections.
- x86-64 codegen test: ordered shared stores are XCHG, unordered stores
  MOV, compare-exchange LOCK CMPXCHG and loads MOV at every width; the
  arm64 test now also fences ordered loads.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The native transport benchmark faulted at Worker exit on 34a2fde: a
recycled packet block kept its free-stack link in the queue's next word, so
a receiver followed it when that block carried the last queued message
(fixed in 8d11261). The fixture repeats the benchmark's sequence across
eight Worker lifetimes: bursts on parentPort, single round trips in recycled
blocks, the same on a transferred MessageChannel port, then exit. Built from
34a2fde it faults in shared-read-word64 in 3 of 3 runs; from the fix it
exits 42.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Messages were UTF-16 strings built in the sender's heap, copied into the
packet one code unit per host call, and rebuilt in the receiver's heap the
same way. Profiles of the clone gaps showed those per-unit copies and the
per-index key strings of arrays.

Messages are now serialized straight into a native packet and decoded from
it, after V8's ValueSerializer:
- one-byte tags, varint counts and lengths, zigzag int32;
- binary64 values at eight-byte-aligned offsets;
- strings copied in bulk as UTF-16 (inline up to 16 units);
- packed number arrays as one binary64 run, other packed arrays by position
  with explicit holes;
- property keys written once and referenced after;
- small cloned ArrayBuffers inside the packet, large ones in an adopted
  mapping as before.
The traversal, property order and getter calls are unchanged.

Packets cross ports by pointer: the sender allocates from the peer's
mailbox (recycled 16 KiB blocks), fills and publishes; the receiver drains
every queued packet under one lock, decodes in place and recycles the block
before running script. Undelivered packets go back to the queue head when a
watched port is transferred or closed.

New host operations back the codec: memory-read-float64 and
memory-write-float64 (inline window-checked binary64 access) and
memory-write-string and memory-read-string (bulk UTF-16 copies through
memmove, the read allocating its string), on arm64 and x86-64.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Qard and others added 7 commits November 23, 2026 05:58
The first paired run of binary packets showed batch 1.68x slower than
the string transport: every packet of a burst took its own 16 KiB
mapping (mmap, a zero-fill fault and munmap), draining a burst shifted
an array per packet, and each message cost one event-loop turn.

- Small packets bump-allocate in reference-counted segments (recycled
  blocks); large ones keep a mapping of their own. Up to 128 blocks per
  mailbox are recycled.
- A port drains its whole queue under one lock and keeps a cursor.
- One I/O task delivers every queued packet, bounded at 1000, with a
  microtask checkpoint between them as Node's MessagePort does
  (EventLoop.checkpointWithin).
- The signal flag clears only when a drain finds the queue empty, in the
  queue-lock hold where senders decide to signal, so senders to a busy
  receiver write no pipe.
- Senders write the wake pipe after both locks are released; signal
  pipes now close with the pair, which keeps them open for any sender.
- Contended registry locks spin briefly before parking.

Batch moves from 19.8 us to 0.61 us per message on macOS arm64 (Node
0.63). On Linux arm64 this protocol is equal or faster than the
previous one in every transport operation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Clone string 1 MiB spent most of its time mapping, faulting in and
unmapping a fresh multi-quantum packet per message. A recycling mailbox
now keeps the larger of its last two released large mappings; a send
that fits (without using under a quarter of it) takes it warm. The
large clone drops from 405 us to 171 us on macOS arm64 (Node 155 us).

The encoder read each own data property twice ([[GetOwnProperty]] and
[[Get]]); it now encodes the descriptor's value unless the object
overrides [[Get]], and accessors still run their getter.

tools/worker-bench/call-floor.mjs measures the untyped call floor under
Atomics (diagnostic only).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Atomics.load, store, compareExchange and the read-modify-write operations
take a fast path for the common case: a fixed-length Int8-Uint32 view over
a SharedArrayBuffer, an in-range integer index and Number operands. A
shared block never shrinks and none of those conversions can run Script,
so the operation is one service call on the element's unsigned encoding,
with no scratch byte arrays or length revalidation. Read-modify-writes use
a new SharedBlockAtomics.updateUnsigned that runs the compare-exchange
loop beside the block. Everything else keeps the general path.

The native shared block facade also resolves a handle's location once per
isolate: a published descriptor never changes and its mapping lives as long
as the engine.

Natively, an untyped Atomics.add loop drops from about 883 ns to 345 ns per
call and Atomics.load to about 315 ns, against a 225 ns untyped builtin call
floor (Math.abs).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
On macOS a zero-timeout kevent64 is not a poll: a zero timespec takes the
timed-wait path and reschedules the thread, about 11 us per call against
0.15 us with KEVENT_FLAG_IMMEDIATE. The event loop polls that way on every
turn that has work queued, so every Worker message hop paid it. The Darwin
reactor now passes KEVENT_FLAG_IMMEDIATE for zero timeouts; Linux's
epoll_wait with a zero timeout is already a true poll.

Before a loop blocks, a port that delivered in that turn polls its queue
for up to 50 us, bounded by the next timer, through a new reactor idle
source. While it polls, its signal flag tells senders it is awake, so they
skip the pipe write; it then settles under the queue lock, scheduling
queued packets or clearing the flag so the next send wakes it. A loop that
keeps finding work this way checks its descriptors at most once per
millisecond. The blocking poll after an empty spin gets what remains of
its timeout.

On macOS (five rotated rounds against Node 26.13.1) the round trip falls
from about 41 us to 7.4 us (0.86x Node), the port round trip from 37 us to
4.8 us (0.60x), and transfers and 1 KiB string clones to about 1.0x. The
transport suite uses about 8% more CPU.

The design document's message-path list now reflects binary packets,
batched delivery and the wake path, and gains the shared-memory soundness
section.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
An idle poll no longer allocates: the loop keeps one list of armed sources
and a port settles with its own metadata scratch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The memory-read-string lowering looped over an `as const` tuple array and
read `host.symbolPrefix` after a nested function had dropped its
narrowing; the native compiler bootstrap rejects both. Check the four
arguments through a small helper and bind the memmove symbol first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- A lone primitive serializes and deserializes without the reference
  tables and helper closures an object graph needs, with the same bytes;
  a malformed payload still goes to the graph decoder.
- A packet producer reserves a segment's references when it opens it, so
  carving a packet needs no shared read and compare-exchange; closing the
  segment hands back the uncarved ones.
- An atomic-wait checkpoint with nothing pending returns at once.

A Linux perf profile of the batch transport put the codec at about 15% of
its time for one-number messages and segment reference updates among the
metadata host calls. In seven rotated rounds against Node 26.13.1, batch
falls from 0.69 to 0.49 us per message on Linux arm64 (1.33x to 0.95x) and
from 0.65 to 0.48 us on macOS arm64 (1.04x to 0.76x).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Qard and others added 5 commits November 23, 2026 09:49
docs/results/worker-runtime-transport-v1.md reports the zero-timeout
kevent64 root cause, the bare wake mechanisms, polling before parking with
its CPU cost, and the per-message cuts, with the paired macOS and Linux
sets as evidence. The design document's message path describes binary
packets, batched delivery and the wake path, the polling window's CPU
trade-off, and typed buffers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Every policy that removed the isolated 1 MiB clone's first-touch cost
regressed the frozen v7 compile by about 2.1% instructions, so the
collector is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Typed code could not name Atomics: the binder rejected it as a global the
program realm does not install, so a typed program had to fall back to the
general path for any Atomics call. Typed code now runs Atomics.load,
store, add, sub, and, or, xor, exchange and compareExchange inline on
native Uint8Array, Uint16Array and Uint32Array values, including views of
an ArrayBuffer. Float64Array is rejected as the pinned library types it.
Other arguments, such as realm typed arrays, still take the general
fallback.

The lowering performs ValidateAtomicAccess, emitting the same RangeErrors
as V8:
- ToIndex of the index, then the length check.
- The operands are numbers, so their ToIntegerOrInfinity cannot run code.
- Atomics.store yields ToIntegerOrInfinity(value), with +0 for NaN and
  either zero.

The new `array-atomic` IR operation carries the access:
- Operands convert as element writes do.
- Every operation but store yields the previous element.
- It traps on an index the lowering has not validated.
- Its effects read and write the heap, so not even a load merges with or
  moves across another access.
- arm64 uses exclusive-pair loops between full inner-shareable fences, as
  the shared-memory primitives do.
- x86-64 uses xchg, lock xadd and lock cmpxchg; a load is a plain load
  under x86-TSO.

tools/native-typed-atomics.test.ts runs the same source under Node and
natively. It covers wrap-around, conversion of the expected value, store
results, index truncation and RangeErrors, and views at an offset. It
exits 42 on macOS arm64, Linux arm64 and Linux x86-64.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Typed code could not name SharedArrayBuffer: the binder rejected it as a
global the program realm does not install. Only the Worker host created a
shared block service, for the realm's constructor. Typed code now has a
SharedArrayBuffer type kind:
- `new SharedArrayBuffer(length?)` creates a fixed-length buffer. A
  maxByteLength option still takes the realm constructor.
- `byteLength`.
- Views of every native element type, with ArrayBuffer's RangeErrors.
- Inline Atomics on those views.

A typed buffer is a block of the isolate's shared block service, viewed
by a borrowed byte array that never moves:
- The lowering calls the `newSharedBlock` runtime helper for the block's
  payload address.
- The existing `c-memory` adopt operation turns an empty byte array into
  that view.
- The view roots the buffer as ArrayBuffer's owner array does.
Blocks stay mapped for the engine's lifetime, so no finalization is
needed.

Typed code reaches the service without the Worker host, and without
module state, which retained runtime helpers cannot hold
(native-runtime/src/shared-buffers.ts):
- The isolate's registry is recorded in the first two words of its
  context's identity page.
- The Worker host records the service it creates or attaches.
- An isolate without one creates its own on first use.
- The words are accessed through the shared memory host, which the
  generational mutator's closed-world proof admits; raw memory-word
  writes it does not.

x86-64 now maps that identity page in every context, read-write, as
arm64 already does. It used to map it only for threaded or JIT images,
inaccessible, so every other x86-64 context had domain 0. Each x86-64
image now makes one more mmap at startup.

Builds opt in to the shared buffer runtime, as they do to Worker shared
memory:
- worker-fixture-options.ts supplies the runtimes and host bindings.
- Hosted fixtures load requested runtimes as roots.

tools/native-typed-shared-buffer.test.ts runs the same source under Node
and natively. It covers views at offsets, Atomics, 64 buffers kept
through collections, and the RangeErrors. It exits 42 on macOS arm64,
Linux arm64 and Linux x86-64. The typed Worker entry fixture still exits
42.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@blacksmith-sh blacksmith-sh Bot mentioned this pull request Nov 23, 2026
15 tasks done
Qard and others added 8 commits November 23, 2026 12:38
A typed SharedArrayBuffer, or a typed array over one, is a native byte array
over a shared block. The codec copied it like any native typed array, so
the receiver got a private copy where Node shares the buffer.
- The codec asks the host whether a native typed array's buffer is a shared
  block (WorkerCloneAttachments.encodeNativeBuffer).
- The native Worker host answers by the buffer's payload address, through
  the service's new trusted `handleAt`, and grants the block as it grants a
  realm SharedArrayBuffer ('s').
- A typed buffer posts as the block's realm SharedArrayBuffer; a view posts
  as a realm typed array over it. Each block is attached once per message.

Also fixes object indices for native typed arrays, wrong since e55e9f7:
the encoder registered none for them, while the decoder allocates two (the
view and its buffer), so a later back-reference in the same message named
the wrong object. The encoder now counts the indices it hands out.

The Worker host now installs the realm's TypedArray and ArrayBuffer
intrinsics. A received typed array otherwise got no prototype when no
source names a typed-array constructor, as in a typed-only Worker, so its
methods were missing and realm instanceof failed.

The shared block service gains a trusted `bytes(handle)`, a nonmoving view
of a block's payload, which the realm-to-typed projection uses. The Node
reference service views its SharedArrayBuffer.

A typed main posting a view of a typed SharedArrayBuffer to two JavaScript
Workers that add with Atomics sees every add (exits 42 on macOS arm64).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… typed Workers

Typed code could not use a realm typed array: a native typed-array
parameter threw "requires the slice 2b buffer view", and Atomics on a
narrowed `unknown` did not compile.

A realm typed array of the parameter's kind with a fixed native window is
now viewed natively, through the dynamic-object runtime's
projectNativeTypedArray. It runs only when the value is not already a
native array.
- **Ordinary buffer:** the view is an `array-view` over the backing, which
  collections move together with the view.
  - The backing is then pinned with a host [[ArrayBufferDetachKey]], as a
    WebAssembly memory's buffer is: detaching or transferring it, including
    as a Worker transfer, throws TypeError.
  - The view therefore never outlives the bytes it shares.
- **Shared block:** the view covers the block's nonmoving payload.
- **Still TypeError:** resizable buffers, length-tracking views, growable
  shared buffers, big-endian views, and values that only imitate a typed
  array.
- **Atomics** on an `unknown` narrowed by `instanceof` convert the same way.
  The closure lowering passes the array's checked kind, since the narrowed
  binding keeps its general carrier.

tools/native-realm-array-projection.test.ts replaces the projection-failure
fixture and now runs in CI. It checks writes in both directions, element
offsets, collections, narrowed Atomics, the pin, and the TypeErrors. It
exits 42 on macOS arm64 and Linux arm64. The x86-64 general lowering lacks
the program realm runtime this fixture's instanceof needs, so it is skipped
there with that reason.

tools/build-worker-typed-shared-fixture.ts is fully typed, with no general
fallback:
- A typed main and two typed Workers add 20000 times each to counters in a
  typed SharedArrayBuffer.
- The main posts a view of the buffer; each Worker narrows the realm typed
  array it receives and runs Atomics on it natively.
- Every add arrives. It exits 42 under LLDB on macOS arm64, Linux arm64 and
  Linux x86-64, and tools/worker-typed-shared.test.ts runs the same sources
  under Node.

Hosted fixtures no longer load generated modules as workspace roots when
they are listed as runtimes. The Worker design and unified pipeline
documents describe typed buffers, the projection and the shared-memory
invariant for typed code.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The typed transport workload gains `typed-counter`:
- The main program posts a view of a typed SharedArrayBuffer to its typed
  Worker. Each side then adds to the same counter 100,000 times with inline
  Atomics, while the other side does too.
- The Worker passes the realm typed array it receives to a typed parameter,
  which views it natively once.
- Node runs the same sources.

A single macOS arm64 run (not a rotation):

| Image | Per 200,000 contended adds |
| --- | ---: |
| Node | 1.5–2.3 ms |
| Native | 1.4–1.6 ms |

Using the narrowed `unknown` directly in the loop instead re-projects it on
every Atomics call, about 9 ms.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
212639d declared the message packets' raw-window intrinsics in
intrinsics/memory.ts:
- readMemoryFloat64 and writeMemoryFloat64;
- readMemoryString and writeMemoryString.

Every image's collector runtime compiles memory.ts whole, so those unbound
declarations entered every image. Programs that start no Worker were no
longer byte-identical to main.

They now live in intrinsics/packet-memory.ts. Images that carry packets
declare it as a runtime and bind it:
- the Worker fixture options;
- the clone, messages and ports fixtures.

The no-Worker benchmark image (tools/worker-bench plain) now differs from
main 183ec70 only by intended changes:
- macOS arm64 and Linux arm64: bb24c5a's fix to the arm64 result type of
  byteOffset and byteLength (2eb18f3d5cd4… and 883169d962aa…, the same as
  main with that fix).
- Linux x86-64: a74d5be's identity page in every context (5be089d09384…,
  the same as main with that change).

The clone, messages, ports, typed entry and typed shared Worker fixtures
exit 42 under LLDB on macOS arm64.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
e55e9f7 checked every value for a typed program's native typed array
before viewing it as a realm object. In a program on the general path those
four instanceof tests are realm instanceof calls, so every record, tree node,
string and buffer message paid for them. The encoder now views the value as
a realm object first and tests for a native typed array only when it is not
one (a native typed array is opaque to the realm).

Transport, macOS arm64, 15 rotated rounds (load 2.9-3.8), against
e47f386 and 6d37cee (before the regression):

| Operation | 6d37cee | e47f386 | This | This / Node |
| --- | ---: | ---: | ---: | ---: |
| round-trip | 6.60 | 8.13 | 6.70 | 0.77x |
| clone-records-16 | 57.4 | 119.6 | 57.3 | 2.75x |
| clone-tree-10 | 7,184 | 15,887 | 7,237 | 5.54x |
| clone-string-1KiB | 9.00 | 12.19 | 9.12 | 0.96x |
| transfer-65536 | 9.36 | 14.13 | 9.52 | 0.95x |

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… pinning it

0290e62 pinned an ordinary buffer once typed code viewed it natively, so a
later transfer or detach threw. A typed program that reads a buffer and then
hands it to a Worker, or detaches it with ArrayBuffer.prototype.transfer, broke.
A projected view now observes the detachment as V8's typed arrays do.

- The buffer's backing record lists the native views projected over it, one
  per element kind and window, and detachByteStorage runs a single hook that
  detaches each through the new native-array-detach host operation
  (packages/native-runtime/src/intrinsics/native-array-detach.ts, bound
  wherever the dynamic-object runtime is).
- A detached view has length 0 and its data one word before its owner's
  payload. Element reads give undefined and writes are ignored by the existing
  bounds check; byteOffset reads as 0.
- Atomics and the validating methods (fill, set, subarray, slice, join, at,
  reverse, indexed iteration) throw TypeError for a detached view after a
  length-0 test, so a nonempty array pays one compare.
- LICM no longer hoists a typed-array length out of a loop that may change
  it: one with an operation that invokes code, a may-callback C call, or a C
  memory adoption or retarget.
- Native-born typed arrays and shared-block views never detach and keep the
  direct path. Resizable and length-tracking buffers keep the TypeError.

Also fixes two arm64 issues: array-byte-offset converted the difference as an
unsigned 32-bit integer (now signed 64-bit, as on x86-64), and the void detach
host call was emitted after the host result check.

Cost against e47f386, macOS arm64, 15 paired rotated rounds each:
- PR #17's typedArrays kernel: 48.1 ms both (identical kernel code).
- Typed transport: 0.97-1.00x per operation. Untyped transport: 0.98-1.02x.
- Frozen v7: instructions +0.04%, cycles +0.05%, peak RSS -0.03%.

tools/native-realm-array-projection.test.ts exits 42 on macOS arm64 and Linux
arm64 (skipped on x86-64, which has no program realm runtime for its
instanceof). The native subset check passes and stage2 == stage3.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The worker clone fixture now serializes a message holding a typed program's
native typed array followed by an object named twice. The decoder allocates
two objects (the view and its buffer) for the typed array, so the second
reference must count them: 6904683 fixed the encoder's indices, and this
covers it in native code. Exits 42 on macOS arm64 and Linux arm64.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…lone

docs/results/worker-runtime-detach-v1.md: the cost of detach-aware typed
views (none measurable on PR #17's typedArrays kernel, the transport sets
or frozen v7), the e55e9f7 codec regression and its fix in 3934a2c, and
the 1 MiB string clone's shift in heap state from 6904683, with the
remaining transport gaps against Node and what bounds each.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@Qard Qard changed the title Worker runtime performance: isolated benchmarks, then per-thread GC and analyses Worker runtime performance and typed shared memory Nov 23, 2026
Qard and others added 7 commits November 23, 2026 18:35
The typed worker_threads facade sent every message by reading postMessage
from the realm object and calling it as a realm function: a property lookup,
an argument array and a full realm call per message. A profile of the typed
batch (10,000 numbers from typed main to a typed Worker) showed the sender
bound the batch, with the realm call machinery 15% and the lookup 10% of the
sending thread.

The facade still reads postMessage, so an object whose method was replaced
keeps calling the replacement. When it is one of the module's two intrinsic
postMessage functions (identified by object identity, assigned at creation),
the new NodeWorkerThreads.post sends through the same endpoint lookup and
messages.send as the intrinsic, with the transfer list as given.

Typed transport, macOS arm64, 15 rotated rounds (load 2.6-3.1), against
eede93e (docs/results/worker-runtime-detach-v1-typed-post.json):

| Operation | Before | After | After / Node |
| --- | ---: | ---: | ---: |
| typed-batch | 0.60 | 0.48 | 0.85x |
| typed-round-trip | 2.64 | 2.54 | 0.39x |
| typed-string-1KiB | 3.47 | 3.31 | 0.50x |

The typed Worker entry and typed shared fixtures exit 42 on macOS arm64.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
c207bdc kept a buffer's projected native typed arrays in a
NativeStorageView[] list, a new collection type in the Script runtime
surface: one more anchor and list class with its eight operations, which
tools/script-runtime-surface.test.ts rejects (130 anchors, expected 129).
The views now form a chain through a `next` field, as other per-record
sequences in the surface do, so the surface's collection types are unchanged.

The surface test passes, and tools/native-realm-array-projection.test.ts
still exits 42 on macOS arm64.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Since 6904683, shared-blocks.ts imports the FFI primitives (adoptExternal),
so a program using typed SharedArrayBuffers loads them. The hosted fixture
builder then appended the FFI runtimes, which declare intrinsics/memory.ts,
after the fixture's own declaration of the same module, and compilation
failed with "duplicate runtime module" (tools/native-typed-shared-buffer
.test.ts on macOS CI). Declarations of one module now merge: the first
namespace stands, retained exports are combined, and a whole-module
declaration retains everything.

The typed shared buffer, typed Atomics and realm array projection native
tests pass on macOS arm64.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
docs/results/worker-runtime-large-objects-v1.md: the design (preserved on
perf/large-objects-wip, ed12de5), its correctness evidence, the two bugs
it surfaced, and why it is parked: frozen v7 regresses (+1.9-2.4%
instructions with a 16 MiB young budget, +3.0% peak RSS with a 128 MiB one)
and the 1 MiB string clone does not improve, isolated or in the suite.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The hosted entry's cleanup sends the allocator's shutdown request on arm64
as x86-64 already did, so the generational runtime joins its parallel
collector threads before the heap, control and stack mappings go. Before,
an arm64 Worker isolate whose nursery reached the parallel threshold left
its pool threads parked on unmapped words.

The call runs while sp is still the entry frame on the mapped stack: x28
holds the runtime's allocator closure once it is published. An abrupt
completion keeps every mapping and exits 71.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A generational isolate starts its parallel collector threads at
initialization (ParallelEvacuator.warm) instead of inside its first large
collection, which already promotes the whole startup heap.

Fifteen rotated rounds (docs/results/worker-runtime-first-minor-v1.md):
- frozen v7 is neutral: paired wall 1.003, cycles 1.0025, instructions
  1.0000, peak RSS 0.9999;
- Worker startup stays at 0.28x Node;
- the isolated 1 MiB clone's first three samples improve 3-5% in median.

A forced collection at the end of host setup was rejected: it made Worker
startup 8.4-9.5 ms against Node's 5.2-5.6 ms.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A string of at least 32,768 units travels between Worker isolates as a
body of the process's shared string arena: the receiver uses the sender's
flat string object directly, as it does an image literal.

- The arena (external-memory.ts, shared-string-arena.ts): one 256 MiB
  reservation in page-sized granules, made by the first isolate that needs
  it, with a control page in the engine grant. A body is a reference count,
  its granule count and a flat string object copied verbatim by its
  header's extent. A full arena, or a full hold queue, falls back to the
  copy and is counted.
- Sending (shared-strings.ts): a string in the arena adds a reference; a
  bounded ephemeron cache, keyed weakly by the sent string, finds a body
  made earlier; otherwise one copy makes a body. Messages carry a `t` grant;
  discarded and unpublished messages drop their reference.
- Receiving: the decoder returns the body's string object; the isolate
  queues a hold that takes over the message's reference.
- Holds: each generational and copying runtime keeps a hold table in unused
  workspaces and publishes it in the identity page. Cheney, the parallel
  evacuator and the compactor (serial and parallel marking) mark arena
  references with one range check. A minor collection frees unmarked young
  holds and ages marked ones; a full collection frees every unmarked hold;
  shutdown frees them all. The last reference frees the body.
- New host operations string-address, string-at and string-copy on both
  backends; string-copy returns -1 for a string that is not flat, the hook
  for sliced strings.

tools/build-worker-shared-strings-fixture.ts covers echo, a discarded
message, four holders, terminated holders, a minor then a full collection,
a body kept only by a message in flight, and contention, for serial,
parallel and copying collectors.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Qard added a commit that referenced this pull request Nov 23, 2026
…rimitives

Sliced strings now hold the byte offset of their first unit in the
parent's units, then the parent, as V8's sliced strings do. The parent is
an ordinary reference slot: Cheney's referenceSlot, the parallel
collector's and the compactor's markReference reach it, and collectors
copy slices verbatim, so the slice-specific relocation code goes.

Every reader tests the sliced flag with one TBZ (new AArch64 TBZ/TBNZ
encodings and a leaf-assembler testBit) on a header it loads anyway.
Equality compares lengths first, sends equal header words to the helper
and otherwise only pairs that include a slice; the helper reuses the
prelude's loads. string-slice copies short results after one length
test, skips the kind scan for one-byte sources and initializes slices
inline.

String helpers start on 64-byte boundaries and pad their loop heads to
32 bytes, so their copy and search loops never straddle a 64-byte fetch
block wherever the code before them ends.

For PR #15's cross-isolate transfer, @tint/abi/host gains
nativeStringIsFlat and nativeFlatStringExtent, and two IR instructions
bind through the memory intrinsics: string-flat (isFlatString) and
string-flatten-into (flattenStringInto), which writes a string's flat
image into a raw window, flattening slices. Like memory-write-bytes, the
latter leaves the closed world for record-layout facts. Both backends
lower them; tools/native-string-transfer.test.ts checks the images,
including a one-byte image literal's.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Qard and others added 7 commits November 24, 2026 02:39
x86-64's memory-release only maps over the managed heap, so returning a freed
body's pages failed outside it and threw inside a collection. A refused
release now leaves the body resident (counted in the arena's statistics) and
the runtime stops asking. The fixture's in-flight step collects in a later
turn, so no frame of the sending turn can still hold the sent string on
either backend.

The shared string fixture and its stress pass on Linux x86-64 (serial and
parallel; the copying runtime is not supported there yet).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
docs/results/worker-runtime-zero-copy-v1.md:
- the 1 MiB string clone falls from 290 to 20 us in the transport suite
  (0.07x Node), and to 16-22 us isolated (Node 155-270);
- frozen v7 is neutral on wall, cycles and peak RSS;
- stage2 == stage3;
- Test262 Atomics 778/778 and SharedArrayBuffer 208/208;
- the fixtures and stress pass on macOS arm64, Linux arm64 and Linux
  x86-64.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
memory-release returns pages only inside the context's managed mapping or
inside the one releasable window the isolate's identity page records
(@tint/abi nativeIdentityReleasable*Offset); any other range returns -1
and maps nothing. x86-64 had the managed-mapping check alone, and arm64 had
none. The Worker host records the shared string arena as the window when it
attaches, so collectors return freed body pages on every backend.

A refused release is now only a counted path (refusedReleases in the arena
statistics), never the normal one: the sticky x86-64 fallback is gone.

tools/build-memory-release-fixture.ts checks the contract from a collector
runtime:
- an unregistered range is rejected and keeps its contents;
- the registered window releases, and reads as zero afterwards;
- ranges straddling the window or below it are rejected, as are misaligned
  ones and the window once unregistered.

The shared string fixtures now also require no refused release and no
resident granule at the end. Both pass on macOS arm64 and Linux x86-64.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
docs/results/worker-runtime-release-window-v1.md:
- the release fixture and the shared string fixtures pass on macOS arm64,
  Linux arm64 and Linux x86-64, with no refused release and no resident
  granule at the end;
- frozen v7 is neutral (paired wall 1.0015, cycles 1.0000, peak RSS 0.9999).

The design doc describes the releasable window.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Each isolate allocates about 2.7 MB during setup and keeps 1.5 MB, which adds
only 1-3 ms to its first minor collection. Neither old-space startup
allocation nor lazy intrinsics is built. The per-collection fixed cost it
found is investigated next.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
tools/worker-shared-strings holds native fixture programs that import Tint
host modules (gc, clock, host, strings, string-address). Only the Tint
compiler resolves those modules, and the fixture build already type-checks
them. tsconfig.tests.json included them through tools/**, so the workspace
typecheck failed with TS2307 on every platform since they were added.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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