CultLib/packages/cultmesh-ts/test/realtime-quic-native.test.ts

388 lines
16 KiB
TypeScript
Raw Normal View History

Test the Node QUIC binding, consumer and the five trust negatives packages/cultmesh-ts/test/realtime-quic-native.test.ts: the FFI smoke against CultMeshQuicNativeRuntime (open/close, a listener with a real PKCS12 credential, a full loopback connection delivering one raw frame end to end), plus the negative grep that .async( appears only on nextEvent and no koffi.register exists. packages/cultmesh-ts/test/realtime-quic-consumer.test.ts: the TypeScript consumer against a raw listener opened through the native runtime (connect with the correct pin; refuse a wrong pin; refuse a missing pin with no validator; a caller validator observes the target and the DER bytes; a late older generation is dropped), mirroring CultMeshNativeQuicRealtimeTransportTests.cs and CultMeshQuicRealtimeTransportTests.cs. Then the five trust negatives through CultMeshQuicRealtimeSessionManager with a static lookup source and routes signed with node:crypto (P-256, IEEE P1363 via dsaEncoding): (a) expired certificate, (b) unsigned remote route, (c) untrusted Odin root, (d) a route that verifies but pins the wrong TLS certificate, refused by the connector before isVerifiedFor is ever asked, and (e) a stale/replayed generation, proven with a stub connector whose transport fails isVerifiedFor, asserting the session manager disposes it and rejects the connect. There is no session_open nonce on the QUIC plane (route generation plus the TLS handshake is its freshness), so (e) is this shape rather than a literal nonce replay, as the cut map records. test/fixtures/quic-test.p12 and quic-test-cert.der: a self-signed ECDSA P-256 PKCS12 test credential (OpenSSL, empty password, 1088 bytes — the same shape as the native bridge's own embedded test PKCS12) and its DER certificate, used to open real raw listeners and compute the expected cert-sha256 pin at test time rather than hand-transcribing it. Discrepancy kept, reported: the C# reference's receive-side inbox also coalesces a backlog of not-yet-drained latest-only frames of the same key to just the newest; this transport applies only the generation-drop filter the cut map names (":538-560") and queues every frame that passes it. The interop lane's frames are far enough apart that this never matters in practice, but a consumer that fell behind would see more history here than the C# reference delivers. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-23 12:32:45 +02:00
// The Cut 3 FFI smoke, now run against `CultMeshQuicNativeRuntime` instead of
// raw koffi calls: open a runtime, open a listener with a real credential,
// connect a real loopback connection, exchange one frame's worth of raw
// bytes, and close everything down. This proves the binding's declared ABI
// matches the shipped bridge; frame semantics (delivery, generation) are
// `realtime-quic-consumer.test.ts`'s job.
//
// Skips instead of failing when no native bridge is available: set
// CULTMESH_QUIC_NATIVE_DIR to a directory `scripts/build-quic-native.ps1` or
// `scripts/build-quic-native.sh` built, or run from the committed
// `packages/cultmesh-ts/native/<platform>` tree once a later cut lands it.
import assert from "node:assert/strict";
import { spawnSync } from "node:child_process";
Test the Node QUIC binding, consumer and the five trust negatives packages/cultmesh-ts/test/realtime-quic-native.test.ts: the FFI smoke against CultMeshQuicNativeRuntime (open/close, a listener with a real PKCS12 credential, a full loopback connection delivering one raw frame end to end), plus the negative grep that .async( appears only on nextEvent and no koffi.register exists. packages/cultmesh-ts/test/realtime-quic-consumer.test.ts: the TypeScript consumer against a raw listener opened through the native runtime (connect with the correct pin; refuse a wrong pin; refuse a missing pin with no validator; a caller validator observes the target and the DER bytes; a late older generation is dropped), mirroring CultMeshNativeQuicRealtimeTransportTests.cs and CultMeshQuicRealtimeTransportTests.cs. Then the five trust negatives through CultMeshQuicRealtimeSessionManager with a static lookup source and routes signed with node:crypto (P-256, IEEE P1363 via dsaEncoding): (a) expired certificate, (b) unsigned remote route, (c) untrusted Odin root, (d) a route that verifies but pins the wrong TLS certificate, refused by the connector before isVerifiedFor is ever asked, and (e) a stale/replayed generation, proven with a stub connector whose transport fails isVerifiedFor, asserting the session manager disposes it and rejects the connect. There is no session_open nonce on the QUIC plane (route generation plus the TLS handshake is its freshness), so (e) is this shape rather than a literal nonce replay, as the cut map records. test/fixtures/quic-test.p12 and quic-test-cert.der: a self-signed ECDSA P-256 PKCS12 test credential (OpenSSL, empty password, 1088 bytes — the same shape as the native bridge's own embedded test PKCS12) and its DER certificate, used to open real raw listeners and compute the expected cert-sha256 pin at test time rather than hand-transcribing it. Discrepancy kept, reported: the C# reference's receive-side inbox also coalesces a backlog of not-yet-drained latest-only frames of the same key to just the newest; this transport applies only the generation-drop filter the cut map names (":538-560") and queues every frame that passes it. The interop lane's frames are far enough apart that this never matters in practice, but a consumer that fell behind would see more history here than the C# reference delivers. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-23 12:32:45 +02:00
import { readFileSync } from "node:fs";
import { join } from "node:path";
import test from "node:test";
import {
CultMeshQuicNativeRuntime,
CULTMESH_QUIC_EVENT_LISTENER_NEW_CONNECTION,
CULTMESH_QUIC_EVENT_CONNECTION_CERTIFICATE_RECEIVED,
CULTMESH_QUIC_EVENT_CONNECTION_CONNECTED,
Add tests for M4b, M10, F7 and strengthen F6kinds M4b: the mirror image of the existing M4 test — a latest-only stream carrying a frame whose own delivery byte says reliable-ordered must fault only that connection, not the pump. M10: an equal-generation frame is dropped by the receive-side filter. Sequenced so it is observable (Soul's note): the first frame is consumed before the duplicate generation arrives, so the coalescer no longer holds a pending value the duplicate could silently overwrite with itself. Without this sequencing, M10's `<=0` -> `<0` mutation is invisible: the coalescer's overwrite semantics make an unconsumed duplicate look identical to a dropped one. F7: split into two tests, because a genuine end-to-end SEND_CANCELED-through-sendFrame() scenario proved unreliable on this host. The native-layer test (realtime-quic-native.test.ts) is deterministic: it round-trips two 64-bit codes above 2^53 through CONNECTION_SHUTDOWN, exercising the exact decode line F7 mutates (`code: toBigInt64(decoded.code)`, shared by every native event type, including STREAM_SEND_COMPLETE). The consumer-level attempt — prime a reliable stream, start a second send, shut the connection down from the peer mid-flight — is recorded as a comment: MsQuic here appears to locally complete a `StreamSend` (as an uncanceled SEND_COMPLETE) faster than any JS-observable window can land a peer shutdown ahead of it, regardless of payload size (tried up to 8 MiB) or an explicit delay before the shutdown call. Recorded as not yet reached at the consumer layer, not as unreachable. F6kinds: the existing "stream shutdown prunes streamKinds" test only proved a second frame still worked afterward, which passes whether or not the map is actually pruned (a stream id is never reused within one connection, so a leaked entry has no other behavioural symptom — exactly why the mutation survived). Strengthened to assert CultMeshQuicRealtimeTransport.trackedStreamCount (added in the previous commit) directly. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-23 16:04:52 +02:00
CULTMESH_QUIC_EVENT_CONNECTION_SHUTDOWN,
Test the Node QUIC binding, consumer and the five trust negatives packages/cultmesh-ts/test/realtime-quic-native.test.ts: the FFI smoke against CultMeshQuicNativeRuntime (open/close, a listener with a real PKCS12 credential, a full loopback connection delivering one raw frame end to end), plus the negative grep that .async( appears only on nextEvent and no koffi.register exists. packages/cultmesh-ts/test/realtime-quic-consumer.test.ts: the TypeScript consumer against a raw listener opened through the native runtime (connect with the correct pin; refuse a wrong pin; refuse a missing pin with no validator; a caller validator observes the target and the DER bytes; a late older generation is dropped), mirroring CultMeshNativeQuicRealtimeTransportTests.cs and CultMeshQuicRealtimeTransportTests.cs. Then the five trust negatives through CultMeshQuicRealtimeSessionManager with a static lookup source and routes signed with node:crypto (P-256, IEEE P1363 via dsaEncoding): (a) expired certificate, (b) unsigned remote route, (c) untrusted Odin root, (d) a route that verifies but pins the wrong TLS certificate, refused by the connector before isVerifiedFor is ever asked, and (e) a stale/replayed generation, proven with a stub connector whose transport fails isVerifiedFor, asserting the session manager disposes it and rejects the connect. There is no session_open nonce on the QUIC plane (route generation plus the TLS handshake is its freshness), so (e) is this shape rather than a literal nonce replay, as the cut map records. test/fixtures/quic-test.p12 and quic-test-cert.der: a self-signed ECDSA P-256 PKCS12 test credential (OpenSSL, empty password, 1088 bytes — the same shape as the native bridge's own embedded test PKCS12) and its DER certificate, used to open real raw listeners and compute the expected cert-sha256 pin at test time rather than hand-transcribing it. Discrepancy kept, reported: the C# reference's receive-side inbox also coalesces a backlog of not-yet-drained latest-only frames of the same key to just the newest; this transport applies only the generation-drop filter the cut map names (":538-560") and queues every frame that passes it. The interop lane's frames are far enough apart that this never matters in practice, but a consumer that fell behind would see more history here than the C# reference delivers. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-23 12:32:45 +02:00
CULTMESH_QUIC_EVENT_STREAM_STARTED,
CULTMESH_QUIC_EVENT_STREAM_FRAME,
CULTMESH_QUIC_EVENT_STREAM_SEND_COMPLETE,
CULTMESH_QUIC_STREAM_RELIABLE,
} from "../src/realtime-quic-native";
Add tests pinning fixes 1-6, M2, M3, M6-M9, and dedupe the two nativeBridgeAvailable helpers Each rule below fails under its own mutation of the code fixed in the previous two commits; verified by hand and restored, per the fix-batch brief, not committed as a mutation harness (the operator retired that pattern). - realtime-quic-native.test.ts: release() refuses a call with no outstanding reference (fix 2). - realtime-quic-consumer.test.ts: a stream-kind/delivery mismatch faults only its connection while a second, independent connection through the same pump keeps working (fix 1 / M4); a peer-initiated shutdown rejects a pending receive and cleans up exactly once, so a further dispose is a no-op and a fresh receive rejects instead of hanging (fix 3); a slow latest-only reader accumulates at most one pending frame per key, and an equal generation is dropped outright (fix 6, M10); a real connected transport's isVerifiedFor rejects a generation other than the one it connected with, and the session manager disposes a real (not stubbed) transport whose generation no longer matches a freshly verified route (M3); the advertised certificate pin matches case-insensitively (M2). - realtime-quic-session-manager.test.ts (new): eviction of a dead cached session and redial on the next connect, single-flight sharing one dial across concurrent callers, refusing a transport that lands after dispose() (all fix 4); the race returning on first success without waiting out a slow candidate (fix 5); the maxRacedCandidates cap (M6); the protocolIds and authorityRuntimeId route filters (M7, M8); the session key including authorityRuntimeId (M9). Trust verification is skipped via mode: "local-development" over loopback endpoints, since these tests are about the session manager's own binding/racing/caching rules, not route trust (already pinned by realtime-quic-consumer.test.ts's trust negatives). Subtraction: `nativeBridgeAvailable` was defined twice, disagreeing on whether to check the dependency library too; both test files now import one definition from test/support/native-bridge.ts (the stricter of the two). Gap, reported rather than papered over: the stream-shutdown pruning half of fix 6 (streamKinds) has no direct test, because the map is private and nothing here exposes it; the committed test only shows a second frame still arrives after the pruned stream's shutdown, which does not by itself prove the entry was removed. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-23 14:38:46 +02:00
import { nativeBridgeAvailable } from "./support/native-bridge";
Test the Node QUIC binding, consumer and the five trust negatives packages/cultmesh-ts/test/realtime-quic-native.test.ts: the FFI smoke against CultMeshQuicNativeRuntime (open/close, a listener with a real PKCS12 credential, a full loopback connection delivering one raw frame end to end), plus the negative grep that .async( appears only on nextEvent and no koffi.register exists. packages/cultmesh-ts/test/realtime-quic-consumer.test.ts: the TypeScript consumer against a raw listener opened through the native runtime (connect with the correct pin; refuse a wrong pin; refuse a missing pin with no validator; a caller validator observes the target and the DER bytes; a late older generation is dropped), mirroring CultMeshNativeQuicRealtimeTransportTests.cs and CultMeshQuicRealtimeTransportTests.cs. Then the five trust negatives through CultMeshQuicRealtimeSessionManager with a static lookup source and routes signed with node:crypto (P-256, IEEE P1363 via dsaEncoding): (a) expired certificate, (b) unsigned remote route, (c) untrusted Odin root, (d) a route that verifies but pins the wrong TLS certificate, refused by the connector before isVerifiedFor is ever asked, and (e) a stale/replayed generation, proven with a stub connector whose transport fails isVerifiedFor, asserting the session manager disposes it and rejects the connect. There is no session_open nonce on the QUIC plane (route generation plus the TLS handshake is its freshness), so (e) is this shape rather than a literal nonce replay, as the cut map records. test/fixtures/quic-test.p12 and quic-test-cert.der: a self-signed ECDSA P-256 PKCS12 test credential (OpenSSL, empty password, 1088 bytes — the same shape as the native bridge's own embedded test PKCS12) and its DER certificate, used to open real raw listeners and compute the expected cert-sha256 pin at test time rather than hand-transcribing it. Discrepancy kept, reported: the C# reference's receive-side inbox also coalesces a backlog of not-yet-drained latest-only frames of the same key to just the newest; this transport applies only the generation-drop filter the cut map names (":538-560") and queues every frame that passes it. The interop lane's frames are far enough apart that this never matters in practice, but a consumer that fell behind would see more history here than the C# reference delivers. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-23 12:32:45 +02:00
Fix the runtime leak that hung the previous ygg-verify job Self killed a verify run after it sat idle for 25+ minutes past its last printed result and root-caused it: SIGUSR2 diagnostics on the stuck process showed an empty JS stack, every libuv handle unreferenced, and MsQuic's own worker threads parked in epoll_wait — a native runtime that was opened but never closed, so its registration and threads never tore down and the process never exited on its own. The cause was mundane and compounds badly: `RawQuicListener.open()` in realtime-quic-consumer.test.ts opened a native runtime, then read a test fixture whose path was wrong (see below) and threw — with no try/catch, so the runtime it had just opened was never released. That test-file pattern ran on seven separate tests in one process, each leaking its own reference to the one process-wide shared runtime; by the time the file's tests finished, the refcount had never reached zero and the live registration held the process open indefinitely. `RawQuicListener.open()` now releases the runtime on any setup failure before rethrowing. Two more real bugs the same run's fixture-path failures exposed: - Both new test files resolved fixtures at `join(__dirname, "fixtures", ...)`. `__dirname` at runtime is `dist-test/test`, and binary fixtures are never compiled or copied there — only `.ts` sources under `test/` and `src/` are. Both now read fixtures from their real location, two directories up. - The negative-grep test looked for a literal `.async(` call. The bugfix in the previous commit references `nextEventFn.async` as a value handed to `promisify`, never written with a trailing `(` at the reference site, so the grep found nothing to check and failed by construction. It now matches `.async` as a property reference, not only a call. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-23 13:13:24 +02:00
// __dirname at runtime is dist-test/test; fixtures are binary and are never
// compiled/copied there, so they are read from their source location, two
// levels up.
const FIXTURE_P12 = join(__dirname, "..", "..", "test", "fixtures", "quic-test.p12");
Test the Node QUIC binding, consumer and the five trust negatives packages/cultmesh-ts/test/realtime-quic-native.test.ts: the FFI smoke against CultMeshQuicNativeRuntime (open/close, a listener with a real PKCS12 credential, a full loopback connection delivering one raw frame end to end), plus the negative grep that .async( appears only on nextEvent and no koffi.register exists. packages/cultmesh-ts/test/realtime-quic-consumer.test.ts: the TypeScript consumer against a raw listener opened through the native runtime (connect with the correct pin; refuse a wrong pin; refuse a missing pin with no validator; a caller validator observes the target and the DER bytes; a late older generation is dropped), mirroring CultMeshNativeQuicRealtimeTransportTests.cs and CultMeshQuicRealtimeTransportTests.cs. Then the five trust negatives through CultMeshQuicRealtimeSessionManager with a static lookup source and routes signed with node:crypto (P-256, IEEE P1363 via dsaEncoding): (a) expired certificate, (b) unsigned remote route, (c) untrusted Odin root, (d) a route that verifies but pins the wrong TLS certificate, refused by the connector before isVerifiedFor is ever asked, and (e) a stale/replayed generation, proven with a stub connector whose transport fails isVerifiedFor, asserting the session manager disposes it and rejects the connect. There is no session_open nonce on the QUIC plane (route generation plus the TLS handshake is its freshness), so (e) is this shape rather than a literal nonce replay, as the cut map records. test/fixtures/quic-test.p12 and quic-test-cert.der: a self-signed ECDSA P-256 PKCS12 test credential (OpenSSL, empty password, 1088 bytes — the same shape as the native bridge's own embedded test PKCS12) and its DER certificate, used to open real raw listeners and compute the expected cert-sha256 pin at test time rather than hand-transcribing it. Discrepancy kept, reported: the C# reference's receive-side inbox also coalesces a backlog of not-yet-drained latest-only frames of the same key to just the newest; this transport applies only the generation-drop filter the cut map names (":538-560") and queues every frame that passes it. The interop lane's frames are far enough apart that this never matters in practice, but a consumer that fell behind would see more history here than the C# reference delivers. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-23 12:32:45 +02:00
async function waitFor<T>(collect: (resolve: (value: T) => void) => void, timeoutMs = 5_000): Promise<T> {
return await new Promise<T>((resolve, reject) => {
const timer = setTimeout(() => reject(new Error("timed out waiting for a native QUIC event")), timeoutMs);
collect((value) => {
clearTimeout(timer);
resolve(value);
});
});
}
test("CultMeshQuicNativeRuntime opens and closes with no listener or connection", async (t) => {
if (!nativeBridgeAvailable()) {
t.skip("CULTMESH_QUIC_NATIVE_DIR is not set to a built native bridge.");
return;
}
const runtime = await CultMeshQuicNativeRuntime.open();
await runtime.release();
});
test("CultMeshQuicNativeRuntime opens and closes a listener with a real PKCS12 credential", async (t) => {
if (!nativeBridgeAvailable()) {
t.skip("CULTMESH_QUIC_NATIVE_DIR is not set to a built native bridge.");
return;
}
const runtime = await CultMeshQuicNativeRuntime.open();
try {
const pkcs12 = readFileSync(FIXTURE_P12);
const { listenerId, boundPort } = runtime.listenerOpen("127.0.0.1", 0, pkcs12, "");
assert.ok(boundPort > 0);
runtime.listenerClose(listenerId);
} finally {
await runtime.release();
}
});
test("a full loopback connection delivers one raw frame end to end", async (t) => {
if (!nativeBridgeAvailable()) {
t.skip("CULTMESH_QUIC_NATIVE_DIR is not set to a built native bridge.");
return;
}
const runtime = await CultMeshQuicNativeRuntime.open();
try {
const pkcs12 = readFileSync(FIXTURE_P12);
const { listenerId, boundPort } = runtime.listenerOpen("127.0.0.1", 0, pkcs12, "");
const accepted = waitFor<bigint>((resolve) => {
runtime.onListenerEvent(listenerId, (event) => {
if (event.type === CULTMESH_QUIC_EVENT_LISTENER_NEW_CONNECTION) resolve(event.connectionId);
});
});
const clientConnectionId = runtime.connectionOpen("127.0.0.1", boundPort);
const clientConnected = waitFor<void>((resolve) => {
runtime.onConnectionEvent(clientConnectionId, (event) => {
if (event.type === CULTMESH_QUIC_EVENT_CONNECTION_CERTIFICATE_RECEIVED) {
runtime.connectionCertificateComplete(clientConnectionId, true);
return;
}
if (event.type === CULTMESH_QUIC_EVENT_CONNECTION_CONNECTED) resolve();
});
});
const serverConnectionId = await accepted;
const serverFrame = waitFor<Uint8Array>((resolve) => {
runtime.onConnectionEvent(serverConnectionId, (event) => {
if (event.type === CULTMESH_QUIC_EVENT_STREAM_STARTED) {
assert.equal(event.streamKind, CULTMESH_QUIC_STREAM_RELIABLE);
return;
}
if (event.type === CULTMESH_QUIC_EVENT_STREAM_FRAME) resolve(event.payload);
});
});
await clientConnected;
const streamId = runtime.streamOpen(clientConnectionId, CULTMESH_QUIC_STREAM_RELIABLE);
const sendComplete = waitFor<void>((resolve) => {
runtime.onConnectionEvent(clientConnectionId, (event) => {
if (event.type === CULTMESH_QUIC_EVENT_STREAM_SEND_COMPLETE) resolve();
});
});
runtime.streamSendFrame(streamId, new Uint8Array([1, 2, 3, 4]), true);
await sendComplete;
const payload = await serverFrame;
assert.deepEqual(Array.from(payload), [1, 2, 3, 4]);
runtime.connectionShutdown(clientConnectionId, 0n);
runtime.connectionShutdown(serverConnectionId, 0n);
runtime.listenerClose(listenerId);
} finally {
await runtime.release();
}
});
Add tests for M4b, M10, F7 and strengthen F6kinds M4b: the mirror image of the existing M4 test — a latest-only stream carrying a frame whose own delivery byte says reliable-ordered must fault only that connection, not the pump. M10: an equal-generation frame is dropped by the receive-side filter. Sequenced so it is observable (Soul's note): the first frame is consumed before the duplicate generation arrives, so the coalescer no longer holds a pending value the duplicate could silently overwrite with itself. Without this sequencing, M10's `<=0` -> `<0` mutation is invisible: the coalescer's overwrite semantics make an unconsumed duplicate look identical to a dropped one. F7: split into two tests, because a genuine end-to-end SEND_CANCELED-through-sendFrame() scenario proved unreliable on this host. The native-layer test (realtime-quic-native.test.ts) is deterministic: it round-trips two 64-bit codes above 2^53 through CONNECTION_SHUTDOWN, exercising the exact decode line F7 mutates (`code: toBigInt64(decoded.code)`, shared by every native event type, including STREAM_SEND_COMPLETE). The consumer-level attempt — prime a reliable stream, start a second send, shut the connection down from the peer mid-flight — is recorded as a comment: MsQuic here appears to locally complete a `StreamSend` (as an uncanceled SEND_COMPLETE) faster than any JS-observable window can land a peer shutdown ahead of it, regardless of payload size (tried up to 8 MiB) or an explicit delay before the shutdown call. Recorded as not yet reached at the consumer layer, not as unreachable. F6kinds: the existing "stream shutdown prunes streamKinds" test only proved a second frame still worked afterward, which passes whether or not the map is actually pruned (a stream id is never reused within one connection, so a leaked entry has no other behavioural symptom — exactly why the mutation survived). Strengthened to assert CultMeshQuicRealtimeTransport.trackedStreamCount (added in the previous commit) directly. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-23 16:04:52 +02:00
test("F7: a 64-bit event code round-trips exactly through the struct decode", async (t) => {
if (!nativeBridgeAvailable()) {
t.skip("CULTMESH_QUIC_NATIVE_DIR is not set to a built native bridge.");
return;
}
const runtime = await CultMeshQuicNativeRuntime.open();
try {
const pkcs12 = readFileSync(FIXTURE_P12);
const { listenerId, boundPort } = runtime.listenerOpen("127.0.0.1", 0, pkcs12, "");
// `code` (a `uint64_t`, the same field `CULTMESH_QUIC_SEND_CANCELED` is
// compared against on the stream-send path) is exercised here through
// CONNECTION_SHUTDOWN instead, whose code is an application-chosen value
// this test fully controls: two values above 2^53 (where koffi's decode
// stops being a plain safe-integer `number`) prove the whole
// encode-native-decode-coerce path is exact, deterministically, with no
// dependency on MsQuic's own send-completion timing.
for (const code of [(1n << 53n) + 1n, (1n << 62n) - 1n]) {
const accepted = waitFor<bigint>((resolve) => {
runtime.onListenerEvent(listenerId, (event) => {
if (event.type === CULTMESH_QUIC_EVENT_LISTENER_NEW_CONNECTION) resolve(event.connectionId);
});
});
const clientConnectionId = runtime.connectionOpen("127.0.0.1", boundPort);
const clientConnected = waitFor<void>((resolve) => {
runtime.onConnectionEvent(clientConnectionId, (event) => {
if (event.type === CULTMESH_QUIC_EVENT_CONNECTION_CERTIFICATE_RECEIVED) {
runtime.connectionCertificateComplete(clientConnectionId, true);
return;
}
if (event.type === CULTMESH_QUIC_EVENT_CONNECTION_CONNECTED) resolve();
});
});
const serverConnectionId = await accepted;
await clientConnected;
const seenOnClient = waitFor<bigint>((resolve) => {
runtime.onConnectionEvent(clientConnectionId, (event) => {
if (event.type === CULTMESH_QUIC_EVENT_CONNECTION_SHUTDOWN) resolve(event.code);
});
});
runtime.connectionShutdown(serverConnectionId, code);
const seen = await seenOnClient;
assert.equal(typeof seen, "bigint", "a decoded event code must always be bigint, never number");
assert.equal(seen, code, `shutdown code ${code} must round-trip exactly through the struct decode`);
}
runtime.listenerClose(listenerId);
} finally {
await runtime.release();
}
});
test(
"P10b: a throwing onFault handler is isolated — the pump survives and other connections' handlers still run",
{ timeout: 10_000 },
async (t) => {
if (!nativeBridgeAvailable()) {
t.skip("CULTMESH_QUIC_NATIVE_DIR is not set to a built native bridge.");
return;
}
const runtime = await CultMeshQuicNativeRuntime.open();
try {
const pkcs12 = readFileSync(FIXTURE_P12);
const { listenerId, boundPort } = runtime.listenerOpen("127.0.0.1", 0, pkcs12, "");
// Connection B: a normal, fully connected loopback pair, established
// before A ever faults — so proving B still works afterward exercises
// an already-running connection's handler, not a second accept cycle
// racing whatever state A's fault left behind.
const acceptedB = waitFor<bigint>((resolve) => {
runtime.onListenerEvent(listenerId, (event) => {
if (event.type === CULTMESH_QUIC_EVENT_LISTENER_NEW_CONNECTION) resolve(event.connectionId);
});
});
const clientB = runtime.connectionOpen("127.0.0.1", boundPort);
const clientBConnected = waitFor<void>((resolve) => {
runtime.onConnectionEvent(clientB, (event) => {
if (event.type === CULTMESH_QUIC_EVENT_CONNECTION_CERTIFICATE_RECEIVED) {
runtime.connectionCertificateComplete(clientB, true);
return;
}
if (event.type === CULTMESH_QUIC_EVENT_CONNECTION_CONNECTED) resolve();
});
});
const serverBId = await acceptedB;
const serverBFrame = waitFor<Uint8Array>((resolve) => {
runtime.onConnectionEvent(serverBId, (event) => {
if (event.type === CULTMESH_QUIC_EVENT_STREAM_FRAME) resolve(event.payload);
});
});
await clientBConnected;
// Connection A, opened only after B is fully connected: both its
// listener and its onFault handler throw on the first event delivered
// to it. Without `faultConnection`'s own try/catch isolating a
// throwing `onFault` (P10b's target), that throw would escape the
// pump's dispatch loop and take every other connection — including
// the already-live B — down with it, instead of staying scoped to A.
//
// The server-side connection listener is registered synchronously,
// inside the LISTENER_NEW_CONNECTION callback itself, rather than
// after an `await`: the native bridge can dispatch a connection's next
// event (CERTIFICATE_RECEIVED, or CONNECTED) before a later `await`'s
// continuation ever runs, and an event with no listener registered for
// its connection id is silently dropped (`dispatch`'s own
// `if (!entry) return`) — the same async-registration gap fix 1 closed
// for the provider's own accept path.
const serverAFaulted = waitFor<void>((resolve) => {
runtime.onListenerEvent(listenerId, (event) => {
if (event.type !== CULTMESH_QUIC_EVENT_LISTENER_NEW_CONNECTION) return;
runtime.onConnectionEvent(
event.connectionId,
() => {
throw new Error("P10b: connection A's listener always throws.");
},
() => {
resolve();
throw new Error("P10b: connection A's onFault also throws.");
},
);
});
});
const clientA = runtime.connectionOpen("127.0.0.1", boundPort);
runtime.onConnectionEvent(clientA, (event) => {
if (event.type === CULTMESH_QUIC_EVENT_CONNECTION_CERTIFICATE_RECEIVED) {
runtime.connectionCertificateComplete(clientA, true);
}
});
await serverAFaulted;
// Prove B's handler is still live after A's onFault threw: send a
// frame on B and confirm the server side still receives it.
const streamId = runtime.streamOpen(clientB, CULTMESH_QUIC_STREAM_RELIABLE);
runtime.streamSendFrame(streamId, new Uint8Array([9, 9, 9]), true);
const payload = await serverBFrame;
assert.deepEqual(
Array.from(payload),
[9, 9, 9],
"connection B must still deliver frames after A's onFault threw",
);
runtime.connectionShutdown(clientA, 0n);
runtime.connectionShutdown(clientB, 0n);
runtime.connectionShutdown(serverBId, 0n);
runtime.listenerClose(listenerId);
} finally {
await runtime.release();
}
},
);
Add tests pinning fixes 1-6, M2, M3, M6-M9, and dedupe the two nativeBridgeAvailable helpers Each rule below fails under its own mutation of the code fixed in the previous two commits; verified by hand and restored, per the fix-batch brief, not committed as a mutation harness (the operator retired that pattern). - realtime-quic-native.test.ts: release() refuses a call with no outstanding reference (fix 2). - realtime-quic-consumer.test.ts: a stream-kind/delivery mismatch faults only its connection while a second, independent connection through the same pump keeps working (fix 1 / M4); a peer-initiated shutdown rejects a pending receive and cleans up exactly once, so a further dispose is a no-op and a fresh receive rejects instead of hanging (fix 3); a slow latest-only reader accumulates at most one pending frame per key, and an equal generation is dropped outright (fix 6, M10); a real connected transport's isVerifiedFor rejects a generation other than the one it connected with, and the session manager disposes a real (not stubbed) transport whose generation no longer matches a freshly verified route (M3); the advertised certificate pin matches case-insensitively (M2). - realtime-quic-session-manager.test.ts (new): eviction of a dead cached session and redial on the next connect, single-flight sharing one dial across concurrent callers, refusing a transport that lands after dispose() (all fix 4); the race returning on first success without waiting out a slow candidate (fix 5); the maxRacedCandidates cap (M6); the protocolIds and authorityRuntimeId route filters (M7, M8); the session key including authorityRuntimeId (M9). Trust verification is skipped via mode: "local-development" over loopback endpoints, since these tests are about the session manager's own binding/racing/caching rules, not route trust (already pinned by realtime-quic-consumer.test.ts's trust negatives). Subtraction: `nativeBridgeAvailable` was defined twice, disagreeing on whether to check the dependency library too; both test files now import one definition from test/support/native-bridge.ts (the stricter of the two). Gap, reported rather than papered over: the stream-shutdown pruning half of fix 6 (streamKinds) has no direct test, because the map is private and nothing here exposes it; the committed test only shows a second frame still arrives after the pruned stream's shutdown, which does not by itself prove the entry was removed. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-23 14:38:46 +02:00
test("fix 2: release() refuses a call with no outstanding reference", async (t) => {
if (!nativeBridgeAvailable()) {
t.skip("CULTMESH_QUIC_NATIVE_DIR is not set to a built native bridge.");
return;
}
const runtime = await CultMeshQuicNativeRuntime.open();
await runtime.release();
await assert.rejects(runtime.release(), /no outstanding reference/i);
});
Test the Node QUIC binding, consumer and the five trust negatives packages/cultmesh-ts/test/realtime-quic-native.test.ts: the FFI smoke against CultMeshQuicNativeRuntime (open/close, a listener with a real PKCS12 credential, a full loopback connection delivering one raw frame end to end), plus the negative grep that .async( appears only on nextEvent and no koffi.register exists. packages/cultmesh-ts/test/realtime-quic-consumer.test.ts: the TypeScript consumer against a raw listener opened through the native runtime (connect with the correct pin; refuse a wrong pin; refuse a missing pin with no validator; a caller validator observes the target and the DER bytes; a late older generation is dropped), mirroring CultMeshNativeQuicRealtimeTransportTests.cs and CultMeshQuicRealtimeTransportTests.cs. Then the five trust negatives through CultMeshQuicRealtimeSessionManager with a static lookup source and routes signed with node:crypto (P-256, IEEE P1363 via dsaEncoding): (a) expired certificate, (b) unsigned remote route, (c) untrusted Odin root, (d) a route that verifies but pins the wrong TLS certificate, refused by the connector before isVerifiedFor is ever asked, and (e) a stale/replayed generation, proven with a stub connector whose transport fails isVerifiedFor, asserting the session manager disposes it and rejects the connect. There is no session_open nonce on the QUIC plane (route generation plus the TLS handshake is its freshness), so (e) is this shape rather than a literal nonce replay, as the cut map records. test/fixtures/quic-test.p12 and quic-test-cert.der: a self-signed ECDSA P-256 PKCS12 test credential (OpenSSL, empty password, 1088 bytes — the same shape as the native bridge's own embedded test PKCS12) and its DER certificate, used to open real raw listeners and compute the expected cert-sha256 pin at test time rather than hand-transcribing it. Discrepancy kept, reported: the C# reference's receive-side inbox also coalesces a backlog of not-yet-drained latest-only frames of the same key to just the newest; this transport applies only the generation-drop filter the cut map names (":538-560") and queues every frame that passes it. The interop lane's frames are far enough apart that this never matters in practice, but a consumer that fell behind would see more history here than the C# reference delivers. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-23 12:32:45 +02:00
test("negative grep: no koffi callbacks, .async only on nextEvent", () => {
// __dirname at runtime is dist-test/test; the source lives two levels up,
// in src/, since only .js output is mirrored under dist-test.
const source = readFileSync(join(__dirname, "..", "..", "src", "realtime-quic-native.ts"), "utf8");
Fix the runtime leak that hung the previous ygg-verify job Self killed a verify run after it sat idle for 25+ minutes past its last printed result and root-caused it: SIGUSR2 diagnostics on the stuck process showed an empty JS stack, every libuv handle unreferenced, and MsQuic's own worker threads parked in epoll_wait — a native runtime that was opened but never closed, so its registration and threads never tore down and the process never exited on its own. The cause was mundane and compounds badly: `RawQuicListener.open()` in realtime-quic-consumer.test.ts opened a native runtime, then read a test fixture whose path was wrong (see below) and threw — with no try/catch, so the runtime it had just opened was never released. That test-file pattern ran on seven separate tests in one process, each leaking its own reference to the one process-wide shared runtime; by the time the file's tests finished, the refcount had never reached zero and the live registration held the process open indefinitely. `RawQuicListener.open()` now releases the runtime on any setup failure before rethrowing. Two more real bugs the same run's fixture-path failures exposed: - Both new test files resolved fixtures at `join(__dirname, "fixtures", ...)`. `__dirname` at runtime is `dist-test/test`, and binary fixtures are never compiled or copied there — only `.ts` sources under `test/` and `src/` are. Both now read fixtures from their real location, two directories up. - The negative-grep test looked for a literal `.async(` call. The bugfix in the previous commit references `nextEventFn.async` as a value handed to `promisify`, never written with a trailing `(` at the reference site, so the grep found nothing to check and failed by construction. It now matches `.async` as a property reference, not only a call. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-23 13:13:24 +02:00
// `.async` is referenced (not necessarily called with a literal "(" at the
// reference site: it is handed to `promisify`, which calls it) only for
// `nextEvent`, the ABI's single blocking export.
const asyncUses = [...source.matchAll(/\.async\b/g)];
assert.ok(asyncUses.length > 0, "expected at least one .async use for nextEvent");
Test the Node QUIC binding, consumer and the five trust negatives packages/cultmesh-ts/test/realtime-quic-native.test.ts: the FFI smoke against CultMeshQuicNativeRuntime (open/close, a listener with a real PKCS12 credential, a full loopback connection delivering one raw frame end to end), plus the negative grep that .async( appears only on nextEvent and no koffi.register exists. packages/cultmesh-ts/test/realtime-quic-consumer.test.ts: the TypeScript consumer against a raw listener opened through the native runtime (connect with the correct pin; refuse a wrong pin; refuse a missing pin with no validator; a caller validator observes the target and the DER bytes; a late older generation is dropped), mirroring CultMeshNativeQuicRealtimeTransportTests.cs and CultMeshQuicRealtimeTransportTests.cs. Then the five trust negatives through CultMeshQuicRealtimeSessionManager with a static lookup source and routes signed with node:crypto (P-256, IEEE P1363 via dsaEncoding): (a) expired certificate, (b) unsigned remote route, (c) untrusted Odin root, (d) a route that verifies but pins the wrong TLS certificate, refused by the connector before isVerifiedFor is ever asked, and (e) a stale/replayed generation, proven with a stub connector whose transport fails isVerifiedFor, asserting the session manager disposes it and rejects the connect. There is no session_open nonce on the QUIC plane (route generation plus the TLS handshake is its freshness), so (e) is this shape rather than a literal nonce replay, as the cut map records. test/fixtures/quic-test.p12 and quic-test-cert.der: a self-signed ECDSA P-256 PKCS12 test credential (OpenSSL, empty password, 1088 bytes — the same shape as the native bridge's own embedded test PKCS12) and its DER certificate, used to open real raw listeners and compute the expected cert-sha256 pin at test time rather than hand-transcribing it. Discrepancy kept, reported: the C# reference's receive-side inbox also coalesces a backlog of not-yet-drained latest-only frames of the same key to just the newest; this transport applies only the generation-drop filter the cut map names (":538-560") and queues every frame that passes it. The interop lane's frames are far enough apart that this never matters in practice, but a consumer that fell behind would see more history here than the C# reference delivers. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-23 12:32:45 +02:00
for (const match of asyncUses) {
const before = source.slice(Math.max(0, match.index! - 40), match.index!);
Fix the runtime leak that hung the previous ygg-verify job Self killed a verify run after it sat idle for 25+ minutes past its last printed result and root-caused it: SIGUSR2 diagnostics on the stuck process showed an empty JS stack, every libuv handle unreferenced, and MsQuic's own worker threads parked in epoll_wait — a native runtime that was opened but never closed, so its registration and threads never tore down and the process never exited on its own. The cause was mundane and compounds badly: `RawQuicListener.open()` in realtime-quic-consumer.test.ts opened a native runtime, then read a test fixture whose path was wrong (see below) and threw — with no try/catch, so the runtime it had just opened was never released. That test-file pattern ran on seven separate tests in one process, each leaking its own reference to the one process-wide shared runtime; by the time the file's tests finished, the refcount had never reached zero and the live registration held the process open indefinitely. `RawQuicListener.open()` now releases the runtime on any setup failure before rethrowing. Two more real bugs the same run's fixture-path failures exposed: - Both new test files resolved fixtures at `join(__dirname, "fixtures", ...)`. `__dirname` at runtime is `dist-test/test`, and binary fixtures are never compiled or copied there — only `.ts` sources under `test/` and `src/` are. Both now read fixtures from their real location, two directories up. - The negative-grep test looked for a literal `.async(` call. The bugfix in the previous commit references `nextEventFn.async` as a value handed to `promisify`, never written with a trailing `(` at the reference site, so the grep found nothing to check and failed by construction. It now matches `.async` as a property reference, not only a call. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-23 13:13:24 +02:00
assert.match(before, /nextEvent/i, "the only .async reference must be nextEvent");
Test the Node QUIC binding, consumer and the five trust negatives packages/cultmesh-ts/test/realtime-quic-native.test.ts: the FFI smoke against CultMeshQuicNativeRuntime (open/close, a listener with a real PKCS12 credential, a full loopback connection delivering one raw frame end to end), plus the negative grep that .async( appears only on nextEvent and no koffi.register exists. packages/cultmesh-ts/test/realtime-quic-consumer.test.ts: the TypeScript consumer against a raw listener opened through the native runtime (connect with the correct pin; refuse a wrong pin; refuse a missing pin with no validator; a caller validator observes the target and the DER bytes; a late older generation is dropped), mirroring CultMeshNativeQuicRealtimeTransportTests.cs and CultMeshQuicRealtimeTransportTests.cs. Then the five trust negatives through CultMeshQuicRealtimeSessionManager with a static lookup source and routes signed with node:crypto (P-256, IEEE P1363 via dsaEncoding): (a) expired certificate, (b) unsigned remote route, (c) untrusted Odin root, (d) a route that verifies but pins the wrong TLS certificate, refused by the connector before isVerifiedFor is ever asked, and (e) a stale/replayed generation, proven with a stub connector whose transport fails isVerifiedFor, asserting the session manager disposes it and rejects the connect. There is no session_open nonce on the QUIC plane (route generation plus the TLS handshake is its freshness), so (e) is this shape rather than a literal nonce replay, as the cut map records. test/fixtures/quic-test.p12 and quic-test-cert.der: a self-signed ECDSA P-256 PKCS12 test credential (OpenSSL, empty password, 1088 bytes — the same shape as the native bridge's own embedded test PKCS12) and its DER certificate, used to open real raw listeners and compute the expected cert-sha256 pin at test time rather than hand-transcribing it. Discrepancy kept, reported: the C# reference's receive-side inbox also coalesces a backlog of not-yet-drained latest-only frames of the same key to just the newest; this transport applies only the generation-drop filter the cut map names (":538-560") and queues every frame that passes it. The interop lane's frames are far enough apart that this never matters in practice, but a consumer that fell behind would see more history here than the C# reference delivers. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-23 12:32:45 +02:00
}
assert.doesNotMatch(source, /koffi\.register/, "no koffi callbacks");
});
// The measurement below runs in its own `node --expose-gc` child process
// instead of in this test's own process: by the time this test would run,
// ~150 earlier tests in the suite have already grown and partly freed the
// glibc heap, so a real per-call native leak can land in already-mapped free
// space and never show up as RSS growth in *this* process (confirmed by hand:
// the in-process version of this test passed even with `nextEvent` mutated
// back to allocating fresh koffi buffers every call). A freshly spawned
// process has no such history, matching the ~8 MiB (fixed) vs ~30 MiB
// (pre-fix) split measured in isolation.
const MEMORY_PROBE_SCRIPT = `
const { CultMeshQuicNativeRuntime } = require(process.argv[1]);
(async () => {
const runtime = await CultMeshQuicNativeRuntime.open();
const nextEvent = runtime.nextEvent.bind(runtime);
try {
for (let i = 0; i < 2000; i += 1) await nextEvent(0, null, 0);
global.gc();
const before = process.memoryUsage().rss;
const ITERATIONS = 200000;
for (let i = 0; i < ITERATIONS; i += 1) await nextEvent(0, null, 0);
global.gc();
const after = process.memoryUsage().rss;
process.stdout.write(JSON.stringify({ before, after, growthBytes: after - before, ITERATIONS }));
} finally {
await runtime.release();
}
})().catch((error) => {
console.error(error);
process.exit(1);
});
`;
test(
"memory: sustained nextEvent calls do not leak koffi-allocated out-parameter buffers",
{ timeout: 60_000 },
(t) => {
if (!nativeBridgeAvailable()) {
t.skip("CULTMESH_QUIC_NATIVE_DIR is not set to a built native bridge.");
return;
}
// `nextEvent` is private; the compiled module path is resolved the same
// way this file's own `import` resolves it, and handed to the child by
// argv so the child needs no path logic of its own.
const modulePath = require.resolve("../src/realtime-quic-native");
const result = spawnSync(process.execPath, ["--expose-gc", "-e", MEMORY_PROBE_SCRIPT, modulePath], {
encoding: "utf8",
env: process.env,
});
if (result.status !== 0 || typeof result.stdout !== "string" || result.stdout.trim().length === 0) {
if (/--expose-gc/.test(result.stderr ?? "")) {
t.skip("this Node build does not support --expose-gc.");
return;
}
assert.fail(
`memory probe child process failed (status ${String(result.status)}):\n${result.stderr ?? "(no stderr)"}`,
);
}
const { before, after, growthBytes, ITERATIONS } = JSON.parse(result.stdout.trim()) as {
before: number;
after: number;
growthBytes: number;
ITERATIONS: number;
};
// Measured on Yggdrasil, same build and host, in a dedicated process:
// fixed code (0 `koffi.alloc` calls in the loop): ~8.0 MiB RSS growth.
// pre-fix code (400k `koffi.alloc` calls, never freed): ~29.9 MiB.
// 18 MiB sits well above the fixed baseline and well below the leaking
// one, so the bound stays robust to ordinary run-to-run noise while
// still catching the regression.
const BOUND_BYTES = 18 * 1024 * 1024;
assert.ok(
growthBytes < BOUND_BYTES,
`RSS grew by ${growthBytes} bytes (${(growthBytes / 1024 / 1024).toFixed(2)} MiB, from ${before} to ${after}) ` +
`over ${ITERATIONS} nextEvent calls; expected it to stay under ${BOUND_BYTES / 1024 / 1024} MiB once ` +
"out-parameter buffers are reused instead of allocated per call.",
);
},
);