Stop the realtime decoder handing back a view of its own frame

Two mutants the cut-2 pass recorded as equivalent were not. Both notes were
reasoning, and both were wrong in the same way: they argued from the shape of
the code instead of trying the input that breaks it.

The decoder's length refusal reads `payloadLength < 0 || expected !== length`.
The note said the first clause could never fire on its own, because a negative
payload length makes the sum smaller than the frame. It does not: the sum also
carries the three identity lengths, and a negative payload cancels against
them. A 37-byte frame declaring `channelLength=65535, payloadLength=-65535`
sums to exactly 37, matches its own byte length, and without the clause decodes
to three blank identities and an empty payload where `CultMeshRealtimeWireProtocol`
refuses it. Two smaller spellings do the same, `ch=1, pl=-1` over 37 bytes and
`ch=2, pl=-1` over 38. No test covered that shape; one does now, and the
mutation is listed and killed rather than excused.

The payload copy was worse, because the fix and the bug looked identical. The
decoder used `bytes.slice(...)`, which copies a `Uint8Array` — and the existing
test passes one, so it was green — but Node's `Buffer` overrides `slice` with
an alias of `subarray`. A `Buffer` is what a socket read hands a Node caller,
which is exactly how the QUIC plane in cut 4 will reach this function, so every
decoded payload would have been a live view of a frame buffer the transport is
free to reuse.

`Uint8Array.prototype.slice.call(bytes, ...)` was the obvious repair and does
copy, but `%TypedArray%.prototype.slice` takes its result constructor from
`@@species`, and `Buffer`'s is `FastBuffer`: the payload then comes back a
`Buffer` from a `Buffer` frame and a `Uint8Array` from a `Uint8Array` one, so
the same frame compares equal or unequal under `deepStrictEqual` depending on
how it arrived. `new Uint8Array(bytes.subarray(...))` copies and is one type on
both. Three mutations now guard the line — return a view, return a `Buffer`
view, return a species-typed copy — and the first two die only on their own
input type.

Mutation runner: 75 mutations, 75 killed, 0 survivors, three green controls.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-09-16 20:20:16 +02:00
commit 9a4c9396b4
3 changed files with 84 additions and 8 deletions

View file

@ -173,6 +173,19 @@ export function decodeRealtimeFrame(bytes: Uint8Array): CultMeshRealtimeFrame {
producerEpoch: view.getBigInt64(5, true),
sequence: view.getBigInt64(13, true),
delivery,
payload: bytes.slice(offset, offset + payloadLength),
// Not `bytes.slice(...)`. Node's `Buffer` overrides `slice` with an alias of
// `subarray`, so on a `Buffer` — which is what every socket read hands a Node
// caller — that spelling returns a *view* of the frame, and a decoded payload
// that changes when the frame buffer is reused.
//
// Nor `Uint8Array.prototype.slice.call(bytes, ...)`, which does bypass the
// override and copy, but takes its result constructor from `@@species`: on a
// `Buffer` that is `FastBuffer`, so the payload comes back a `Buffer` from a
// `Buffer` frame and a `Uint8Array` from a `Uint8Array` one. The declared
// type holds either way, but `deepStrictEqual` does not, so the same frame
// would compare equal or not depending on how it reached the decoder.
//
// The constructor copies and is the one type on both inputs.
payload: new Uint8Array(bytes.subarray(offset, offset + payloadLength)),
};
}

View file

