Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,8 @@ Core built-ins include `Math`, `JSON`, `Object`, `Function`, `Array`, `Boolean`,

Non-standard data-format APIs and SemVer are import-only Goccia runtime modules, not auto-installed globals: `goccia:csv`, `goccia:json5`, `goccia:jsonl`, `goccia:toml`, `goccia:tsv`, `goccia:yaml`, and `goccia:semver`. They expose named exports only; use `import * as CSV from "goccia:csv"` when you want the namespace-object shape. There is no default export.

`node:async_hooks` is an import-only module too, at Node's own address and with Node's exports: `AsyncLocalStorage` and `AsyncResource`, named and on the default export. The engine propagates the async context, so a store bound with `run` survives `await` and every promise-reaction continuation. See the [Async Context reference](docs/built-ins-async-context.md) and [ADR 0112](docs/adr/0112-native-async-local-storage.md).
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

Native FFI is an explicit unsafe runtime opt-in (`--unsafe-ffi` or the matching configuration key). It provides native-layout structures, unions, fixed-length arrays, callbacks, and guarded library lifetimes through GocciaScript's custom bidirectional ABI machinery. See the [FFI reference](docs/built-ins-ffi.md) and [ADR 0095](docs/adr/0095-custom-bidirectional-ffi-abi-engine.md).

