Add generated Node 24 fetch conformance

- Pin the supported fetch surface to an explicit Node and Undici profile.
- Generate deterministic WebIDL, AbortSignal, and stream differential campaigns.
- Match Node stream pull scheduling while preserving typed source identity.
This commit is contained in:
Chris Tate
2026-08-01 15:33:37 -05:00
parent 0d3c006c0d
commit 2d0bc2df0b
11 changed files with 1562 additions and 77 deletions
+1
View File
@@ -8,6 +8,7 @@
"build": "pnpm -r --filter \"./packages/*\" run build",
"build:fresh": "rm -rf packages/compiler/dist packages/cli/dist node_modules/.cache/scriptc-tsc && pnpm build",
"test": "vitest run",
"test:fetch-conformance": "vitest run tests/harness/fetch-conformance.test.ts",
"test:cache-identity": "node tests/harness/cache-identity.mjs",
"test:sandbox": "node scripts/sandbox-test.mjs",
"test:sandbox:image": "node scripts/sandbox-image.mjs",
@@ -0,0 +1,369 @@
/**
* The engine-free fetch/Web-platform compatibility contract.
*
* Keep this data-only: lowering, the shipped surface manifest, and the
* differential conformance generator all consume the same profile. A Node
* upgrade is deliberate because Node's bundled Undici version is observable
* in coercion, error, stream, and transport behavior.
*/
export type FetchCompatFacet =
| "argument-evaluation"
| "body-consumption"
| "callback-order"
| "callback-this"
| "error-shape"
| "identity"
| "liveness"
| "missing-arguments"
| "mutation"
| "promise-settlement"
| "property-read"
| "state-machine"
| "surplus-arguments"
| "transport"
| "webidl-conversion";
export interface FetchCompatEvidence {
/** Stable scenario id interpreted by the generated differential harness. */
generated?: string;
/** Fixture directory below tests/fixtures/fetch. */
fixture?: string;
}
export interface FetchCompatOperation {
id: string;
name: string;
kind: "constructor" | "function" | "method" | "property" | "static-method";
facets: readonly FetchCompatFacet[];
evidence: readonly FetchCompatEvidence[];
}
export interface FetchCompatOption {
id: string;
name: string;
conversion: string;
evidence: readonly FetchCompatEvidence[];
}
export interface FetchCompatProfile {
schemaVersion: 1;
target: {
node: string;
undici: string;
};
requestInit: readonly FetchCompatOption[];
members: {
responseReads: readonly string[];
responseCalls: readonly string[];
readableStreamReads: readonly string[];
readableStreamCalls: readonly string[];
};
operations: readonly FetchCompatOperation[];
}
const generated = (scenario: string): FetchCompatEvidence => ({ generated: scenario });
const fixture = (name: string): FetchCompatEvidence => ({ fixture: name });
export const NODE24_FETCH_COMPAT_PROFILE = {
schemaVersion: 1,
target: {
node: "24.15.0",
undici: "7.24.4",
},
requestInit: [
{
id: "stdlib.fetch.request-init.method",
name: "RequestInit.method",
conversion: "WebIDL ByteString after all call arguments evaluate",
evidence: [fixture("static-coercion")],
},
{
id: "stdlib.fetch.request-init.headers",
name: "RequestInit.headers",
conversion: "Headers, record, or sequence-of-pairs snapshot",
evidence: [fixture("static"), fixture("static-coercion")],
},
{
id: "stdlib.fetch.request-init.body",
name: "RequestInit.body",
conversion: "string, Uint8Array, ReadableStream, or null",
evidence: [fixture("static"), fixture("static-stream"), fixture("static-coercion")],
},
{
id: "stdlib.fetch.request-init.duplex",
name: "RequestInit.duplex",
conversion: "WebIDL enum; 'half' required for streaming bodies",
evidence: [fixture("static-stream"), fixture("static-coercion")],
},
{
id: "stdlib.fetch.request-init.redirect",
name: "RequestInit.redirect",
conversion: "WebIDL enum: follow, error, or manual",
evidence: [fixture("static"), fixture("static-coercion")],
},
{
id: "stdlib.fetch.request-init.signal",
name: "RequestInit.signal",
conversion: "native AbortSignal handle or absent",
evidence: [fixture("static"), fixture("static-abort-throw")],
},
],
members: {
responseReads: [
"ok",
"status",
"statusText",
"url",
"redirected",
"headers",
"body",
"bodyUsed",
],
responseCalls: ["json", "text", "bytes"],
readableStreamReads: ["locked"],
readableStreamCalls: ["cancel", "getReader"],
},
operations: [
{
id: "stdlib.fetch",
name: "fetch",
kind: "function",
facets: [
"argument-evaluation",
"webidl-conversion",
"surplus-arguments",
"promise-settlement",
"transport",
"error-shape",
],
evidence: [fixture("static"), fixture("static-coercion"), fixture("static-network-error")],
},
{
id: "stdlib.abort-signal.abort",
name: "AbortSignal.abort",
kind: "static-method",
facets: ["identity", "liveness", "surplus-arguments", "property-read"],
evidence: [generated("webidl-operations"), fixture("static-stream-this")],
},
{
id: "stdlib.abort-signal.any",
name: "AbortSignal.any",
kind: "static-method",
facets: ["webidl-conversion", "missing-arguments", "surplus-arguments", "property-read"],
evidence: [generated("webidl-operations"), fixture("static-stream-this")],
},
{
id: "stdlib.abort-signal.timeout",
name: "AbortSignal.timeout",
kind: "static-method",
facets: ["webidl-conversion", "missing-arguments", "surplus-arguments", "error-shape"],
evidence: [generated("webidl-operations"), fixture("static-stream-this")],
},
{
id: "stdlib.abort-signal.aborted",
name: "AbortSignal.aborted",
kind: "property",
facets: ["property-read"],
evidence: [generated("webidl-operations")],
},
{
id: "stdlib.abort-signal.reason",
name: "AbortSignal.reason",
kind: "property",
facets: ["identity", "liveness", "property-read"],
evidence: [generated("webidl-operations"), fixture("static-stream-this")],
},
{
id: "stdlib.abort-signal.onabort",
name: "AbortSignal.onabort",
kind: "property",
facets: ["callback-order", "callback-this", "mutation", "property-read"],
evidence: [generated("abort-events"), fixture("static-listener-this")],
},
{
id: "stdlib.abort-signal.throw-if-aborted",
name: "AbortSignal.throwIfAborted",
kind: "method",
facets: ["identity", "error-shape"],
evidence: [generated("webidl-operations"), fixture("static-abort-throw")],
},
{
id: "stdlib.abort-signal.add-event-listener",
name: "AbortSignal.addEventListener",
kind: "method",
facets: ["webidl-conversion", "identity", "callback-order", "callback-this"],
evidence: [generated("abort-events"), fixture("static-listener-this"), fixture("static-listener-noncallable")],
},
{
id: "stdlib.abort-signal.remove-event-listener",
name: "AbortSignal.removeEventListener",
kind: "method",
facets: ["webidl-conversion", "identity", "callback-order"],
evidence: [generated("abort-events"), fixture("static-stream-this")],
},
{
id: "stdlib.abort-signal.dispatch-event",
name: "AbortSignal.dispatchEvent",
kind: "method",
facets: ["callback-order", "callback-this", "error-shape"],
evidence: [fixture("static-dispatch-throw")],
},
{
id: "stdlib.readable-stream.constructor",
name: "ReadableStream constructor",
kind: "constructor",
facets: ["webidl-conversion", "callback-this", "callback-order", "state-machine"],
evidence: [generated("stream-traces"), fixture("static-stream-this")],
},
{
id: "stdlib.readable-stream.from",
name: "ReadableStream.from",
kind: "static-method",
facets: ["webidl-conversion", "missing-arguments", "surplus-arguments", "liveness"],
evidence: [generated("webidl-operations"), generated("stream-traces")],
},
{
id: "stdlib.readable-stream.locked",
name: "ReadableStream.locked",
kind: "property",
facets: ["property-read", "state-machine"],
evidence: [generated("stream-traces")],
},
{
id: "stdlib.readable-stream.cancel",
name: "ReadableStream.cancel",
kind: "method",
facets: ["identity", "promise-settlement", "state-machine"],
evidence: [generated("stream-traces"), fixture("static-stream")],
},
{
id: "stdlib.readable-stream.get-reader",
name: "ReadableStream.getReader",
kind: "method",
facets: ["webidl-conversion", "identity", "state-machine", "error-shape"],
evidence: [generated("stream-traces"), fixture("static-stream")],
},
{
id: "stdlib.readable-stream-default-reader.closed",
name: "ReadableStreamDefaultReader.closed",
kind: "property",
facets: ["promise-settlement", "property-read", "state-machine"],
evidence: [generated("stream-traces"), fixture("static-stream")],
},
{
id: "stdlib.readable-stream-default-reader.read",
name: "ReadableStreamDefaultReader.read",
kind: "method",
facets: ["identity", "promise-settlement", "state-machine"],
evidence: [generated("stream-traces"), fixture("static-stream")],
},
{
id: "stdlib.readable-stream-default-reader.cancel",
name: "ReadableStreamDefaultReader.cancel",
kind: "method",
facets: ["identity", "promise-settlement", "state-machine"],
evidence: [generated("stream-traces"), fixture("static-stream")],
},
{
id: "stdlib.readable-stream-default-reader.release-lock",
name: "ReadableStreamDefaultReader.releaseLock",
kind: "method",
facets: ["promise-settlement", "state-machine", "error-shape"],
evidence: [generated("stream-traces"), fixture("static-stream")],
},
{
id: "stdlib.readable-stream-default-controller.desired-size",
name: "ReadableStreamDefaultController.desiredSize",
kind: "property",
facets: ["property-read", "state-machine"],
evidence: [generated("stream-traces")],
},
{
id: "stdlib.readable-stream-default-controller.enqueue",
name: "ReadableStreamDefaultController.enqueue",
kind: "method",
facets: ["identity", "liveness", "state-machine", "error-shape"],
evidence: [generated("stream-traces"), fixture("static-stream")],
},
{
id: "stdlib.readable-stream-default-controller.close",
name: "ReadableStreamDefaultController.close",
kind: "method",
facets: ["state-machine", "error-shape"],
evidence: [generated("stream-traces"), fixture("static-stream")],
},
{
id: "stdlib.readable-stream-default-controller.error",
name: "ReadableStreamDefaultController.error",
kind: "method",
facets: ["identity", "promise-settlement", "state-machine"],
evidence: [generated("stream-traces"), fixture("static-stream")],
},
...[
"append",
"delete",
"get",
"getSetCookie",
"has",
"set",
"forEach",
].map((member): FetchCompatOperation => ({
id: `stdlib.headers.${member}`,
name: `Headers.${member}`,
kind: "method",
facets:
member === "forEach"
? ["callback-order", "callback-this", "mutation"]
: member === "get" || member === "has"
? ["webidl-conversion", "missing-arguments", "property-read"]
: ["webidl-conversion", "mutation", "error-shape"],
evidence: [fixture("static"), fixture("static-coercion")],
})),
...[
"ok",
"status",
"statusText",
"url",
"redirected",
"headers",
"body",
"bodyUsed",
].map((member): FetchCompatOperation => ({
id: `stdlib.response.${member}`,
name: `Response.${member}`,
kind: "property",
facets: ["property-read"],
evidence: [fixture("static")],
})),
...["json", "text", "bytes"].map((member): FetchCompatOperation => ({
id: `stdlib.response.${member}`,
name: `Response.${member}`,
kind: "method",
facets: ["body-consumption", "promise-settlement", "state-machine", "error-shape"],
evidence: [fixture("static"), fixture("static-stream")],
})),
],
} satisfies FetchCompatProfile;
export const STATIC_REQUEST_INIT_KEYS = new Set(
NODE24_FETCH_COMPAT_PROFILE.requestInit.map((entry) =>
entry.id.slice("stdlib.fetch.request-init.".length)
),
);
export const STATIC_RESPONSE_READS = new Set(
NODE24_FETCH_COMPAT_PROFILE.members.responseReads,
);
export const STATIC_RESPONSE_CALLS = new Set(
NODE24_FETCH_COMPAT_PROFILE.members.responseCalls,
);
export const STATIC_READABLE_STREAM_READS = new Set(
NODE24_FETCH_COMPAT_PROFILE.members.readableStreamReads,
);
export const STATIC_READABLE_STREAM_CALLS = new Set(
NODE24_FETCH_COMPAT_PROFILE.members.readableStreamCalls,
);
@@ -38,6 +38,7 @@
* byte-deterministic: entries sort by id, keys are emitted in one fixed
* order, and the output carries no timestamps or absolute paths. */
import { FENCE_CODES, UNSUPPORTED } from "../diagnostics/diagnostic.js";
import { NODE24_FETCH_COMPAT_PROFILE } from "../compat/fetch-profile.js";
import { SUPPORTED_BUILTIN_MODULES, SUPPORTED_NODE_MODULES } from "../frontend/shared.js";
import {
AMBIENT_SURFACE_FNS,
@@ -89,6 +90,7 @@ const COVERAGE_NOTES: string[] = [
"stdlib and node-builtin member entries name surface whose LOWERED call forms are constrained (arity, argument shapes); declared call forms outside the lowered set are refused per site, with code SC2020 for standard-library and node-builtin surface.",
"Entries with status 'unsupported' or 'dynamic-only' describe where the named code is raised: forms of the construct outside the supported subset are refused with that code — not that every form of the named feature is refused. Supported forms appear as their own static entries where a table projects them.",
"Entries with status 'dynamic-only' compile when the build embeds the dynamic engine (--dynamic); without the flag each use site is refused with the entry's code.",
`The engine-free fetch projection targets Node ${NODE24_FETCH_COMPAT_PROFILE.target.node} with bundled Undici ${NODE24_FETCH_COMPAT_PROFILE.target.undici}. Each projected row names the differential evidence that guards it; changing the pinned Node or Undici version is an explicit profile update.`,
"Process-level diagnostic codes are not surface entries: SC0001-SC0004 are preflight gates, SC1110 is a comptime evaluation failure, SC3001 is the alternate-backend tier refusal, SC9001/SC9002 are internal errors.",
"No scheduling metadata is published; entry ids are the stable diff keys across releases.",
];
@@ -309,6 +311,43 @@ export function generateSurfaceManifest(compilerVersion: string): SurfaceManifes
}
}
// ── fetch/Web platform: one explicit, versioned compatibility profile ─
const fetchTarget =
`Node ${NODE24_FETCH_COMPAT_PROFILE.target.node} / ` +
`Undici ${NODE24_FETCH_COMPAT_PROFILE.target.undici}`;
for (const operation of NODE24_FETCH_COMPAT_PROFILE.operations) {
const evidence = operation.evidence.map((item) =>
item.generated !== undefined
? `generated:${item.generated}`
: `fixture:${item.fixture!}`
);
add({
id: operation.id,
kind: "stdlib",
name: operation.name,
status: "static",
note:
`${fetchTarget}; facets: ${operation.facets.join(", ")}; ` +
`differential evidence: ${evidence.join(", ")}`,
});
}
for (const option of NODE24_FETCH_COMPAT_PROFILE.requestInit) {
const evidence = option.evidence.map((item) =>
item.generated !== undefined
? `generated:${item.generated}`
: `fixture:${item.fixture!}`
);
add({
id: option.id,
kind: "stdlib",
name: option.name,
status: "static",
note:
`${fetchTarget}; conversion: ${option.conversion}; ` +
`differential evidence: ${evidence.join(", ")}`,
});
}
// ── ambient dedicated-path surfaces: the attestation's ground ─────────
// Date/perf_hooks/process rows from the one ambient table — each entry
// is fenceable by construction (its row carries the reach-witnessing
@@ -10,6 +10,13 @@ import { requiresDynamicApiDiag, requiresDynamicPackageDiag } from "../../diagno
import { isCjsJsFile, isJsSourceFile, locOf, npmPackageNameOf } from "../program.js";
import { lowerDynObjectLiteral, pureReemittable } from "./lower-exprs.js";
import { PoisonError, dynUndefinedExpr, newFnCtx, own } from "./lowerer.js";
import {
STATIC_READABLE_STREAM_CALLS,
STATIC_READABLE_STREAM_READS,
STATIC_REQUEST_INIT_KEYS,
STATIC_RESPONSE_CALLS,
STATIC_RESPONSE_READS,
} from "../../compat/fetch-profile.js";
/** True iff the checker's type for this node maps to jsval ('any') —
* the island test in front of every engine-op lowering (receivers,
@@ -229,15 +236,6 @@ import { PoisonError, dynUndefinedExpr, newFnCtx, own } from "./lowerer.js";
return entry;
}
const STATIC_REQUEST_INIT_KEYS = new Set([
"method",
"headers",
"body",
"duplex",
"redirect",
"signal",
]);
function requestInitLiteralKey(
prop: ts.ObjectLiteralElementLike,
): string | null {
@@ -453,23 +451,6 @@ export function lowerStaticResponseCall(L: Lowerer, call: ts.CallExpression): Ir
};
}
const STATIC_RESPONSE_READS = new Set([
"ok",
"status",
"statusText",
"url",
"redirected",
"headers",
"body",
"bodyUsed",
]);
const STATIC_RESPONSE_CALLS = new Set(["json", "text", "bytes"]);
const STATIC_READABLE_STREAM_READS = new Set(["locked"]);
const STATIC_READABLE_STREAM_CALLS = new Set(["cancel", "getReader"]);
type StaticResponseAccess =
| ts.PropertyAccessExpression
| ts.ElementAccessExpression;
+8
View File
@@ -47,6 +47,14 @@ export {
type SurfaceManifest,
type SurfaceManifestEntry,
} from "./coverage/surface-manifest.js";
export {
NODE24_FETCH_COMPAT_PROFILE,
type FetchCompatEvidence,
type FetchCompatFacet,
type FetchCompatOperation,
type FetchCompatOption,
type FetchCompatProfile,
} from "./compat/fetch-profile.js";
export { LIB_FN_SIGS, validateModule } from "./ir/validate.js";
export { resolveLibraryFences, type LibraryFenceDecl, type ResolvedLibraryFence } from "./library/fence-eval.js";
export {
+337
View File
@@ -8,6 +8,7 @@
"stdlib and node-builtin member entries name surface whose LOWERED call forms are constrained (arity, argument shapes); declared call forms outside the lowered set are refused per site, with code SC2020 for standard-library and node-builtin surface.",
"Entries with status 'unsupported' or 'dynamic-only' describe where the named code is raised: forms of the construct outside the supported subset are refused with that code — not that every form of the named feature is refused. Supported forms appear as their own static entries where a table projects them.",
"Entries with status 'dynamic-only' compile when the build embeds the dynamic engine (--dynamic); without the flag each use site is refused with the entry's code.",
"The engine-free fetch projection targets Node 24.15.0 with bundled Undici 7.24.4. Each projected row names the differential evidence that guards it; changing the pinned Node or Undici version is an explicit profile update.",
"Process-level diagnostic codes are not surface entries: SC0001-SC0004 are preflight gates, SC1110 is a comptime evaluation failure, SC3001 is the alternate-backend tier refusal, SC9001/SC9002 are internal errors.",
"No scheduling metadata is published; entry ids are the stable diff keys across releases."
],
@@ -1864,6 +1865,76 @@
"code": "SC2020",
"note": "deflateSync and inflateSync are the lowered zlib surface"
},
{
"id": "stdlib.abort-signal.abort",
"kind": "stdlib",
"name": "AbortSignal.abort",
"status": "static",
"note": "Node 24.15.0 / Undici 7.24.4; facets: identity, liveness, surplus-arguments, property-read; differential evidence: generated:webidl-operations, fixture:static-stream-this"
},
{
"id": "stdlib.abort-signal.aborted",
"kind": "stdlib",
"name": "AbortSignal.aborted",
"status": "static",
"note": "Node 24.15.0 / Undici 7.24.4; facets: property-read; differential evidence: generated:webidl-operations"
},
{
"id": "stdlib.abort-signal.add-event-listener",
"kind": "stdlib",
"name": "AbortSignal.addEventListener",
"status": "static",
"note": "Node 24.15.0 / Undici 7.24.4; facets: webidl-conversion, identity, callback-order, callback-this; differential evidence: generated:abort-events, fixture:static-listener-this, fixture:static-listener-noncallable"
},
{
"id": "stdlib.abort-signal.any",
"kind": "stdlib",
"name": "AbortSignal.any",
"status": "static",
"note": "Node 24.15.0 / Undici 7.24.4; facets: webidl-conversion, missing-arguments, surplus-arguments, property-read; differential evidence: generated:webidl-operations, fixture:static-stream-this"
},
{
"id": "stdlib.abort-signal.dispatch-event",
"kind": "stdlib",
"name": "AbortSignal.dispatchEvent",
"status": "static",
"note": "Node 24.15.0 / Undici 7.24.4; facets: callback-order, callback-this, error-shape; differential evidence: fixture:static-dispatch-throw"
},
{
"id": "stdlib.abort-signal.onabort",
"kind": "stdlib",
"name": "AbortSignal.onabort",
"status": "static",
"note": "Node 24.15.0 / Undici 7.24.4; facets: callback-order, callback-this, mutation, property-read; differential evidence: generated:abort-events, fixture:static-listener-this"
},
{
"id": "stdlib.abort-signal.reason",
"kind": "stdlib",
"name": "AbortSignal.reason",
"status": "static",
"note": "Node 24.15.0 / Undici 7.24.4; facets: identity, liveness, property-read; differential evidence: generated:webidl-operations, fixture:static-stream-this"
},
{
"id": "stdlib.abort-signal.remove-event-listener",
"kind": "stdlib",
"name": "AbortSignal.removeEventListener",
"status": "static",
"note": "Node 24.15.0 / Undici 7.24.4; facets: webidl-conversion, identity, callback-order; differential evidence: generated:abort-events, fixture:static-stream-this"
},
{
"id": "stdlib.abort-signal.throw-if-aborted",
"kind": "stdlib",
"name": "AbortSignal.throwIfAborted",
"status": "static",
"note": "Node 24.15.0 / Undici 7.24.4; facets: identity, error-shape; differential evidence: generated:webidl-operations, fixture:static-abort-throw"
},
{
"id": "stdlib.abort-signal.timeout",
"kind": "stdlib",
"name": "AbortSignal.timeout",
"status": "static",
"note": "Node 24.15.0 / Undici 7.24.4; facets: webidl-conversion, missing-arguments, surplus-arguments, error-shape; differential evidence: generated:webidl-operations, fixture:static-stream-this"
},
{
"id": "stdlib.array.at",
"kind": "stdlib",
@@ -2036,6 +2107,104 @@
"status": "static",
"note": "the composed new Date(ms?).toISOString() form"
},
{
"id": "stdlib.fetch",
"kind": "stdlib",
"name": "fetch",
"status": "static",
"note": "Node 24.15.0 / Undici 7.24.4; facets: argument-evaluation, webidl-conversion, surplus-arguments, promise-settlement, transport, error-shape; differential evidence: fixture:static, fixture:static-coercion, fixture:static-network-error"
},
{
"id": "stdlib.fetch.request-init.body",
"kind": "stdlib",
"name": "RequestInit.body",
"status": "static",
"note": "Node 24.15.0 / Undici 7.24.4; conversion: string, Uint8Array, ReadableStream, or null; differential evidence: fixture:static, fixture:static-stream, fixture:static-coercion"
},
{
"id": "stdlib.fetch.request-init.duplex",
"kind": "stdlib",
"name": "RequestInit.duplex",
"status": "static",
"note": "Node 24.15.0 / Undici 7.24.4; conversion: WebIDL enum; 'half' required for streaming bodies; differential evidence: fixture:static-stream, fixture:static-coercion"
},
{
"id": "stdlib.fetch.request-init.headers",
"kind": "stdlib",
"name": "RequestInit.headers",
"status": "static",
"note": "Node 24.15.0 / Undici 7.24.4; conversion: Headers, record, or sequence-of-pairs snapshot; differential evidence: fixture:static, fixture:static-coercion"
},
{
"id": "stdlib.fetch.request-init.method",
"kind": "stdlib",
"name": "RequestInit.method",
"status": "static",
"note": "Node 24.15.0 / Undici 7.24.4; conversion: WebIDL ByteString after all call arguments evaluate; differential evidence: fixture:static-coercion"
},
{
"id": "stdlib.fetch.request-init.redirect",
"kind": "stdlib",
"name": "RequestInit.redirect",
"status": "static",
"note": "Node 24.15.0 / Undici 7.24.4; conversion: WebIDL enum: follow, error, or manual; differential evidence: fixture:static, fixture:static-coercion"
},
{
"id": "stdlib.fetch.request-init.signal",
"kind": "stdlib",
"name": "RequestInit.signal",
"status": "static",
"note": "Node 24.15.0 / Undici 7.24.4; conversion: native AbortSignal handle or absent; differential evidence: fixture:static, fixture:static-abort-throw"
},
{
"id": "stdlib.headers.append",
"kind": "stdlib",
"name": "Headers.append",
"status": "static",
"note": "Node 24.15.0 / Undici 7.24.4; facets: webidl-conversion, mutation, error-shape; differential evidence: fixture:static, fixture:static-coercion"
},
{
"id": "stdlib.headers.delete",
"kind": "stdlib",
"name": "Headers.delete",
"status": "static",
"note": "Node 24.15.0 / Undici 7.24.4; facets: webidl-conversion, mutation, error-shape; differential evidence: fixture:static, fixture:static-coercion"
},
{
"id": "stdlib.headers.forEach",
"kind": "stdlib",
"name": "Headers.forEach",
"status": "static",
"note": "Node 24.15.0 / Undici 7.24.4; facets: callback-order, callback-this, mutation; differential evidence: fixture:static, fixture:static-coercion"
},
{
"id": "stdlib.headers.get",
"kind": "stdlib",
"name": "Headers.get",
"status": "static",
"note": "Node 24.15.0 / Undici 7.24.4; facets: webidl-conversion, missing-arguments, property-read; differential evidence: fixture:static, fixture:static-coercion"
},
{
"id": "stdlib.headers.getSetCookie",
"kind": "stdlib",
"name": "Headers.getSetCookie",
"status": "static",
"note": "Node 24.15.0 / Undici 7.24.4; facets: webidl-conversion, mutation, error-shape; differential evidence: fixture:static, fixture:static-coercion"
},
{
"id": "stdlib.headers.has",
"kind": "stdlib",
"name": "Headers.has",
"status": "static",
"note": "Node 24.15.0 / Undici 7.24.4; facets: webidl-conversion, missing-arguments, property-read; differential evidence: fixture:static, fixture:static-coercion"
},
{
"id": "stdlib.headers.set",
"kind": "stdlib",
"name": "Headers.set",
"status": "static",
"note": "Node 24.15.0 / Undici 7.24.4; facets: webidl-conversion, mutation, error-shape; differential evidence: fixture:static, fixture:static-coercion"
},
{
"id": "stdlib.map.clear",
"kind": "stdlib",
@@ -2275,6 +2444,174 @@
"status": "dynamic-only",
"code": "SC2012"
},
{
"id": "stdlib.readable-stream-default-controller.close",
"kind": "stdlib",
"name": "ReadableStreamDefaultController.close",
"status": "static",
"note": "Node 24.15.0 / Undici 7.24.4; facets: state-machine, error-shape; differential evidence: generated:stream-traces, fixture:static-stream"
},
{
"id": "stdlib.readable-stream-default-controller.desired-size",
"kind": "stdlib",
"name": "ReadableStreamDefaultController.desiredSize",
"status": "static",
"note": "Node 24.15.0 / Undici 7.24.4; facets: property-read, state-machine; differential evidence: generated:stream-traces"
},
{
"id": "stdlib.readable-stream-default-controller.enqueue",
"kind": "stdlib",
"name": "ReadableStreamDefaultController.enqueue",
"status": "static",
"note": "Node 24.15.0 / Undici 7.24.4; facets: identity, liveness, state-machine, error-shape; differential evidence: generated:stream-traces, fixture:static-stream"
},
{
"id": "stdlib.readable-stream-default-controller.error",
"kind": "stdlib",
"name": "ReadableStreamDefaultController.error",
"status": "static",
"note": "Node 24.15.0 / Undici 7.24.4; facets: identity, promise-settlement, state-machine; differential evidence: generated:stream-traces, fixture:static-stream"
},
{
"id": "stdlib.readable-stream-default-reader.cancel",
"kind": "stdlib",
"name": "ReadableStreamDefaultReader.cancel",
"status": "static",
"note": "Node 24.15.0 / Undici 7.24.4; facets: identity, promise-settlement, state-machine; differential evidence: generated:stream-traces, fixture:static-stream"
},
{
"id": "stdlib.readable-stream-default-reader.closed",
"kind": "stdlib",
"name": "ReadableStreamDefaultReader.closed",
"status": "static",
"note": "Node 24.15.0 / Undici 7.24.4; facets: promise-settlement, property-read, state-machine; differential evidence: generated:stream-traces, fixture:static-stream"
},
{
"id": "stdlib.readable-stream-default-reader.read",
"kind": "stdlib",
"name": "ReadableStreamDefaultReader.read",
"status": "static",
"note": "Node 24.15.0 / Undici 7.24.4; facets: identity, promise-settlement, state-machine; differential evidence: generated:stream-traces, fixture:static-stream"
},
{
"id": "stdlib.readable-stream-default-reader.release-lock",
"kind": "stdlib",
"name": "ReadableStreamDefaultReader.releaseLock",
"status": "static",
"note": "Node 24.15.0 / Undici 7.24.4; facets: promise-settlement, state-machine, error-shape; differential evidence: generated:stream-traces, fixture:static-stream"
},
{
"id": "stdlib.readable-stream.cancel",
"kind": "stdlib",
"name": "ReadableStream.cancel",
"status": "static",
"note": "Node 24.15.0 / Undici 7.24.4; facets: identity, promise-settlement, state-machine; differential evidence: generated:stream-traces, fixture:static-stream"
},
{
"id": "stdlib.readable-stream.constructor",
"kind": "stdlib",
"name": "ReadableStream constructor",
"status": "static",
"note": "Node 24.15.0 / Undici 7.24.4; facets: webidl-conversion, callback-this, callback-order, state-machine; differential evidence: generated:stream-traces, fixture:static-stream-this"
},
{
"id": "stdlib.readable-stream.from",
"kind": "stdlib",
"name": "ReadableStream.from",
"status": "static",
"note": "Node 24.15.0 / Undici 7.24.4; facets: webidl-conversion, missing-arguments, surplus-arguments, liveness; differential evidence: generated:webidl-operations, generated:stream-traces"
},
{
"id": "stdlib.readable-stream.get-reader",
"kind": "stdlib",
"name": "ReadableStream.getReader",
"status": "static",
"note": "Node 24.15.0 / Undici 7.24.4; facets: webidl-conversion, identity, state-machine, error-shape; differential evidence: generated:stream-traces, fixture:static-stream"
},
{
"id": "stdlib.readable-stream.locked",
"kind": "stdlib",
"name": "ReadableStream.locked",
"status": "static",
"note": "Node 24.15.0 / Undici 7.24.4; facets: property-read, state-machine; differential evidence: generated:stream-traces"
},
{
"id": "stdlib.response.body",
"kind": "stdlib",
"name": "Response.body",
"status": "static",
"note": "Node 24.15.0 / Undici 7.24.4; facets: property-read; differential evidence: fixture:static"
},
{
"id": "stdlib.response.bodyUsed",
"kind": "stdlib",
"name": "Response.bodyUsed",
"status": "static",
"note": "Node 24.15.0 / Undici 7.24.4; facets: property-read; differential evidence: fixture:static"
},
{
"id": "stdlib.response.bytes",
"kind": "stdlib",
"name": "Response.bytes",
"status": "static",
"note": "Node 24.15.0 / Undici 7.24.4; facets: body-consumption, promise-settlement, state-machine, error-shape; differential evidence: fixture:static, fixture:static-stream"
},
{
"id": "stdlib.response.headers",
"kind": "stdlib",
"name": "Response.headers",
"status": "static",
"note": "Node 24.15.0 / Undici 7.24.4; facets: property-read; differential evidence: fixture:static"
},
{
"id": "stdlib.response.json",
"kind": "stdlib",
"name": "Response.json",
"status": "static",
"note": "Node 24.15.0 / Undici 7.24.4; facets: body-consumption, promise-settlement, state-machine, error-shape; differential evidence: fixture:static, fixture:static-stream"
},
{
"id": "stdlib.response.ok",
"kind": "stdlib",
"name": "Response.ok",
"status": "static",
"note": "Node 24.15.0 / Undici 7.24.4; facets: property-read; differential evidence: fixture:static"
},
{
"id": "stdlib.response.redirected",
"kind": "stdlib",
"name": "Response.redirected",
"status": "static",
"note": "Node 24.15.0 / Undici 7.24.4; facets: property-read; differential evidence: fixture:static"
},
{
"id": "stdlib.response.status",
"kind": "stdlib",
"name": "Response.status",
"status": "static",
"note": "Node 24.15.0 / Undici 7.24.4; facets: property-read; differential evidence: fixture:static"
},
{
"id": "stdlib.response.statusText",
"kind": "stdlib",
"name": "Response.statusText",
"status": "static",
"note": "Node 24.15.0 / Undici 7.24.4; facets: property-read; differential evidence: fixture:static"
},
{
"id": "stdlib.response.text",
"kind": "stdlib",
"name": "Response.text",
"status": "static",
"note": "Node 24.15.0 / Undici 7.24.4; facets: body-consumption, promise-settlement, state-machine, error-shape; differential evidence: fixture:static, fixture:static-stream"
},
{
"id": "stdlib.response.url",
"kind": "stdlib",
"name": "Response.url",
"status": "static",
"note": "Node 24.15.0 / Undici 7.24.4; facets: property-read; differential evidence: fixture:static"
},
{
"id": "stdlib.set.add",
"kind": "stdlib",
+73 -51
View File
@@ -1681,11 +1681,13 @@ static void sf_stream_enqueue_value(SfStream *s, ScrDyn *value) {
if (value->kind == SCR_DYN_TYPED_REF) {
for (SfTypedRef **at = &s->typed_refs; *at;) {
SfTypedRef *ref = *at;
/* The cache's own reference is no longer observable. Drop it before
* comparing the next value so a consume-and-discard stream retains
* only its live queue/reader window instead of every value ever
* seen. A retained reader result keeps rc > 1 and remains canonical. */
if (ref->value->rc == 1) {
/* A typed ReadableStream.from(array) retains the source array for the
* stream's lifetime, so a source object can recur after an arbitrary
* number of pulls and must still denote the same JS object. Keep its
* capsule as long as that source is live. Callback-fed streams have no
* such bounded owner; drop an otherwise-unobserved capsule there so a
* long-running producer does not retain every object it ever emitted. */
if (!s->from_array && ref->value->rc == 1) {
*at = ref->next;
scr_dyn_release(ref->value);
free(ref);
@@ -2052,6 +2054,35 @@ static void sf_stream_schedule_initial_pull(SfStream *s) {
scr_queue_microtask(cb);
}
/* Web Streams wraps an underlying source's plain pull return in a resolved
* promise. Its fulfillment step therefore runs as a promise job, never in
* the pull callback's stack. In particular, enqueueing into a pending read
* wakes that read's awaiter before a desiredSize-driven repull: the awaiter
* can cancel or release the reader first. Keep pulling=true through this
* microtask so demand raised by enqueue/read records pull_again exactly as
* it does while awaiting a genuinely asynchronous pull result. */
static void sf_stream_pull_complete_task(ScrClosure *cb) {
SfStream *s = (SfStream *)scr_box_get_ref(cb->caps[0]);
if (!s) return;
s->pulling = false;
bool again = s->pull_again;
s->pull_again = false;
if (again && !s->close_requested && !s->closed && !s->error) {
sf_stream_pull(s);
}
sf_stream_release(s);
}
static void sf_stream_schedule_pull_complete(SfStream *s) {
ScrClosure *cb =
scr_closure_new((void *)&sf_stream_pull_complete_task, 1);
ScrBox *box =
scr_box_new_obj(&sf_stream_retain_v, &sf_stream_release_v, NULL);
scr_box_set_ref(box, sf_stream_retain(s));
cb->caps[0] = box;
scr_queue_microtask(cb);
}
static void sf_stream_pull(SfStream *s) {
if (!s->started ||
(!s->pull_cb && !sf_stream_has_from_source(s)) ||
@@ -2064,54 +2095,45 @@ static void sf_stream_pull(SfStream *s) {
return;
}
if (sf_stream_has_from_source(s)) {
for (;;) {
s->pulling = true;
sf_stream_pull_from_source(s);
s->pulling = false;
bool again = s->pull_again;
s->pull_again = false;
if (!again || s->close_requested || s->closed || s->error) return;
}
}
for (;;) {
s->pulling = true;
ScrDyn *controller = sf_controller_box(s);
ScrDyn *args[1] = {controller};
ScrDyn *pull_cb = scr_dyn_retain(s->pull_cb);
scr_dyn_this_push_dyn(s->source_this);
ScrDyn *r =
scr_dyn_call(pull_cb, args, 1, "underlyingSource.pull");
scr_dyn_this_pop();
scr_dyn_release(pull_cb);
scr_dyn_release(controller);
if (!r) {
s->pulling = false;
s->pull_again = false;
ScrCaught *caught = scr_exc_take();
ScrDyn *reason = scr_caught_to_dyn(caught);
sf_stream_error(s, reason);
scr_dyn_release(reason);
scr_caught_release(caught);
return;
}
ScrPromise *callback_promise = sf_stream_callback_promise(r);
if (callback_promise) {
SfPullWait *wait = malloc(sizeof *wait);
if (!wait) sf_oom();
wait->stream = sf_stream_retain(s);
wait->promise = callback_promise;
ScrPromise *watcher =
scr_async_spawn(&sf_stream_pull_wait_entry, wait);
scr_promise_release(watcher);
scr_dyn_release(r);
return;
}
scr_dyn_release(r);
s->pulling = false;
bool again = s->pull_again;
s->pull_again = false;
if (!again || s->close_requested || s->closed || s->error) return;
sf_stream_pull_from_source(s);
sf_stream_schedule_pull_complete(s);
return;
}
s->pulling = true;
ScrDyn *controller = sf_controller_box(s);
ScrDyn *args[1] = {controller};
ScrDyn *pull_cb = scr_dyn_retain(s->pull_cb);
scr_dyn_this_push_dyn(s->source_this);
ScrDyn *r =
scr_dyn_call(pull_cb, args, 1, "underlyingSource.pull");
scr_dyn_this_pop();
scr_dyn_release(pull_cb);
scr_dyn_release(controller);
if (!r) {
s->pulling = false;
s->pull_again = false;
ScrCaught *caught = scr_exc_take();
ScrDyn *reason = scr_caught_to_dyn(caught);
sf_stream_error(s, reason);
scr_dyn_release(reason);
scr_caught_release(caught);
return;
}
ScrPromise *callback_promise = sf_stream_callback_promise(r);
if (callback_promise) {
SfPullWait *wait = malloc(sizeof *wait);
if (!wait) sf_oom();
wait->stream = sf_stream_retain(s);
wait->promise = callback_promise;
ScrPromise *watcher =
scr_async_spawn(&sf_stream_pull_wait_entry, wait);
scr_promise_release(watcher);
scr_dyn_release(r);
return;
}
scr_dyn_release(r);
sf_stream_schedule_pull_complete(s);
}
static SfReader *sf_stream_get_reader(SfStream *s) {
+27
View File
@@ -16,6 +16,33 @@ A fifth lane covers LIBRARY MODE across targets: `SCRIPTC_CROSS=1 pnpm exec vite
Iterate filtered, gate full: while developing, run just what you're touching (`pnpm exec vitest run tests/harness/differential.test.ts -t <name>` or a single test file); run the full lanes (`pnpm test`, then `SCRIPTC_SAN=1 pnpm test`) as the gate before committing.
### Fetch compatibility profile
The engine-free fetch/Web Streams slice has one versioned source of truth in
`packages/compiler/src/compat/fetch-profile.ts`. It pins the exact Node and
bundled Undici oracle, drives the lowering allowlists, projects every supported
operation into `packages/compiler/surface-manifest.json`, and names the
differential evidence for each operation and `RequestInit` member. A new row
without a real fixture or registered generated scenario fails the profile
suite.
`pnpm test:fetch-conformance` generates a program from that profile and runs it
under the pinned Node plus both native backends. The default seed exercises
WebIDL argument conversion/order, AbortSignal events, and twelve valid
ReadableStream state-machine traces. Reproduce or widen a campaign with:
```bash
SCRIPTC_FETCH_CONFORMANCE_SEED=12345 \
SCRIPTC_FETCH_CONFORMANCE_TRACES=50 \
pnpm test:fetch-conformance
```
When Node changes, update `.node-version` and the profile's Node/Undici tuple
together, regenerate with `pnpm manifest`, then run the focused plain and
sanitized conformance lanes before the full sandbox gate. When the static fetch
surface changes, update the profile first; its evidence check makes the missing
fixture or generated scenario the implementation worklist.
Full-suite runs (`vitest run` with no filters) take an advisory machine-wide lock (a pidfile in the OS temp dir) so concurrent full suites — typically parallel agents — queue instead of oversubscribing the CPU, which is a known flake source (vitest worker RPC timeouts, event-loop timing failures). The lock is per flavor (plain vs `SCRIPTC_SAN=1`): the two lanes read the same committed tree through separate cache directories, so a merge gate may deliberately run one of each concurrently — split the cores between them with `SCRIPTC_TEST_WORKERS` (e.g. 5 and 5) or the oversubscription flakes come back. Two runs of the SAME flavor still queue. Filtered and watch runs never wait. `SCRIPTC_NO_LOCK=1` opts out; stale locks from dead processes are stolen automatically. `SCRIPTC_TEST_WORKERS=<n>` caps the vitest worker pool (default: unchanged, all cores).
## Build and oracle caches
+441
View File
@@ -0,0 +1,441 @@
import type { FetchCompatProfile } from "../../packages/compiler/src/compat/fetch-profile.js";
export const FETCH_CONFORMANCE_SEED = 0x24_15_07_24;
export const FETCH_CONFORMANCE_SCENARIOS = [
"abort-events",
"stream-traces",
"webidl-operations",
] as const;
type GeneratedScenario = (typeof FETCH_CONFORMANCE_SCENARIOS)[number];
class XorShift32 {
constructor(private state: number) {
if (state === 0) this.state = 0x9e3779b9;
}
next(): number {
let value = this.state | 0;
value ^= value << 13;
value ^= value >>> 17;
value ^= value << 5;
this.state = value | 0;
return value >>> 0;
}
pick(size: number): number {
return this.next() % size;
}
}
function webIdlOperations(): string {
return String.raw`
let webIdlEffects = "";
function webIdlEffect(label) {
webIdlEffects += label;
return "ignored";
}
const abortReason = JSON.parse('{"value":"before"}');
const abortedSignal = AbortSignal.abort(
abortReason,
webIdlEffect("abort "),
);
abortReason.value = "after";
console.log(
"webidl abort:",
webIdlEffects,
abortedSignal.aborted,
abortedSignal.reason.value,
);
const combinedSignal = AbortSignal.any(
[abortedSignal],
webIdlEffect("any "),
);
console.log(
"webidl any:",
webIdlEffects,
combinedSignal.aborted,
combinedSignal.reason.value,
);
try {
combinedSignal.throwIfAborted();
console.log("webidl throwIfAborted: no-error");
} catch (error) {
console.log(
"webidl throwIfAborted:",
error.value,
);
}
webIdlEffects = "";
try {
AbortSignal.timeout(
JSON.parse('{"delay":1}'),
webIdlEffect("timeout-surplus"),
);
console.log("webidl invalid timeout: no-error");
} catch (error) {
console.log(
"webidl invalid timeout:",
webIdlEffects,
error.name,
error.code || "no-code",
error.message,
);
}
try {
AbortSignal.timeout();
console.log("webidl missing timeout: no-error");
} catch (error) {
console.log(
"webidl missing timeout:",
error.name,
error.code || "no-code",
error.message,
);
}
try {
AbortSignal.any();
console.log("webidl missing any: no-error");
} catch (error) {
console.log(
"webidl missing any:",
error.name,
error.code || "no-code",
error.message,
);
}
try {
AbortSignal.any(JSON.parse('{"not":"a sequence"}'));
console.log("webidl invalid any: no-error");
} catch (error) {
console.log(
"webidl invalid any:",
error.name,
error.code || "no-code",
error.message,
);
}
try {
ReadableStream.from();
console.log("webidl missing from: no-error");
} catch (error) {
console.log(
"webidl missing from:",
error.name,
error.code || "no-code",
error.message,
);
}
const fromItem = { value: "before" };
const fromItems = [fromItem];
webIdlEffects = "";
const fromStream = ReadableStream.from(
fromItems,
webIdlEffect("from-surplus"),
);
fromItems[0].value = "after";
const fromReader = fromStream.getReader();
const fromPart = await fromReader.read();
const fromDone = await fromReader.read();
console.log(
"webidl from:",
webIdlEffects,
fromPart.done,
fromPart.done ? "done" : fromPart.value.value,
fromDone.done,
fromStream.locked,
);
await fromReader.closed;
`;
}
function abortEvents(): string {
return String.raw`
let abortEventOrder = "";
let abortEventNameEffects = "";
const eventSignal = AbortSignal.timeout(0);
function abortEventNameToString() {
abortEventNameEffects += this.operation;
return "abort";
}
function keptAbortListener(event) {
abortEventOrder +=
this === eventSignal &&
event.target === eventSignal &&
event.currentTarget === eventSignal
? "listener-this "
: "listener-wrong ";
}
function removedAbortListener() {
abortEventOrder += "removed ";
}
function onAbortListener(event) {
abortEventOrder +=
this === eventSignal && event.target === eventSignal
? "onabort-this"
: "onabort-wrong";
}
eventSignal.addEventListener(
{ operation: "add ", toString: abortEventNameToString },
keptAbortListener,
);
eventSignal.addEventListener("abort", removedAbortListener);
eventSignal.removeEventListener(
{ operation: "remove", toString: abortEventNameToString },
removedAbortListener,
);
eventSignal.onabort = onAbortListener;
console.log("abort events before:", eventSignal.aborted);
await new Promise((resolve) => setTimeout(resolve, 5));
console.log(
"abort events after:",
abortEventNameEffects,
abortEventOrder,
eventSignal.aborted,
);
`;
}
interface TraceState {
locked: boolean;
reader: string;
readerSerial: number;
reads: number;
terminal: boolean;
}
function acquireReader(lines: string[], trace: number, state: TraceState): void {
state.readerSerial++;
state.reader = `trace${trace}Reader${state.readerSerial}`;
lines.push(`const ${state.reader} = trace${trace}Stream.getReader();`);
lines.push(
`console.log("trace ${trace} acquire ${state.readerSerial}:", trace${trace}Stream.locked);`,
);
state.locked = true;
}
function readOnce(lines: string[], trace: number, state: TraceState): void {
const part = `trace${trace}Part${state.reads}`;
lines.push(`const ${part} = await ${state.reader}.read();`);
lines.push(
`console.log("trace ${trace} read ${state.reads}:", ${part}.done, ${part}.done ? "done" : ${part}.value);`,
);
state.reads++;
}
function releaseReader(lines: string[], trace: number, state: TraceState): void {
lines.push(`${state.reader}.releaseLock();`);
lines.push(
`console.log("trace ${trace} release ${state.readerSerial}:", trace${trace}Stream.locked);`,
);
state.locked = false;
}
function oneStreamTrace(rng: XorShift32, trace: number): string {
const startChunk = rng.pick(2) === 0;
const chunks = 2 + rng.pick(3);
const pullChunks = chunks - (startChunk ? 1 : 0);
const lines: string[] = [
`let trace${trace}Pulls = 0;`,
`let trace${trace}Cancel = "none";`,
`function trace${trace}Start(controller) {`,
` console.log("trace ${trace} start:", this.marker, controller.desiredSize);`,
...(startChunk
? [
` controller.enqueue("trace-${trace}-start");`,
` console.log("trace ${trace} start enqueue:", controller.desiredSize);`,
]
: []),
`}`,
`function trace${trace}Pull(controller) {`,
` trace${trace}Pulls++;`,
` console.log("trace ${trace} pull:", this.marker, trace${trace}Pulls, controller.desiredSize);`,
` if (trace${trace}Pulls <= ${pullChunks}) {`,
` controller.enqueue("trace-${trace}-pull-" + trace${trace}Pulls);`,
` }`,
` if (trace${trace}Pulls === ${pullChunks}) controller.close();`,
`}`,
`function trace${trace}CancelFn(reason) {`,
` trace${trace}Cancel = reason;`,
` console.log("trace ${trace} cancel callback:", this.marker, reason);`,
`}`,
`const trace${trace}Source = {`,
` marker: "source-${trace}",`,
` start: trace${trace}Start,`,
` pull: trace${trace}Pull,`,
` cancel: trace${trace}CancelFn,`,
`};`,
`const trace${trace}Stream = new ReadableStream(trace${trace}Source);`,
];
const state: TraceState = {
locked: false,
reader: "",
readerSerial: 0,
reads: 0,
terminal: false,
};
acquireReader(lines, trace, state);
readOnce(lines, trace, state);
// Each residue class forces one important transition; the remaining
// steps are seeded model choices. This keeps coverage stable while still
// exploring different valid traces when the seed or count changes.
if (trace % 4 === 1) {
releaseReader(lines, trace, state);
acquireReader(lines, trace, state);
} else if (trace % 4 === 2) {
lines.push(`await ${state.reader}.cancel("reader-cancel-${trace}");`);
lines.push(`console.log("trace ${trace} reader cancel:", trace${trace}Stream.locked);`);
state.terminal = true;
} else if (trace % 4 === 3) {
releaseReader(lines, trace, state);
lines.push(`await trace${trace}Stream.cancel("stream-cancel-${trace}");`);
lines.push(`console.log("trace ${trace} stream cancel:", trace${trace}Stream.locked);`);
state.terminal = true;
}
const randomSteps = 2 + rng.pick(5);
for (let step = 0; step < randomSteps && !state.terminal; step++) {
if (!state.locked) {
if (rng.pick(3) === 0) {
lines.push(`await trace${trace}Stream.cancel("random-cancel-${trace}-${step}");`);
lines.push(`console.log("trace ${trace} random stream cancel ${step}:", trace${trace}Stream.locked);`);
state.terminal = true;
} else {
acquireReader(lines, trace, state);
}
continue;
}
switch (rng.pick(4)) {
case 0:
case 1:
readOnce(lines, trace, state);
if (state.reads >= chunks) state.terminal = true;
break;
case 2:
releaseReader(lines, trace, state);
break;
default:
lines.push(`await ${state.reader}.cancel("random-reader-cancel-${trace}-${step}");`);
lines.push(`console.log("trace ${trace} random reader cancel ${step}:", trace${trace}Stream.locked);`);
state.terminal = true;
break;
}
}
if (!state.locked) acquireReader(lines, trace, state);
if (!state.terminal) {
while (state.reads <= chunks) readOnce(lines, trace, state);
} else {
readOnce(lines, trace, state);
}
lines.push(`await ${state.reader}.closed;`);
lines.push(
`console.log("trace ${trace} final:", trace${trace}Pulls, trace${trace}Cancel, trace${trace}Stream.locked);`,
);
return lines.join("\n");
}
function streamTraces(seed: number, traceCount: number): string {
const rng = new XorShift32(seed);
const traces: string[] = [];
for (let trace = 0; trace < traceCount; trace++) {
traces.push(`{\n${oneStreamTrace(rng, trace)}\n}`);
}
traces.push(String.raw`
{
const streamErrorReason = { marker: "stream-error" };
const erroredStream = new ReadableStream({
start(controller) {
console.log("stream error desired size:", controller.desiredSize);
controller.error(streamErrorReason);
console.log("stream error after:", controller.desiredSize);
},
});
const erroredReader = erroredStream.getReader();
try {
await erroredReader.read();
console.log("stream error read: no-error");
} catch (error) {
console.log("stream error read:", error.marker);
}
try {
await erroredReader.closed;
console.log("stream error closed: no-error");
} catch (error) {
console.log("stream error closed:", error.marker);
}
}
try {
new ReadableStream({
start(controller) {
controller.close();
controller.close();
},
});
console.log("stream double close: no-error");
} catch (error) {
console.log("stream double close:", error.name, error.message);
}
`);
return traces.join("\n");
}
const SCENARIO_GENERATORS: Record<
GeneratedScenario,
(seed: number, traceCount: number) => string
> = {
"abort-events": () => abortEvents(),
"stream-traces": (seed, traceCount) => streamTraces(seed, traceCount),
"webidl-operations": () => webIdlOperations(),
};
export function generatedScenarioIds(profile: FetchCompatProfile): string[] {
return [...new Set(
profile.operations.flatMap((operation) =>
operation.evidence.flatMap((item) =>
item.generated === undefined ? [] : [item.generated]
)
),
)].sort();
}
export function generateFetchConformanceProgram(
profile: FetchCompatProfile,
options: { seed?: number; traceCount?: number } = {},
): string {
const seed = options.seed ?? FETCH_CONFORMANCE_SEED;
const traceCount = options.traceCount ?? 12;
const scenarios = generatedScenarioIds(profile);
const sections: string[] = [
`// Generated from NODE24_FETCH_COMPAT_PROFILE. Seed: 0x${seed.toString(16)}.`,
];
for (const scenario of scenarios) {
if (!Object.hasOwn(SCENARIO_GENERATORS, scenario)) {
throw new Error(`unknown generated fetch conformance scenario: ${scenario}`);
}
sections.push(`// scenario: ${scenario}`);
sections.push(
SCENARIO_GENERATORS[scenario as GeneratedScenario](seed, traceCount),
);
}
sections.push("export {};", "");
return sections.join("\n");
}
+259
View File
@@ -0,0 +1,259 @@
/**
* Generated, version-pinned conformance for the engine-free fetch slice.
*
* The compatibility profile is compiler input, not test-only metadata: its
* member allowlists drive lowering and its entries project into the shipped
* surface manifest. This suite checks that the pinned Node executable is the
* intended oracle, every profile row names differential evidence, and the
* generated WebIDL/state-machine program agrees through both native backends.
*/
import { execFile } from "node:child_process";
import { createHash } from "node:crypto";
import {
existsSync,
mkdirSync,
mkdtempSync,
readFileSync,
writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { promisify } from "node:util";
import { beforeAll, describe, expect, test } from "vitest";
import {
compile,
NODE24_FETCH_COMPAT_PROFILE,
renderAll,
type FetchCompatEvidence,
} from "@scriptc/compiler";
import {
FETCH_CONFORMANCE_SCENARIOS,
FETCH_CONFORMANCE_SEED,
generateFetchConformanceProgram,
generatedScenarioIds,
} from "./fetch-conformance-program.js";
const execFileAsync = promisify(execFile);
const repoRoot = join(import.meta.dirname, "../..");
const fixturesRoot = join(repoRoot, "tests/fixtures/fetch");
const sanitize = process.env["SCRIPTC_SAN"] === "1";
const profile = NODE24_FETCH_COMPAT_PROFILE;
function configuredInteger(
name: string,
fallback: number,
maximum: number,
): number {
const raw = process.env[name];
if (raw === undefined || raw === "") return fallback;
const value = Number(raw);
if (!Number.isInteger(value) || value < 0 || value > maximum) {
throw new Error(`${name} must be an integer between 0 and ${maximum}`);
}
return value;
}
const conformanceSeed = configuredInteger(
"SCRIPTC_FETCH_CONFORMANCE_SEED",
FETCH_CONFORMANCE_SEED,
0xffff_ffff,
);
const conformanceTraceCount = configuredInteger(
"SCRIPTC_FETCH_CONFORMANCE_TRACES",
12,
100,
);
const generatedSource = generateFetchConformanceProgram(profile, {
seed: conformanceSeed,
traceCount: conformanceTraceCount,
});
const sourceHash = createHash("sha256")
.update(generatedSource)
.digest("hex")
.slice(0, 16);
const workRoot = mkdtempSync(join(tmpdir(), "scriptc-fetch-conformance-"));
const entry = join(workRoot, "main.js");
interface RunResult {
stdout: Buffer;
stderr: Buffer;
exitCode: number;
}
function normalizedStderr(result: RunResult): string {
const stderr = result.stderr.toString("utf8");
if (!sanitize) return stderr;
// Linux ASan prints this once per process at the runtime's first fiber
// context switch. It has no suppression switch and is harness noise, not
// program stderr; retain every other byte so real sanitizer reports fail.
return stderr.replace(
/^==\d+==WARNING: ASan doesn't fully support makecontext\/swapcontext.*\n/gm,
"",
);
}
async function run(command: string, args: string[]): Promise<RunResult> {
try {
const result = await execFileAsync(command, args, {
encoding: "buffer",
env: process.env,
timeout: 30_000,
});
return { stdout: result.stdout, stderr: result.stderr, exitCode: 0 };
} catch (error) {
const failure = error as {
code?: unknown;
stdout?: Buffer;
stderr?: Buffer;
};
if (
typeof failure.code !== "number" ||
!Buffer.isBuffer(failure.stdout) ||
!Buffer.isBuffer(failure.stderr)
) {
throw error;
}
return {
stdout: failure.stdout,
stderr: failure.stderr,
exitCode: failure.code,
};
}
}
async function build(backend: "c" | "llvm"): Promise<string> {
const outDir = join(
workRoot,
`${sourceHash}-${backend}-${sanitize ? "san" : "plain"}`,
);
mkdirSync(outDir, { recursive: true });
const result = await compile(entry, {
outDir,
outPath: join(outDir, "program"),
backend,
sanitize,
});
if (!result.ok) {
expect.unreachable(
`generated fetch conformance program failed to compile (${backend}):\n` +
renderAll(result.diagnostics, result.sourceTexts, { color: false }) +
`\ngenerated source: ${entry}`,
);
}
return result.binaryPath;
}
function evidenceKey(evidence: FetchCompatEvidence): string {
if (evidence.generated !== undefined && evidence.fixture === undefined) {
return `generated:${evidence.generated}`;
}
if (evidence.fixture !== undefined && evidence.generated === undefined) {
return `fixture:${evidence.fixture}`;
}
throw new Error("fetch profile evidence must name exactly one source");
}
beforeAll(() => {
writeFileSync(entry, generatedSource);
});
describe("Node 24 fetch compatibility profile", () => {
test("the running oracle is the exact pinned Node/Undici tuple", () => {
const pinnedNode = readFileSync(join(repoRoot, ".node-version"), "utf8").trim();
expect(profile.target.node).toBe(pinnedNode);
expect(process.versions.node).toBe(profile.target.node);
expect(process.versions.undici).toBe(profile.target.undici);
});
test("every row has unique ids and resolvable differential evidence", () => {
expect(profile.schemaVersion).toBe(1);
const rows = [...profile.operations, ...profile.requestInit];
const ids = rows.map((row) => row.id);
expect(new Set(ids).size).toBe(ids.length);
expect(profile.operations.length).toBeGreaterThanOrEqual(35);
for (const row of rows) {
expect(row.evidence.length, `${row.id}: missing differential evidence`).toBeGreaterThan(0);
for (const evidence of row.evidence) {
const key = evidenceKey(evidence);
if (evidence.generated !== undefined) {
expect(
FETCH_CONFORMANCE_SCENARIOS,
`${row.id}: unknown generated scenario ${key}`,
).toContain(evidence.generated);
} else {
const root = join(fixturesRoot, evidence.fixture!);
expect(
existsSync(join(root, "main.js")) || existsSync(join(root, "main.mts")),
`${row.id}: missing ${key}`,
).toBe(true);
}
}
}
});
test("the profile member allowlists have matching operation rows", () => {
for (const member of [
...profile.members.responseReads,
...profile.members.responseCalls,
]) {
expect(
profile.operations.some((operation) =>
operation.name === `Response.${member}`
),
`Response.${member} has no compatibility row`,
).toBe(true);
}
for (const member of [
...profile.members.readableStreamReads,
...profile.members.readableStreamCalls,
]) {
expect(
profile.operations.some((operation) =>
operation.name === `ReadableStream.${member}`
),
`ReadableStream.${member} has no compatibility row`,
).toBe(true);
}
});
test("generation is deterministic and covers every registered scenario", () => {
expect(generateFetchConformanceProgram(profile, {
seed: conformanceSeed,
traceCount: conformanceTraceCount,
})).toBe(generatedSource);
expect(generatedScenarioIds(profile)).toEqual(
[...FETCH_CONFORMANCE_SCENARIOS].sort(),
);
for (const scenario of FETCH_CONFORMANCE_SCENARIOS) {
expect(generatedSource).toContain(`// scenario: ${scenario}`);
}
});
});
describe(
`generated fetch conformance (seed=${conformanceSeed}, traces=${conformanceTraceCount}` +
`${sanitize ? ", sanitized" : ""})`,
() => {
test.for(["c", "llvm"] as const)(
"%s backend matches the pinned Node oracle",
async (backend) => {
const binary = await build(backend);
const [nodeResult, nativeResult] = await Promise.all([
run(process.execPath, [entry]),
run(binary, []),
]);
if (!nativeResult.stdout.equals(nodeResult.stdout)) {
expect(nativeResult.stdout.toString("utf8")).toBe(
nodeResult.stdout.toString("utf8"),
);
expect.unreachable("stdout differed at byte level but not after UTF-8 decoding");
}
expect(normalizedStderr(nativeResult)).toBe(
nodeResult.stderr.toString("utf8"),
);
expect(nativeResult.exitCode).toBe(nodeResult.exitCode);
},
120_000,
);
},
);
+1
View File
@@ -115,6 +115,7 @@ const PROBES: Probe[] = [
{ id: "stdlib.map.has", source: 'const m = new Map<string, number>();\nm.set("a", 1);\nconsole.log(m.has("a"));\n' },
{ id: "stdlib.date.now", source: "console.log(Date.now() > 0);\n" },
{ id: "stdlib.number.toFixed", source: "const n = 1.2345;\nconsole.log(n.toFixed(2));\n" },
{ id: "stdlib.abort-signal.timeout", source: "const signal = AbortSignal.timeout(1000);\nconsole.log(signal.aborted);\n" },
{ id: "node-builtin.process.pid", source: "console.log(process.pid > 0);\n" },
{ id: "node-builtin.perf_hooks.performance.now", source: "console.log(performance.now() >= 0);\n" },
{ id: "node-builtin.path.join", source: 'import { join } from "node:path";\nconsole.log(join("a", "b"));\n' },