From 5af8df1879666b786ceb102f0f30a247f4f10aa6 Mon Sep 17 00:00:00 2001 From: Peter Steinberger Date: Tue, 20 Oct 2026 02:14:06 -0700 Subject: [PATCH] perf: avoid cause-free Error serialization overhead Retain terminal v14 Error records and snapshot own data causes for a distinct v16 tag. Negotiate v16 support separately from the intermediate v15 format so older IPC peers continue receiving v14 messages. --- CHANGELOG.md | 2 + docs/guides/process/ipc.mdx | 2 +- docs/runtime/nodejs-compat.mdx | 2 +- .../webcore/SerializedScriptValue.cpp | 169 ++++++++---------- src/runtime/ipc.rs | 3 +- test/js/bun/spawn/spawn.ipc.test.ts | 4 +- test/js/node/v8/v8-serdes-buffer.test.ts | 4 +- test/js/web/workers/structured-clone.test.ts | 53 +++++- 8 files changed, 135 insertions(+), 104 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 87b369cfb96c..b4bbfc57ec52 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## Unreleased +- Keep cause-free Error serialization on its terminal fast path with byte-identical v14 output; use a distinct v16 Error cause tag and capability negotiation with older IPC peers. + - Preserve Error cause graphs in structured cloning and worker messages, while retaining v14 bytes for cause-free values and negotiating cause support for advanced IPC with older Bun processes; thanks fuller-stack-dev. - Sync oven-sh/bun through `ad4089bf49d9f4c3ab7c8d95a58f3e0f0f186054`, including lint, format, binding, WebSocket and SQL updates, while retaining the fork runtime and CI contracts. diff --git a/docs/guides/process/ipc.mdx b/docs/guides/process/ipc.mdx index 120585f40d73..f55db9c160f1 100644 --- a/docs/guides/process/ipc.mdx +++ b/docs/guides/process/ipc.mdx @@ -56,7 +56,7 @@ process.on("message", message => { By default, Bun serializes messages with the JSC `serialize` API. This API supports everything [`structuredClone` supports](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm), including strings, typed arrays, and objects. The API does not support transferring ownership of objects. -Advanced IPC preserves `Error.cause` once the peer has advertised support on that channel. Messages sent before that advertisement, or to an older Bun process, omit causes and retain the v14 format used by older builds. Cause-free messages always retain v14 bytes. This allows an already-running process to communicate with a child started from an updated Bun executable. In-process `structuredClone`, Worker, MessagePort, and BroadcastChannel messages preserve causes without IPC negotiation. +Advanced IPC preserves `Error.cause` once the peer has advertised v16 cause-format support on that channel. Messages sent before that advertisement, or to an older Bun process, omit causes and retain the v14 format used by older builds. The unreleased intermediate v15 capability does not enable v16 causes. Cause-free messages always retain v14 bytes. This allows an already-running process to communicate with a child started from an updated Bun executable. In-process `structuredClone`, Worker, MessagePort, and BroadcastChannel messages preserve causes without IPC negotiation. ```ts child.ts icon="/icons/typescript.svg" // send a string diff --git a/docs/runtime/nodejs-compat.mdx b/docs/runtime/nodejs-compat.mdx index c8f2b1deca3b..3b8f37106a02 100644 --- a/docs/runtime/nodejs-compat.mdx +++ b/docs/runtime/nodejs-compat.mdx @@ -315,7 +315,7 @@ Destroying an HTTP/2 session releases its TLS transport without waiting for the Map and Set serialization copies entries and ignores custom own properties, like `structuredClone`. Existing Bun records with own-property sections remain readable. -🟡 `writeHeapSnapshot`, `getHeapSnapshot`, `getHeapStatistics`, `getHeapSpaceStatistics`, `queryObjects`, `GCProfiler` and `startupSnapshot` are implemented. `queryObjects()` collects garbage and returns a count or shallow summaries of objects matching the constructor's prototype chain in the current context. The heap statistics describe JavaScriptCore's single heap, and `setFlagsFromString` ignores the flags it is given. `serialize` and `deserialize` use JavaScriptCore's wire format instead of V8's. Cause-free values retain the v14 format; Error cause graphs use v15, which older Bun builds cannot deserialize. These bytes are not interchangeable with Node.js serialization. Missing `startCpuProfile`, `startHeapProfile`, `Serializer`/`Deserializer`, `takeCoverage`/`stopCoverage` and `promiseHooks`. For profiling, use [`bun:jsc`](/project/benchmarking#javascript-heap-stats) instead. +🟡 `writeHeapSnapshot`, `getHeapSnapshot`, `getHeapStatistics`, `getHeapSpaceStatistics`, `queryObjects`, `GCProfiler` and `startupSnapshot` are implemented. `queryObjects()` collects garbage and returns a count or shallow summaries of objects matching the constructor's prototype chain in the current context. The heap statistics describe JavaScriptCore's single heap, and `setFlagsFromString` ignores the flags it is given. `serialize` and `deserialize` use JavaScriptCore's wire format instead of V8's. Cause-free values retain the v14 format; Error cause graphs use v16, which older Bun builds cannot deserialize. Readers reject v15, an unreleased intermediate format. These bytes are not interchangeable with Node.js serialization. Missing `startCpuProfile`, `startHeapProfile`, `Serializer`/`Deserializer`, `takeCoverage`/`stopCoverage` and `promiseHooks`. For profiling, use [`bun:jsc`](/project/benchmarking#javascript-heap-stats) instead. ### [`node:vm`](https://nodejs.org/api/vm.html) diff --git a/src/jsc/bindings/webcore/SerializedScriptValue.cpp b/src/jsc/bindings/webcore/SerializedScriptValue.cpp index 1a5661523b14..4eb3f2e8bac4 100644 --- a/src/jsc/bindings/webcore/SerializedScriptValue.cpp +++ b/src/jsc/bindings/webcore/SerializedScriptValue.cpp @@ -190,6 +190,7 @@ enum SerializationTag { DOMExceptionTag = 51, ResizableArrayBufferTag = 54, ErrorInstanceTag = 55, + ErrorInstanceWithCauseTag = 56, Bun__BlobTag = 254, // bun types start at 254 and decrease with each addition @@ -417,11 +418,12 @@ const uint8_t cryptoKeyOKPOpNameTagMaximumValue = 1; * Version 13. added support for ErrorInstance objects. * Version 14. Date, RegExp, Error, DOMException, CryptoKey, KeyObject, X509Certificate, * and Bun cloneable types are recorded in the object reference pool on both sides. - * Version 15. ErrorInstance records include an own data cause, traversed as part of the graph. + * Version 15. Unreleased intermediate format with inline Error cause-presence bytes; rejected. + * Version 16. A distinct ErrorInstanceWithCauseTag carries an own data cause. */ -[[maybe_unused]] static constexpr unsigned CurrentVersion = 15; +[[maybe_unused]] static constexpr unsigned CurrentVersion = 16; static constexpr unsigned DefaultVersion = 14; -static constexpr unsigned FirstVersionWithErrorCause = 15; +static constexpr unsigned FirstVersionWithErrorCause = 16; // Deserializers must not pool the version 14 terminal types for older payloads, // whose writers never counted them, or the pool indices stop matching the writer's. [[maybe_unused]] static constexpr unsigned FirstVersionWithPooledTerminals = 14; @@ -456,9 +458,9 @@ static constexpr unsigned StringDataIs8BitFlag = 0x80000000; * MapData :- ()* NonMapPropertiesTag ()* TerminatorTag * SetData :- ()* NonSetPropertiesTag ()* TerminatorTag * - * Error :- ErrorInstanceTag - * Value? - * (hasCause and its value are present only in version 15; version 14 is otherwise emitted.) + * Error :- ErrorInstanceWithCauseTag ErrorMetadata Value (version 16 only) + * ErrorMetadata :- + * * * Terminal :- * UndefinedTag @@ -486,6 +488,7 @@ static constexpr unsigned StringDataIs8BitFlag = 0x80000000; * | ArrayBuffer * | ArrayBufferViewTag ArrayBufferViewSubtag (ArrayBuffer | ObjectReference) * | CryptoKeyTag + * | ErrorInstanceTag ErrorMetadata * | DOMPoint * | DOMRect * | DOMMatrix @@ -746,8 +749,6 @@ class CloneSerializer : public CloneBase { if (serializer.m_failed) code = SerializationReturnCode::UnspecifiedError; } - if (code == SerializationReturnCode::SuccessfullyCompleted) - serializer.finishErrorCauseFormat(); serializedBlockListRefs = WTF::move(serializer.m_serializedBlockListRefs); return code; } @@ -1130,29 +1131,38 @@ class CloneSerializer : public CloneBase { code = SerializationReturnCode::DataCloneError; } - JSValue dumpError(ErrorInstance* errorInstance) + JSValue errorCause(ErrorInstance* errorInstance) { auto& vm = m_lexicalGlobalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); - JSValue cause; - bool hasCause = false; - // Snapshot and root before metadata getters/coercions can replace the cause or collect it. - // Worker error events retain their separate bounded, best-effort metadata owner. - bool supportsCause = m_context != SerializationContext::WorkerError && m_context != SerializationContext::LegacyIPC; - if (supportsCause) { + if (m_context == SerializationContext::WorkerError || m_context == SerializationContext::LegacyIPC) + return {}; + + // Unlike stack/line/column, cause has no lazy Error metadata slot. + unsigned attributes = 0; + JSValue cause = errorInstance->getDirect(vm, vm.propertyNames->cause, attributes); + if (errorInstance->classInfo() != ErrorInstance::info() || (attributes & PropertyAttribute::CustomAccessorOrValue)) [[unlikely]] { JSC::PropertyDescriptor descriptor; bool found = errorInstance->getOwnPropertyDescriptor(m_lexicalGlobalObject, vm.propertyNames->cause, descriptor); RETURN_IF_EXCEPTION(scope, JSValue()); - hasCause = found && descriptor.isDataDescriptor(); - if (hasCause) { - cause = descriptor.value(); - m_gcBuffer.appendWithCrashOnOverflow(cause); - } - } + cause = found && descriptor.isDataDescriptor() ? descriptor.value() : JSValue(); + } else if (attributes & PropertyAttribute::Accessor) + return {}; + + // Root the own data value before any Error metadata can run user code. + if (cause) + m_gcBuffer.appendWithCrashOnOverflow(cause); + return cause; + } + + bool dumpError(ErrorInstance* errorInstance, SerializationTag tag) + { + auto& vm = m_lexicalGlobalObject->vm(); + auto scope = DECLARE_THROW_SCOPE(vm); auto errorTypeValue = errorInstance->get(m_lexicalGlobalObject, vm.propertyNames->name); - RETURN_IF_EXCEPTION(scope, JSValue()); + RETURN_IF_EXCEPTION(scope, false); auto errorTypeString = errorTypeValue.toWTFString(m_lexicalGlobalObject); - RETURN_IF_EXCEPTION(scope, JSValue()); + RETURN_IF_EXCEPTION(scope, false); // .message/.line/.column/.sourceURL: HTML spec + Node/WebKit read // OWN data descriptors only (an inherited or accessor .message is @@ -1167,62 +1177,57 @@ class CloneSerializer : public CloneBase { // Symbol message from reaching ErrorInstance's lazy materialization. JSC::PropertyDescriptor d; bool found = errorInstance->getOwnPropertyDescriptor(m_lexicalGlobalObject, vm.propertyNames->message, d); - RETURN_IF_EXCEPTION(scope, JSValue()); + RETURN_IF_EXCEPTION(scope, false); if (found && d.isDataDescriptor() && d.value()) { message = d.value().toWTFString(m_lexicalGlobalObject); - RETURN_IF_EXCEPTION(scope, JSValue()); + RETURN_IF_EXCEPTION(scope, false); } } // Trigger ErrorInstance's lazy materialization up front so a throwing // prepareStackTrace propagates here instead of tripping the exception // assertion inside JSObject::getOwnPropertyDescriptor. errorInstance->materializeErrorInfoIfNeeded(vm); - RETURN_IF_EXCEPTION(scope, JSValue()); + RETURN_IF_EXCEPTION(scope, false); { JSC::PropertyDescriptor d; bool found = errorInstance->getOwnPropertyDescriptor(m_lexicalGlobalObject, vm.propertyNames->line, d); - RETURN_IF_EXCEPTION(scope, JSValue()); + RETURN_IF_EXCEPTION(scope, false); if (found && d.isDataDescriptor() && d.value().isNumber()) line = d.value().toNumber(m_lexicalGlobalObject); - RETURN_IF_EXCEPTION(scope, JSValue()); + RETURN_IF_EXCEPTION(scope, false); } { JSC::PropertyDescriptor d; bool found = errorInstance->getOwnPropertyDescriptor(m_lexicalGlobalObject, vm.propertyNames->column, d); - RETURN_IF_EXCEPTION(scope, JSValue()); + RETURN_IF_EXCEPTION(scope, false); if (found && d.isDataDescriptor() && d.value().isNumber()) column = d.value().toNumber(m_lexicalGlobalObject); - RETURN_IF_EXCEPTION(scope, JSValue()); + RETURN_IF_EXCEPTION(scope, false); } { JSC::PropertyDescriptor d; bool found = errorInstance->getOwnPropertyDescriptor(m_lexicalGlobalObject, vm.propertyNames->sourceURL, d); - RETURN_IF_EXCEPTION(scope, JSValue()); + RETURN_IF_EXCEPTION(scope, false); if (found && d.isDataDescriptor() && d.value().isString()) sourceURL = d.value().toWTFString(m_lexicalGlobalObject); - RETURN_IF_EXCEPTION(scope, JSValue()); + RETURN_IF_EXCEPTION(scope, false); } { JSValue v = errorInstance->get(m_lexicalGlobalObject, vm.propertyNames->stack); - RETURN_IF_EXCEPTION(scope, JSValue()); + RETURN_IF_EXCEPTION(scope, false); if (v.isString()) stack = v.toWTFString(m_lexicalGlobalObject); - RETURN_IF_EXCEPTION(scope, JSValue()); + RETURN_IF_EXCEPTION(scope, false); } - write(ErrorInstanceTag); + write(tag); write(errorNameToSerializableErrorType(errorTypeString)); writeNullableString(message); write(line); write(column); writeNullableString(sourceURL); writeNullableString(stack); - if (supportsCause) { - m_errorCauseOffsets.append(m_buffer.size()); - write(static_cast(hasCause)); - m_hasErrorCause |= hasCause; - } - return cause; + return true; } bool dumpIfTerminal(JSValue value, SerializationReturnCode& code) @@ -1318,8 +1323,22 @@ class CloneSerializer : public CloneBase { write(String(JSC::Yarr::flagsString(regExp->regExp()->flags()).span())); return true; } - if (obj->inherits()) - return false; + if (auto* error = dynamicDowncast(obj)) { + if (m_pendingError == error) + return false; + if (!startObjectInternal(error)) + return true; + JSValue cause = errorCause(error); + RETURN_IF_EXCEPTION(scope, false); + if (cause) { + m_pendingError = error; + m_pendingErrorCause = cause; + return false; + } + dumpError(error, ErrorInstanceTag); + RETURN_IF_EXCEPTION(scope, false); + return true; + } if (obj->inherits()) { auto index = m_transferredMessagePorts.find(obj); if (index != m_transferredMessagePorts.end()) { @@ -1698,32 +1717,6 @@ class CloneSerializer : public CloneBase { writeConstantPoolIndex(m_objectPool, i); } - void finishErrorCauseFormat() - { - if (m_hasErrorCause) { - m_buffer[0] = CurrentVersion; - return; - } - size_t removed = 0; - for (auto& reference : m_objectReferences) { - while (removed < m_errorCauseOffsets.size() && m_errorCauseOffsets[removed] < reference.offset) - ++removed; - reference.offset -= removed; - } - size_t readOffset = 0; - size_t writeOffset = 0; - for (auto offset : m_errorCauseOffsets) { - size_t length = offset - readOffset; - memmove(m_buffer.mutableSpan().data() + writeOffset, m_buffer.span().data() + readOffset, length); - writeOffset += length; - readOffset = offset + 1; - } - size_t length = m_buffer.size() - readOffset; - memmove(m_buffer.mutableSpan().data() + writeOffset, m_buffer.span().data() + readOffset, length); - m_buffer.shrink(writeOffset + length); - m_errorCauseOffsets.clear(); - } - // Retain the v14 pre-scan's Buffer order and framing. Only cause-bearing // graphs add identities discovered by the native walk. bool finishBufferEnvelope() @@ -1758,7 +1751,6 @@ class CloneSerializer : public CloneBase { fail(); return false; } - finishErrorCauseFormat(); Vector valueBytes = WTF::move(m_buffer); m_buffer = {}; write(m_hasErrorCause ? CurrentVersion : DefaultVersion); @@ -2148,7 +2140,9 @@ class CloneSerializer : public CloneBase { }; Vector m_objectReferences; Vector m_nodeBuffers; - Vector m_errorCauseOffsets; + // The dispatcher can check a nonterminal Error twice before visiting its cause. + ErrorInstance* m_pendingError { nullptr }; + JSValue m_pendingErrorCause; bool m_hasErrorCause { false }; ObjectPool m_objectPool; ObjectPool m_transferredMessagePorts; @@ -2400,12 +2394,14 @@ SerializationReturnCode CloneSerializer::serialize(JSValue in) if (inputObjectStack.size() > maximumFilterRecursion) return SerializationReturnCode::StackOverflowError; auto* error = uncheckedDowncast(inValue); - if (!startObjectInternal(error)) - break; - JSValue cause = dumpError(error); + ASSERT(m_pendingError == error); + JSValue cause = std::exchange(m_pendingErrorCause, JSValue()); + m_pendingError = nullptr; + m_hasErrorCause = true; + m_buffer[0] = CurrentVersion; + dumpError(error, ErrorInstanceWithCauseTag); RETURN_IF_EXCEPTION(scope, SerializationReturnCode::ExistingExceptionError); - if (!cause) - break; + ASSERT(cause); // Keep the Error in the same pool before traversing its cause, including self references. inputObjectStack.append(error); inValue = cause; @@ -2588,7 +2584,7 @@ class CloneDeserializer : public CloneBase { DeserializationResult deserialize(); - bool isValid() const { return m_version <= CurrentVersion; } + bool isValid() const { return m_version <= DefaultVersion || m_version == CurrentVersion; } template bool readLittleEndian(T& value) { @@ -3931,11 +3927,11 @@ class CloneDeserializer : public CloneBase { addTerminalToObjectPool(obj); return obj; } - case ErrorInstanceTag: - if (m_version < FirstVersionWithErrorCause) { - auto* error = readError(); - return error ? JSValue(error) : JSValue(); - } + case ErrorInstanceTag: { + auto* error = readError(); + return error ? JSValue(error) : JSValue(); + } + case ErrorInstanceWithCauseTag: m_ptr = preTagPtr; return JSValue(); case ObjectReferenceTag: { @@ -4352,13 +4348,6 @@ DeserializationResult CloneDeserializer::deserialize() auto* error = readError(); if (scope.exception() || !error) goto error; - uint8_t hasCause; - if (!read(hasCause) || hasCause > 1) - goto error; - if (!hasCause) { - outValue = error; - break; - } outputObjectStack.append(error); stateStack.append(ErrorEndVisitCause); goto stateUnknown; @@ -4393,7 +4382,7 @@ DeserializationResult CloneDeserializer::deserialize() goto mapObjectStartState; if (tag == SetObjectTag) goto setObjectStartState; - if (tag == ErrorInstanceTag && m_version >= FirstVersionWithErrorCause) + if (tag == ErrorInstanceWithCauseTag && m_version >= FirstVersionWithErrorCause) goto errorStartState; goto error; } diff --git a/src/runtime/ipc.rs b/src/runtime/ipc.rs index 914a69828771..781fa4ee0ac4 100644 --- a/src/runtime/ipc.rs +++ b/src/runtime/ipc.rs @@ -266,7 +266,8 @@ mod advanced { // entire hello word, so its high bits can advertise serializer capabilities. const VERSION: u32 = 2; const VERSION_MASK: u32 = 0xFFFF; - const ERROR_CAUSE_CAPABILITY: u32 = 1 << 16; + // Bit 16 identified the incompatible, intermediate v15 Error layout. + const ERROR_CAUSE_CAPABILITY: u32 = 1 << 17; pub(super) fn supports_error_cause(hello: u32) -> bool { hello & VERSION_MASK == VERSION && hello & ERROR_CAUSE_CAPABILITY != 0 diff --git a/test/js/bun/spawn/spawn.ipc.test.ts b/test/js/bun/spawn/spawn.ipc.test.ts index 10d8dd350389..281a7317e536 100644 --- a/test/js/bun/spawn/spawn.ipc.test.ts +++ b/test/js/bun/spawn/spawn.ipc.test.ts @@ -357,7 +357,7 @@ it("child with unusable NODE_CHANNEL_FD tears down IPC without crashing", async it.skipIf(isWindows)("advanced serialization advertises protocol 2 and Error.cause support", async () => { // The version packet is the first frame on the channel: - // [type=Version(1), u16 LE protocol=2, u16 LE capabilities=1]. Read it raw off fd 3 before the + // [type=Version(1), u16 LE protocol=2, u16 LE capabilities=2]. Read it raw off fd 3 before the // child's own channel machinery starts consuming the socket. await using child = Bun.spawn({ cmd: [ @@ -381,7 +381,7 @@ it.skipIf(isWindows)("advanced serialization advertises protocol 2 and Error.cau ipc() {}, }); const [stdout, exitCode] = await Promise.all([child.stdout.text(), child.exited]); - expect(JSON.parse(stdout.trim())).toEqual([1, 2, 0, 1, 0]); + expect(JSON.parse(stdout.trim())).toEqual([1, 2, 0, 2, 0]); expect(exitCode).toBe(0); }); diff --git a/test/js/node/v8/v8-serdes-buffer.test.ts b/test/js/node/v8/v8-serdes-buffer.test.ts index df24fa362778..903926c3cc7f 100644 --- a/test/js/node/v8/v8-serdes-buffer.test.ts +++ b/test/js/node/v8/v8-serdes-buffer.test.ts @@ -16,12 +16,12 @@ describe("v8 serialize/deserialize Buffer identity", () => { } }); - test("only a graph with a cause edge requires v15", () => { + test("only a graph with a cause edge requires v16", () => { const error = new Error("empty"); error.stack = "stable"; expect(v8.serialize([error, error]).readUInt32LE(0)).toBe(14); error.cause = undefined; - expect(v8.serialize([new Error("first"), error]).readUInt32LE(0)).toBe(15); + expect(v8.serialize([new Error("first"), error]).readUInt32LE(0)).toBe(16); }); test.each([new Uint8Array([1, 2]), Buffer.from([1, 2])])("serialized output is transferable: %p", input => { const serialized = v8.serialize(input); diff --git a/test/js/web/workers/structured-clone.test.ts b/test/js/web/workers/structured-clone.test.ts index 48d018a5ff83..df58e54efb9e 100644 --- a/test/js/web/workers/structured-clone.test.ts +++ b/test/js/web/workers/structured-clone.test.ts @@ -1427,6 +1427,43 @@ for (const clone of [structuredClone, jscSerializeRoundtrip, v8SerializeRoundtri expect(result.cause.cause).toEqual({ code: 42 }); }); + test("mixed Error tags preserve snapshots, terminal records, and aliases", () => { + const early = new Error("early"); + const late = new Error("late", { cause: early }); + const last = new Error("last"); + let calls = 0; + Object.defineProperty(early, "name", { + get() { + calls++; + early.cause = "added after snapshot"; + return "Error"; + }, + }); + const result = clone([early, late, last, early, late, { sentinel: 42 }]); + expect(calls).toBe(1); + expect(Object.hasOwn(result[0], "cause")).toBe(false); + expect(result[1].cause).toBe(result[0]); + expect(Object.hasOwn(result[2], "cause")).toBe(false); + expect(result[3]).toBe(result[0]); + expect(result[4]).toBe(result[1]); + expect(result[5]).toEqual({ sentinel: 42 }); + }); + + test("dictionary Error properties retain an own data cause before metadata effects", () => { + const source = new Error("dictionary"); + for (let i = 0; i < 100; i++) source[`property${i}`] = i; + for (let i = 0; i < 100; i++) delete source[`property${i}`]; + const cause = { original: true }; + Object.defineProperty(source, "cause", { value: cause, writable: true }); + Object.defineProperty(source, "name", { + get() { + source.cause = "replacement"; + return "Error"; + }, + }); + expect(clone(source).cause).toEqual({ original: true }); + }); + for (const field of ["name", "message", "stack"]) { test.each(["replace", "delete", "uncloneable"])( "cause snapshot precedes " + field + " metadata effects: %s", @@ -1614,23 +1651,25 @@ for (const [name, read] of [ const error = new Error("wire", { cause: 1 }); error.stack = ""; const bytes = Buffer.from(serialize(error)); - expect(bytes.readUInt32LE(0)).toBe(15); + expect(bytes.readUInt32LE(0)).toBe(16); expect(read(bytes).cause).toBe(1); for (let end = 4; end < bytes.length; end++) { expect(() => read(bytes.subarray(0, end))).toThrow("Unable to deserialize data."); } - // A present cause ends with the presence byte and OneTag for this primitive. - expect([...bytes.subarray(-2)]).toEqual([1, 7]); - const invalidPresence = Buffer.from(bytes); - invalidPresence[invalidPresence.length - 2] = 2; - expect(() => read(invalidPresence)).toThrow("Unable to deserialize data."); + expect(bytes[4]).toBe(56); + expect(bytes.at(-1)).toBe(7); // OneTag, directly after Error metadata. + for (const version of [14, 15]) { + const invalidVersion = Buffer.from(bytes); + invalidVersion.writeUInt32LE(version, 0); + expect(() => read(invalidVersion)).toThrow("Unable to deserialize data."); + } const invalidTag = Buffer.from(bytes); invalidTag[invalidTag.length - 1] = 255; expect(() => read(invalidTag)).toThrow("Unable to deserialize data."); const invalidReference = Buffer.concat([bytes.subarray(0, -1), Buffer.from([19, 255])]); expect(() => read(invalidReference)).toThrow("Unable to deserialize data."); const future = Buffer.from(bytes); - future.writeUInt32LE(16, 0); + future.writeUInt32LE(17, 0); expect(() => read(future)).toThrow("Unable to deserialize data."); }); }