@ -325,6 +325,43 @@ test("decode refuses every malformed frame the reference refuses, in the referen
assert.equal(decodeRealtimeFrame(blank).channelId, " ".repeat(15));
});
// The `payloadLength < 0` clause in the length refusal is not redundant with the
// sum check beside it, which is what a surviving mutant that dropped it claimed.
// A negative payload length cancels against the identity lengths, so a frame can
// be crafted whose sum lands exactly on its own byte length. Without the clause
// each of these decodes to blank identities and an empty payload where the C#
// reference (`CultMeshRealtimeWireProtocol.cs:74-76`, same clause) refuses.
test("decode refuses a negative payload length that the length sum cancels out", () => {
const good = encodeRealtimeFrame(sample());
// A valid magic, wire version, header size and delivery byte, then the three
// identity lengths and the payload length written by hand.
const crafted = (channelLength: number, payloadLength: number, totalBytes: number) => {
const bytes = new Uint8Array(totalBytes);
bytes.set(good.subarray(0, 37), 0);
const view = new DataView(bytes.buffer);
view.setUint16(21, channelLength, true);
view.setUint16(23, 0, true);
view.setUint16(25, 0, true);
view.setInt32(27, payloadLength, true);
// The sum the decoder computes must land exactly on the frame's own length,
// or the check beside the clause would refuse it and prove nothing.
assert.equal(37 + channelLength + 0 + 0 + payloadLength, totalBytes, "the crafted sum must match");
return bytes;
};
const cases: readonly (readonly [string, Uint8Array])[] = [
["a maximal channel length cancelled by -65535, summing to 37", crafted(0xffff, -0xffff, 37)],
["a channel length of 1 cancelled by -1, summing to 37", crafted(1, -1, 37)],
["a channel length of 2 cancelled by -1, summing to 38", crafted(2, -1, 38)],
];
for (const [label, bytes] of cases) {
assert.throws(
() => decodeRealtimeFrame(bytes),
(error: Error) => error.message === "Realtime frame length is invalid.",
label,
);
}
});
test("decode reads exactly the viewed bytes of an offset view, not the buffer behind it", () => {
const good = encodeRealtimeFrame(sample({ payload: Uint8Array.from([9, 8, 7]) }));
const pool = new Uint8Array(good.byteLength + 64).fill(0xa5);
@ -338,6 +375,22 @@ test("decode reads exactly the viewed bytes of an offset view, not the buffer be
assert.deepEqual(decoded.payload, Uint8Array.from([9, 8, 7]));
});
// The `Uint8Array` case above passes with a plain `bytes.slice(...)`; this one
// does not. Node's `Buffer` overrides `slice` with an alias of `subarray`, and a
// `Buffer` is what a socket read hands a Node caller, so the aliasing bug this
// pins is the one that would actually reach a consumer.
test("the decoded payload copies out of a Node Buffer too, which overrides slice", () => {
const frame = Buffer.from(encodeRealtimeFrame(sample({ payload: Uint8Array.from([9, 8, 7]) })));
const decoded = decodeRealtimeFrame(frame);
frame[frame.byteLength - 1] = 0;
assert.deepEqual(decoded.payload, Uint8Array.from([9, 8, 7]), "payload unchanged by a later write to the frame");
assert.equal(Buffer.isBuffer(decoded.payload), false, "the copy is a plain Uint8Array, not a Buffer");
assert.notEqual(decoded.payload.buffer, frame.buffer, "the copy has its own backing store");
// The three identities need no such check: `TextDecoder` returns strings, which
// hold no reference to the bytes they were decoded from.
assert.equal(decoded.channelId, "aetheria.zone-1");
});
test("the codec touches no socket: no node: import in the source", () => {
const source = readFileSync(join(__dirname, "..", "..", "src", "realtime-wire.ts"), "utf8");
assert.doesNotMatch(source, /from "node:|require\("node:/);

View file

@ -303,16 +303,26 @@ const mutations = [
{ target: "realtime", rule: "decode checks the wire version", old: " if (view.getUint16(35, true) !== WIRE_VERSION || view.getInt32(31, true) !== FIXED_HEADER_BYTES) {", new: " if (view.getInt32(31, true) !== FIXED_HEADER_BYTES) {" },
{ target: "realtime", rule: "decode checks the stamped header size", old: " if (view.getUint16(35, true) !== WIRE_VERSION || view.getInt32(31, true) !== FIXED_HEADER_BYTES) {", new: " if (view.getUint16(35, true) !== WIRE_VERSION) {" },
{ target: "realtime", rule: "decode refuses a delivery byte outside the three modes", old: ' if (delivery === undefined) throw new Error("Realtime frame delivery mode is invalid.");\n', new: ' if (delivery === undefined) return { channelId: "", schemaId: "", bodyId: "", producerEpoch: 0n, sequence: 0n, delivery: "unreliable", payload: new Uint8Array(0) };\n' },
// Not listed: removing `payloadLength < 0` from the decoder's length refusal.
// The clause mirrors the reference but cannot fire on its own: a negative
// payload length makes the sum smaller than the frame, and reaching the sum
// check at all means the frame is already at least 37 bytes, so the sum can
// never match while the length is negative. The mutant is equivalent, and it
// survived when tried.
{ target: "realtime", rule: "decode refuses a length sum that misses the frame", old: " if (payloadLength < 0 || expected !== bytes.byteLength) throw", new: " if (payloadLength < 0) throw" },
// This one was first listed as equivalent — "a negative payload length makes
// the sum smaller than the frame, so the sum check covers it" — and it did
// survive. The reasoning was wrong: a negative payload length cancels against
// the identity lengths, so a 37-byte frame with channelLength 65535 and
// payloadLength -65535 sums to exactly 37 and decoded to blank identities
// while the reference refused it. No test covered that shape; one does now.
{ target: "realtime", rule: "decode refuses a negative payload length the sum cancels out", old: " if (payloadLength < 0 || expected !== bytes.byteLength) throw", new: " if (expected !== bytes.byteLength) throw" },
{ target: "realtime", rule: "decode keeps a leading byte-order mark, as Encoding.UTF8.GetString does", old: 'const decoder = new TextDecoder("utf-8", { ignoreBOM: true });', new: "const decoder = new TextDecoder();" },
{ target: "realtime", rule: "decode reads exactly the viewed bytes of an offset view", old: " const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);", new: " const view = new DataView(bytes.buffer);" },
{ target: "realtime", rule: "the decoded payload does not alias the frame it came from", old: " payload: bytes.slice(offset, offset + payloadLength),", new: " payload: bytes.subarray(offset, offset + payloadLength)," },
{ target: "realtime", rule: "the decoded payload does not alias the frame it came from", old: " payload: new Uint8Array(bytes.subarray(offset, offset + payloadLength)),", new: " payload: bytes.subarray(offset, offset + payloadLength)," },
// The narrower half of the same rule, and the one that shipped broken: a plain
// `bytes.slice` copies a `Uint8Array` but aliases a `Buffer`, whose own `slice`
// is an alias of `subarray`. The mutation above dies on the `Uint8Array` test;
// this one survives it and dies only on the `Buffer` test.
{ target: "realtime", rule: "the decoded payload copies out of a Buffer, whose own slice is a view", old: " payload: new Uint8Array(bytes.subarray(offset, offset + payloadLength)),", new: " payload: bytes.slice(offset, offset + payloadLength)," },
// And the payload's type does not follow the frame's. This spelling copies, so
// both mutations above are dead to it, but `@@species` hands a `Buffer` frame a
// `Buffer` payload; only the `Buffer.isBuffer` assertion kills it.
{ target: "realtime", rule: "the decoded payload is a plain Uint8Array whatever the frame was", old: " payload: new Uint8Array(bytes.subarray(offset, offset + payloadLength)),", new: " payload: Uint8Array.prototype.slice.call(bytes, offset, offset + payloadLength)," },
// Last, because it removes this target's sentinel.
{ target: "realtime", rule: "the frame magic is 0x31545343", old: "const MAGIC = 0x31545343;", new: "const MAGIC = 0x31545344;" },
];