See [Built-in Objects](docs/built-ins.md) for the complete API reference.
Expand Down Expand Up @@ -379,6 +381,7 @@ See [Core patterns](docs/core-patterns.md) and [Interpreter](docs/interpreter.md
| [FFI Built-ins](docs/built-ins-ffi.md) | Native libraries, aggregate types, callbacks, lifetimes, and safety limits |
| [Temporal Built-ins](docs/built-ins-temporal.md) | Temporal API: dates, times, durations, time zones |
| [Binary Data Built-ins](docs/built-ins-binary-data.md) | ArrayBuffer, SharedArrayBuffer, TypedArray API |
| [Async Context](docs/built-ins-async-context.md) | `node:async_hooks`: `AsyncLocalStorage`, `AsyncResource`, and what propagates |
| [Errors](docs/errors.md) | Error types, parser/runtime display, JSON output, `Error.cause`, `try`/`catch`/`finally` |
| [Architecture](docs/architecture.md) | Pipelines, main layers, design direction, duplication boundaries |
| [Interpreter](docs/interpreter.md) · [Bytecode VM](docs/bytecode-vm.md) | Tree-walk and bytecode execution modes |
Expand Down
173 changes: 173 additions & 0 deletions docs/adr/0112-native-async-local-storage.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
# Native AsyncLocalStorage over continuation snapshots

**Date:** 2026-08-20
**Area:** `runtime`

GocciaScript implements `node:async_hooks` natively — `AsyncLocalStorage` and
`AsyncResource` — and the engine, not the JavaScript layer, propagates the
async context. The propagation mechanism is general: one immutable snapshot per
continuation, holding the bindings of every `AsyncLocalStorage` instance at
once, rather than a per-instance stack.

## Why the engine has to do it

A userland shim cannot express these semantics, and the reason is structural
rather than a matter of effort. `storage.run(store, callback)` returns as soon
as an `async` callback reaches its first `await`. A shim's `finally` therefore
pops the store at that moment, and the resumed continuation — the part of the
callback that actually does the work — reads nothing. The context has to travel
with each continuation, and only the code that creates continuations can attach
it. The acceptance target is `convex-test`, which is built on three concurrent
`AsyncLocalStorage` instances; a mechanism that handles one instance, or that
handles `run` but not interleaving, does not run it.

Declining the feature was the alternative. It was rejected for the same reason:
`AsyncLocalStorage` is the last engine-level wall in front of npm-shaped test
suites, and there is no workaround a suite author can apply.

## The mechanism

A snapshot is an immutable association list from `AsyncLocalStorage` instance to
store. `run` derives a new snapshot from the current one, installs it, calls the
callback, and restores the previous snapshot when the callback's synchronous
part returns. Deriving copies the entries once, so every continuation that
already captured a snapshot keeps seeing exactly the bindings that were in
effect when it was created.

Two seams carry snapshots into continuations, and both sit in machinery the
interpreter and the bytecode VM share, so mode parity is structural rather than
maintained:

- **Registration** — a promise reaction records the current snapshot when it is
registered on a still-pending promise (`TGocciaPromiseReaction.Context` in
`Goccia.Values.PromiseValue`). Recording it at settlement instead would be
wrong: `run(store, () => pending.then(handler))` must reach `handler` with
the store even though whatever resolves `pending` runs outside the `run`.
- **Execution** — the microtask queue installs a job's snapshot before running
it and restores the previous one afterwards
(`TGocciaMicrotaskQueue.ExecuteTask` in `Goccia.MicrotaskQueue`). Every
enqueue path captures the current snapshot unless it passes one explicitly,
so no call site can forget.

`await` needs no seam of its own, but not because nothing suspends. An async
function does suspend at each `await` — `EGocciaAsyncAwaitSuspend` in the
interpreter, `EGocciaBytecodeAsyncSuspend` in the bytecode VM — and its
resumption is attached with `InvokeThen` on the awaited promise. That lands the
continuation on the registration seam above, which records the snapshot in
effect at the point of the `await`, so the resumed body sees exactly the
bindings the suspending frame had. What GocciaScript does not do is *park*:
the awaited promise is driven to settlement by draining the microtask queue on
the same Pascal stack, so the resumption is reached from inside the awaiting
call rather than from a later turn of an event loop. Either way the snapshot
travels with the reaction, not with the stack. The restore in the execution
seam is what additionally keeps a foreign continuation, drained by an unrelated
`await`, from leaking its bindings into the frame that drained it.

The current snapshot is a garbage-collection root through a `TGCRootSource`, and
queued snapshots are rooted with the microtask they belong to. `nil` is the
empty snapshot rather than a missing one, so a program that never touches
`AsyncLocalStorage` allocates nothing and pays one null check per enqueue.

## Availability

`node:async_hooks` is registered by the loader runtime profile, which means it
is present in `GocciaScriptLoader`, `GocciaTestRunner`, `GocciaREPL`, and
`GocciaBenchmarkRunner` without an opt-in. It carries no capability: no I/O, no
clock, no ambient authority, no way to observe anything the running program did
not already have. It is context bookkeeping over values the program itself
supplies, so gating it would add a switch that protects nothing. The address is
Node's own — there is no `goccia:` spelling — because the surface is Node's
rather than one GocciaScript invented.

## Semantics and scope

The implemented surface was probed against Node v24.0.1 rather than read off the
documentation, and matches it on every probe: `run`, `getStore`, `enterWith`,
`exit`, `disable`, the `defaultValue` and `name` constructor options, the
`AsyncLocalStorage.bind` and `AsyncLocalStorage.snapshot` statics, and
`AsyncResource` with `runInAsyncScope`, `bind` (instance and static), `asyncId`,
`triggerAsyncId`, and `emitDestroy`. Two behaviours are worth recording because
they are not obvious from the prose: `exit` binds `undefined` rather than
dropping the binding, so `getStore` inside it reports `undefined` even when the
instance has a `defaultValue`; and `disable` leaves the default value reachable,
so `getStore` reports it rather than `undefined`.

Deliberately out of scope:

- **Host-scheduled callbacks.** GocciaScript has no timer task queue and no
general event loop, so there is no `setTimeout` continuation for a context to
travel into. When a host-scheduled callback surface is added, its scheduling
point becomes a third seam; nothing about the snapshot representation has to
change for that.
- **The `async_hooks` observer API.** `createHook`, `executionAsyncId`,
`triggerAsyncId`, and the `init`/`before`/`after`/`destroy` callbacks are not
provided. They describe an async-resource lifecycle GocciaScript does not
have — awaits do not suspend, so there are no resources to report. The
per-resource ids `AsyncResource` exposes are unique and stable but relate to
nothing else, and `triggerAsyncId` reports the resource's own id.
- **Cross-realm propagation.** Snapshot state is thread-local, not
realm-local: a ShadowRealm child shares the thread's current snapshot rather
than getting one of its own. Nothing can observe that, because a child realm
has no way to import `node:async_hooks` and therefore no way to read or bind
a store. If a child ever gains access to the module, whether the state should
be partitioned per realm becomes a real question; today it is unobservable
rather than isolated.

`disable()` deletes the binding from the current frame and does nothing else,
matching Node v24's AsyncContextFrame model. Every observable consequence
follows from that one edit rather than from a rule of its own: `getStore()`
reports the default value afterwards because no binding is left in this frame;
a later `run` or `enterWith` re-binds; and a continuation captured *before* the
disable still reports the store it captured, because the disable never reached
that frame.

An earlier draft used a per-instance `disabled` flag instead. It reproduced the
first two consequences and got the third wrong in both directions, which is why
the model rather than the flag is the mechanism: the flag masked bindings in
already-captured continuations where Node keeps them, and it made `exit()` on a
disabled instance report the default value where Node reports `undefined`. Both
were probed against Node v24.0.1, along with the cases that agreed either way
(disable-then-getStore with a default value; disable followed by a re-binding
`run` straddling a pending continuation).

## Async generators

Each executor drives async generators through its own request queue
(`TGocciaAsyncGeneratorObjectValue` in `Goccia.Values.GeneratorValue`,
`TGocciaBytecodeAsyncGeneratorObjectValue` in `Goccia.VM`), and neither queue
records an async context of its own. That is deliberate and was checked rather
than assumed: every resumption reaches the generator body through a promise
reaction, which already carries the snapshot captured where it was registered,
so the body observes the context of whichever call resumed it — which is what
Node does.

Four shapes were probed against Node v24.0.1 and match in both executors: a
`for await` inside a `run`; a generator created under one store and resumed
with none; a generator started with no store and resumed inside a `run`; and
two overlapping `next()` calls from two different stores, where the second is
queued behind the first. `tests/built-ins/AsyncHooks/async-generators.js` locks
all four in, and the differential suite gates the first two against bun. The two
queues are duplicated machinery, so each carries a comment pointing at the
other.

## Consequences

Installing a snapshot has to go through a saved-context stack that the
collector marks, not through a Pascal local. The current-snapshot slot is a
snapshot's only root, so a scope that displaced one and held it in a local
across guest code let a collection inside that code free it, and the restore
then wrote a dangling pointer — `run` nested in `run` with a `Goccia.gc()` in
the inner callback crashed both executors. `EnterAsyncContext` /
`LeaveAsyncContext` in `Goccia.AsyncContext` push the displaced snapshot onto a
per-thread stack that the async-context root source also marks, and all three
scoped-installation sites use them. The token they exchange is the stack depth
at entry, so a frame restores to its own depth and cannot unwind past an
enclosing frame's entry.

A latent bytecode-VM bug had to be fixed to ship this. `OP_CALL_METHOD`
recognised `Function.prototype.bind` by the callee's *name*, so any own static
named `bind` on a function object was silently redirected into
`TGocciaBoundFunctionValue` — which is exactly what `AsyncLocalStorage.bind` and
`AsyncResource.bind` are. The check now matches the intrinsic by identity
(`nikFunctionBind`). The sibling `call` and `apply` fast paths carry the same
name-based hazard behind a narrower guard and are untouched here.
1 change: 1 addition & 0 deletions docs/adr/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,3 +121,4 @@ Durable architecture and implementation decisions for GocciaScript. New ADRs use
- [0109 — Engine-integrity faults are never guest-catchable](0109-engine-integrity-faults-are-uncatchable.md)
- [0110 — The growth gate collects before refusing, and store paths root their temporaries](0110-growth-gate-collects-before-refusing.md)
- [0111 — Opt-in node_modules resolution](0111-opt-in-node-modules-resolution.md)
- [0112 — Native AsyncLocalStorage over continuation snapshots](0112-native-async-local-storage.md)
106 changes: 106 additions & 0 deletions docs/built-ins-async-context.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
# Async Context

*The `node:async_hooks` surface: stores that travel with a continuation instead of with a call.*

## Executive Summary

- **Node's module, Node's address** — `import { AsyncLocalStorage, AsyncResource } from "node:async_hooks"`, with a default export carrying both, exactly as Node spells it.
- **The engine propagates the context** — a snapshot of every bound store is captured when a continuation is created and installed when it runs, so a store survives `await`, `.then`, `.catch`, and `.finally`.
- **Concurrent chains stay separate** — the snapshot holds all instances at once, so interleaved chains and several `AsyncLocalStorage` instances never see each other's stores.
- **Available everywhere the loader profile is** — it carries no capability, so there is no opt-in flag.
- **No observer API** — `createHook`, `executionAsyncId`, and the resource lifecycle callbacks are not provided; see [ADR 0112](adr/0112-native-async-local-storage.md).

## AsyncLocalStorage

```javascript
import { AsyncLocalStorage } from "node:async_hooks";

const requestContext = new AsyncLocalStorage();

const handle = async (request) =>
requestContext.run({ id: request.id }, async () => {
await loadUser();
// Still the same store, on the other side of the await.
return requestContext.getStore().id;
});
```

`new AsyncLocalStorage(options?)` accepts an options object with two members:

| Option | Effect |
|--------|--------|
| `defaultValue` | What `getStore()` reports when no store is bound. Defaults to `undefined`. |
| `name` | Read back through the `name` property. Defaults to the empty string. |

| Method | Behavior |
|--------|----------|
| `run(store, callback, ...args)` | Binds `store`, calls `callback(...args)`, and restores the previous binding when the synchronous part of `callback` returns. Returns the callback's result. Continuations created while it runs keep the store. Re-enables a disabled instance. |
| `getStore()` | The bound store, or the instance's `defaultValue` when nothing is bound. A store bound as `undefined` wins over the default value. |
| `enterWith(store)` | Binds `store` for the rest of the current execution and for continuations created from it. There is no scope to leave, so the binding lasts until whatever installed the surrounding context restores it. Re-enables a disabled instance. |
| `exit(callback, ...args)` | Calls `callback(...args)` with `undefined` bound — not with the default value — and restores the previous binding afterwards. |
| `disable()` | Deletes the binding from the current context. `getStore()` then reports the `defaultValue` until `run` or `enterWith` binds again. A continuation captured *before* the `disable` still carries the store it captured. |

| Static | Behavior |
|--------|----------|
| `AsyncLocalStorage.bind(fn)` | Returns `fn` pinned to the context current at the `bind` call. Throws `TypeError` at the `bind` call if `fn` is not callable. |
| `AsyncLocalStorage.snapshot()` | Returns `(fn, ...args) => fn(...args)`, run under the context current at the `snapshot` call. It has no callback to validate, so a non-callable is a `TypeError` at the runner's call instead. |

Every function these return is named `bound` and reports its target's `length`,
as Node's do.
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

## AsyncResource

An `AsyncResource` captures the async context once, at construction, and replays
it on demand. It is the mechanism a library uses to run a stored callback under
the context it was registered in.

```javascript
import { AsyncResource } from "node:async_hooks";

const resource = new AsyncResource("db-query");
const later = resource.bind(() => requestContext.getStore());
```

| Member | Behavior |
|--------|----------|
| `new AsyncResource(type, options?)` | Captures the current context. `type` and `options` are accepted and unused. |
| `runInAsyncScope(fn, thisArg, ...args)` | Calls `fn` under the captured context and returns its result. Unlike `bind`, an omitted `thisArg` means `this` is `undefined` rather than the call site's receiver. |
| `bind(fn, thisArg?)` | Returns `fn` pinned to the captured context. An undefined `thisArg` leaves the call site's own receiver in place, so a bound function installed as an object method still sees that object as `this`. Throws `TypeError` at the `bind` call if `fn` is not callable. |
| `AsyncResource.bind(fn, type?, thisArg?)` | Returns `fn` pinned to the context current at the `bind` call, with the same receiver and validation rules. |
| `asyncId()` / `triggerAsyncId()` | A number unique to the resource. Nothing else in the engine relates to it, and `triggerAsyncId` reports the resource's own id. |
| `emitDestroy()` | Returns the resource. There are no destroy hooks to emit to. |

## What propagates, and what does not

The context travels with every continuation the engine creates: `await`
resumptions, `.then` / `.catch` / `.finally` handlers, callbacks passed to
`queueMicrotask`, and promise reactions registered inside a scope but settled
outside it. A reaction records the context where it was *registered*, so

```javascript
storage.run("registered", () => pending.then(handler));
```

reaches `handler` with `"registered"` bound however `pending` is eventually
settled.

An async generator body observes the context of whichever call resumed it, in
both executors and as in Node — a `for await` inside a `run` sees that run's
store, and a generator resumed outside one sees no store.

It does not travel into host-scheduled callbacks, because there are none:
GocciaScript has no timer task queue and no general event loop, so there is no
`setTimeout` continuation for a context to reach. The `async_hooks` observer API
(`createHook`, `executionAsyncId`, and the `init` / `before` / `after` /
`destroy` callbacks) is not provided either — it describes an async-resource
lifecycle this engine does not have. [ADR
0112](adr/0112-native-async-local-storage.md) records both cuts and the
snapshot mechanism behind the propagation.

## Availability

`node:async_hooks` is installed by the loader runtime profile, so it resolves in
`GocciaScriptLoader`, `GocciaTestRunner`, `GocciaREPL`, and
`GocciaBenchmarkRunner` without a flag. It grants no capability — no I/O, no
clock, no ambient authority — so nothing about it is gated. `GocciaScriptLoaderBare`
attaches no runtime and therefore does not resolve it.
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
Loading
Loading