Skip to content

Bytecode cache: pack the per-function records - #515

Merged
Jarred-Sumner merged 1 commit into
mainfrom
claude/bytecode-cache-packing
Aug 25, 2026
Merged

Jarred-Sumner merged 1 commit into
mainfrom
claude/bytecode-cache-packing

Conversation

@Jarred-Sumner

@Jarred-Sumner Jarred-Sumner commented Aug 25, 2026 •

Copy link
Copy Markdown
Collaborator

Shrinks the cached bytecode format. On Claude Code's darwin-arm64 build the embedded bytecode goes from 93.7 MB to 77.9 MB (−16.9% on the pre-8c4fd563 base; −14.6% on the 20 largest chunks against current main, which already dropped jump targets); time to prompt, --help, and footprint are unchanged within noise (two release-local builds differing only in this branch).

What changed, per function:

  • Constants: one kind byte + a 4 B slot. int32 / undefined / null / booleans live in the slot; doubles and records are pointed at. Was an 8 B slot + 8 B payload per value.

  • Symbol table entries: 16 B → 8 B. The slim entry's raw offset and six flag bits fit one word.

  • Executable record: a header word with presence bits + parse mode, then only the 4 B slots that exist (construct block is used by 1.6% of functions, rare data 11%, name 64%), then the varint tail. No checksum/extent unless the payload carries checksums. 57 B → 47 B.

  • Code block record: the 16 B fixed header is gone; the record's offset in its region is in the varint tail; region size + checksum are trailer words only when checksums are on. 62 B → 51 B.

  • Expression info: 20 B header record → 4 B count + varint header with the payload inline, and the whole record is content-deduped (every async wrapper shares one).

  • Rare data: presence bits; class source as four varints.

  • Private-name environments: one set of entries per distinct environment instead of a copy in every nested function.

Two encoder modes are now explicit: BytecodeCacheChecksums and BytecodeCacheUpdatable. A payload embedded in an executable (bun --compile) has neither. Separate .jsc files keep checksums. The jsc shell's disk cache keeps both (the patchable fixed fields CachedBytecode::commitUpdates rewrites are present only in updatable records).

Record order in the payload is unchanged (bodies breadth-first, expression info in the cold tail), so nothing new is paged in at decode.

Tested: 60 JSTests/stress files round-tripped through Bun's .jsc path with output compared to an uncached run; the jsc shell's bytecode-cache-test-helper (write, then JSC_forceDiskCache) on the bytecode-cache-* tests, class-fields-bytecode-cache, and the same 60 files.

Constants: a kind byte and a 4-byte slot each; int32, undefined, null and booleans live in the slot.
Symbol table entries: the slim entry's raw offset and six flag bits in one 32-bit word.
Jump targets: varint deltas.
Executable record: a header word of presence bits, only the 4-byte slots that are used (construct block, rare data,
name, TDZ link), a varint tail, and no checksum or extent unless the payload carries checksums.
Code block record: no fixed header; the record offset is in the tail, region size and checksum only when checksums are on.
Expression info: a 4-byte count, varint header, payload inline; identical records are written once.
Rare data: presence bits; class source as varints.
Private-name environments shared across every function nested in the same class.

BytecodeCacheChecksums and BytecodeCacheUpdatable make the two encoder modes explicit: a payload embedded in an
executable (bun --compile) has neither; the jsc shell's disk cache keeps both.
@coderabbitai

coderabbitai Bot commented Aug 25, 2026 •

Copy link
Copy Markdown

Review Change Stack

Walkthrough

Changes

Bytecode cache redesign

Layer / File(s) Summary
Cache modes and decoder contracts
Source/JavaScriptCore/runtime/CachedTypes.h, Source/JavaScriptCore/runtime/CachedTypes.cpp
Adds checksum and updatability modes, decoder payload accessors, and updated encoding APIs.
Compact cached values and auxiliary records
Source/JavaScriptCore/runtime/CachedTypes.cpp
Adds compact encodings for expression data, symbols, values, jump targets, vectors, and private-name environments.
Function and code-block record layouts
Source/JavaScriptCore/runtime/CachedTypes.cpp
Reworks rare-data, function-executable, and code-block records with packed layouts, optional fields, bounded parsing, and checksum validation.
Region encoding and update integration
Source/JavaScriptCore/runtime/CachedTypes.cpp, Source/JavaScriptCore/runtime/CachedBytecode.cpp, Source/JavaScriptCore/parser/SourceCode.h, Source/JavaScriptCore/parser/UnlinkedSourceCode.h
Updates region encoding and source-code friendship. commitUpdates now checks that records are updatable before patching.
🚥 Pre-merge checks | ✅ 3 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description provides a detailed, relevant summary of the format changes, size impact, and testing. It does not follow the required template because it lacks a bug title, Bugzilla link, review stat… Add the required bug title and Bugzilla URL, include the "Reviewed by NOBODY (OOPS!)." line or actual reviewer information, explain why the change fixes the bug, and list the changed paths with relevant functions or classes.
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly identifies the main change: packing per-function bytecode-cache records.
Full details: Description check

Explanation

The description provides a detailed, relevant summary of the format changes, size impact, and testing. It does not follow the required template because it lacks a bug title, Bugzilla link, review status, and changed-file/function list.

Warning

Git: Failed to clone repository. Please run the @coderabbitai full review command to re-trigger a full review. If the issue persists, set path_filters to include or exclude specific files.


Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔇 Additional comments (31)
Source/JavaScriptCore/runtime/CachedTypes.h (2)

57-64: LGTM!

Also applies to: 73-73, 152-153


197-205: 🗄️ Data Integrity & Integration

⚠️ Unverified finding
Sandbox verification was unavailable.

Verify that no caller pairs BytecodeCacheUpdatable::No with function updates.

These three APIs now let a caller disable updatable records. CachedBytecode::commitUpdates asserts the opposite: CachedBytecodeOffsets::isUpdatable(record) is a RELEASE_ASSERT in Source/JavaScriptCore/runtime/CachedBytecode.cpp at Line 78. A payload encoded with BytecodeCacheUpdatable::No therefore crashes if it later reaches addFunctionUpdate and commitUpdates.

The defaults are Yes, so existing callers keep the old behavior. Confirm that every caller that passes BytecodeCacheUpdatable::No never feeds that payload into the update path.

Source/JavaScriptCore/runtime/CachedTypes.cpp (26)

398-442: LGTM!


492-529: LGTM!


552-569: LGTM!


792-806: LGTM!


877-879: LGTM!

Also applies to: 1054-1056, 1132-1135


1533-1552: 🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

⚠️ Unverified finding
Sandbox verification was unavailable.

Shared private-name entries escape the sharing record's checksum coverage.

encodeShared reuses element bytes that an earlier environment wrote, through m_entries.shareElements(encoder, *existing, map.size()). Those bytes sit at a lower offset than the record that shares them.

The encoder has a mechanism for exactly this case, and this path does not use it. encodeArrayForTail calls encoder.noteSharedArray(*existing, bytes.size()) at Line 2636, and CachedCodeBlock::create folds the collected spans into the region checksum through encoder.takeBlockExternalArrays() at Line 4394. On the decode side, regionIsIntact only tolerates an out-of-region array for the four arrays it passes shareable = true at Lines 3544-3547.

Trace the coverage for a shared environment inside a function-executable record:

  • CachedFunctionExecutable::encode sets *extent = encoder.currentOffset() - start at Line 4074, so the record checksum covers only [start, start + extent). Shared entries are below start.
  • CachedCodeBlock::create computes regionSize at Line 4391, before the deferred bodies write the child executable records, so the child record and its shared entries are outside the block region too.

A damaged on-disk cache can therefore pass every checksum and still decode corrupted private-name entries. Route the shared offset through noteSharedArray so the sharing record folds it into its checksum, or restrict sharing to offsets inside the current record's extent.

🔒️ Proposed fix: note the shared span so it joins the checksum
         if (auto existing = encoder.sharedPrivateNameEnvironment(hash, entries)) {
             m_entries.shareElements(encoder, *existing, map.size());
+            encoder.noteSharedArray(*existing, map.size() * sizeof(CachedPair<Key, Value>));
             return;
         }

This alone is not sufficient for a function-executable record, because addChecksum for that record does not accept external arrays. Extend CachedFunctionExecutable::encode to pass the collected spans, or keep the entries inside the record extent.

Confirm whether any enclosing checksummed region already covers these bytes before choosing a fix.


1538-1544: 🗄️ Data Integrity & Integration

⚠️ Unverified finding
Sandbox verification was unavailable.

Verify that the dedup key cannot alias across the encoder's lifetime.

The key stored in Encoder::m_sharedPrivateNameEnvironments is a sorted vector of raw const UniquedStringImpl* values plus entry bits, and the hash at Line 1543 is computed over the raw bytes of those pointers. The vector outlives the individual encodeShared call, because addSharedPrivateNameEnvironment keeps it for the whole encode.

Pointer identity is a valid content key only while every referenced UniquedStringImpl stays alive. If one is destroyed during encoding and a later allocation reuses the address, two different environments compare equal and the second one decodes the first one's private names.

Confirm that the identifiers referenced by encoded private-name environments outlive the Encoder. If that is not guaranteed, key the dedup on string contents instead of addresses.


1455-1462: LGTM!


2022-2027: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

⚠️ Unverified finding
Sandbox verification was unavailable.

Verify that payloadSizeInBytes cannot wrap for corrupt counts.

chapters and extensions come from varints in the record, and encodedInfo comes from m_numberOfEncodedInfo. All three are attacker-free but corruption-controlled, and each can reach 0xffffffff. payloadBytes then feeds the only bounds check at Line 2026.

If ExpressionInfo::payloadSizeInBytes computes in 32-bit arithmetic, a large chapters or extensions wraps to a small payloadBytes. payloadContains(base, total) then passes, and createBorrowed(chapters, encodedInfo, extensions, words) at Line 2038 keeps the large counts. Later reads of the borrowed table walk past the payload.

The checksum path closes this, but verifiesChecksums() returns false when Options::verifyBytecodeCacheChecksums() is off, and the persistent payload never carries checksums. Confirm the arithmetic width, and add an explicit chapters/extensions sanity bound against the remaining payload size if it is 32-bit.


1976-2021: LGTM!

Also applies to: 2028-2048


2203-2225: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

⚠️ Unverified finding
Sandbox verification was unavailable.

Promote the round-trip invariant to a release check, and mind the sign asymmetry.

The release guard at Line 2208 only proves that rawOffset survives a 32-bit shift round trip. It does not prove that unpack() reproduces bits. The debug ASSERT at Line 2210 states the invariant that actually matters.

The two directions are not symmetric for a negative rawOffset:

  • encode derives rawOffset with an arithmetic shift of intptr_t bits, so a negative bits yields a negative rawOffset.
  • unpack reads it back through unsigned rawOffset = static_cast<unsigned>(m_bits >> FlagBits), then widens with static_cast<intptr_t>(rawOffset). That widening zero-extends, so every bit above 31 + FlagBits comes back as 0 instead of 1.

The comment says offsets stay far below 2^25, so this should never trigger. Make the release build enforce that instead of assuming it. The check is one line and turns a silent wrong SymbolTableEntry into a deterministic failure.

🛡️ Proposed fix: check the real invariant in release builds
         intptr_t bits = symbolTableEntry.bits() | SymbolTableEntry::SlimFlag;
         int32_t rawOffset = static_cast<int32_t>(bits >> SymbolTableEntry::FlagBits);
-        RELEASE_ASSERT((rawOffset << SymbolTableEntry::FlagBits) >> SymbolTableEntry::FlagBits == rawOffset);
         m_bits = (rawOffset << SymbolTableEntry::FlagBits) | static_cast<int32_t>(bits & ((1 << SymbolTableEntry::FlagBits) - 1));
-        ASSERT(unpack() == bits);
+        RELEASE_ASSERT(unpack() == bits);

Also confirm the shift semantics for the repository's C++ standard level, because rawOffset << SymbolTableEntry::FlagBits shifts a signed value that can be negative.


2290-2330: LGTM!

Also applies to: 2410-2579


2653-2684: LGTM!


3110-3118: 🗄️ Data Integrity & Integration

⚠️ Unverified finding
Sandbox verification was unavailable.

Verify that a class source is never decoded without a provider.

Line 3113 assigns source.m_provider = decoder.provider(), which is an unchecked RefPtr. If the Decoder was created without a provider, m_classSource receives a null provider while the offsets and line data are set. SourceCode::isNull() returns true in that state, so the HasClassSource bit is set but the decoded class source is unusable.

This file already treats a null provider as a reachable case. CachedStringSourceProvider::decode tests if (RefPtr<SourceProvider> provider = decoder.provider()) at Line 2806 and documents a fallback for callers that supply none.

Confirm that every path that can reach a record with HasClassSource constructs the Decoder with a provider. If it cannot be guaranteed, reject the entry instead of building a half-initialized SourceCode.


3026-3109: LGTM!

Also applies to: 3119-3142


3242-3254: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

⚠️ Unverified finding
Sandbox verification was unavailable.

Add static assertions for the packed-layout assumptions.

slotBytes encodes three unasserted assumptions that the record layout depends on:

  1. sizeof(CachedFunctionExecutableMetadata) is a multiple of 4. encode places the metadata first at Line 4037, then the checksum and extent words. If the metadata size is not a multiple of 4, every following slot is misaligned, and *v.extent at Line 3237 becomes an unaligned uint32_t read. CachedFunctionExecutableOffsets::checksumOffset() at Line 3271 depends on the same property.
  2. Each of the five optional slots is exactly 4 bytes. The loop adds sizeof(uint32_t) per bit, while view() advances by sizeof(T) for CodeBlockSlot, CachedIdentifier, CachedRefPtr<CachedTDZEnvironmentLink>, and CachedPtr<CachedFunctionExecutableRareData>. A future member added to any of those types desynchronizes tailSize from view() silently.
  3. SourceParseMode fits in 8 bits. headerFor shifts it by ParseModeShift at Line 3914 and view() masks it with 0xff at Line 3990. A mode value above 255 decodes as a different parse mode.

Assertions make each of these a build failure instead of a silent format break.

🛡️ Proposed fix: assert the layout invariants
     static Vector<uint8_t, 64> packedTail(const UnlinkedFunctionExecutable&);
     static void packScalars(const UnlinkedFunctionExecutable&, VarintWriter&);
+
+    static_assert(!(sizeof(CachedFunctionExecutableMetadata) % sizeof(uint32_t)),
+        "the metadata slot must keep the following 4-byte slots aligned");
+    static_assert(sizeof(CodeBlockSlot) == sizeof(uint32_t));
+    static_assert(sizeof(CachedIdentifier) == sizeof(uint32_t));
+    static_assert(sizeof(CachedRefPtr<CachedTDZEnvironmentLink>) == sizeof(uint32_t));
+    static_assert(sizeof(CachedPtr<CachedFunctionExecutableRareData>) == sizeof(uint32_t));

Add a range check for the parse mode in headerFor:

     uint32_t header = static_cast<uint32_t>(executable.m_sourceParseMode) << ParseModeShift;
+    RELEASE_ASSERT(static_cast<uint32_t>(executable.m_sourceParseMode) <= 0xff);

Confirm the current size of CachedFunctionExecutableMetadata and the highest SourceParseMode value.


3151-3241: LGTM!

Also applies to: 3255-3302


3394-3417: LGTM!

Also applies to: 3445-3559


3763-3775: LGTM!

Also applies to: 4225-4252, 4303-4303


3882-4015: LGTM!


4020-4082: LGTM!


4141-4163: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

⚠️ Unverified finding
Sandbox verification was unavailable.

The code block offsets stay unassigned when the header selects neither slot.

m_cachedCodeBlockForCallOffset and m_cachedCodeBlockForConstructOffset are written only by checkBounds, and checkBounds runs only inside the if at Line 4156. m_decoder is assigned only in that same block.

The new header-selected layout makes "neither slot present" reachable. headerFor sets HasCallSlot and HasConstructSlot only when the corresponding code block exists, unless Updatable forces both. So a non-updatable record for an executable with no compiled code block has v.call == nullptr and v.construct == nullptr, the condition at Line 4156 is false, and all three members keep their pre-constructor contents. The constructor initializer list at Lines 4096-4102 does not cover them.

The fix is to give them a defined value on every path.

🐛 Proposed fix: initialize the offsets unconditionally
+    m_cachedCodeBlockForCallOffset = 0;
+    m_cachedCodeBlockForConstructOffset = 0;
+    m_decoder = nullptr;
     if ((v.call && !v.call->isEmpty()) || (v.construct && !v.construct->isEmpty())) {
         checkBounds(m_cachedCodeBlockForCallOffset, v.call);
         checkBounds(m_cachedCodeBlockForConstructOffset, v.construct);
         if (m_isCached)
             m_decoder = &decoder;
-        else
-            m_decoder = nullptr;
     }

Confirm whether the three members carry default member initializers. If they do, this is redundant rather than a defect.


4096-4140: LGTM!


4356-4370: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

⚠️ Unverified finding
Sandbox verification was unavailable.

The predicted record size understates the real size, so the placement assertion can fire.

probe is copied from layout at Line 4359, before layout.recordOffsetInRegion is assigned at Line 4364. packLayout writes that field as a varint at Line 4225. So the two passes disagree:

  • probeWriter encodes recordOffsetInRegion == 0, which is 1 byte.
  • writer at Line 4366 encodes the real offset. Any region larger than 127 bytes needs 2 to 5 bytes.

predictOffset returns an offset that does not depend on the requested size, except through the page capacity test at Line 796. The prediction is therefore correct until the record straddles the end of the current page: the understated probe size fits, the real size does not, malloc moves to a fresh page, and RELEASE_ASSERT(result.offset() - regionStart == layout.recordOffsetInRegion) at Line 4370 fails. The encoder aborts while writing the cache.

The value being predicted feeds back into the size of the thing being predicted, so the current form has no fixed point. Break the dependency by making the tail size independent of the offset value.

🐛 Proposed fix: reserve the maximum varint width in the probe
     {
         Layout probe = layout;
+        // packLayout writes recordOffsetInRegion as a varint, so the probe must not
+        // assume the 1-byte encoding of 0; reserve the widest encoding instead.
+        probe.recordOffsetInRegion = std::numeric_limits<uint32_t>::max();
         VarintWriter probeWriter;
         packLayout(probe, probeWriter);
         packScalars(codeBlock, probeWriter);
         ptrdiff_t predicted = encoder.predictOffset(sizeof(Record) + probeWriter.size() + ((layout.flags & LayoutHasChecksum) ? 2 * sizeof(uint32_t) : 0), alignof(Record));
         layout.recordOffsetInRegion = safeCast<uint32_t>(predicted - regionStart);
     }

This over-reserves by up to 4 bytes, so the real allocation always fits wherever the probe said it would. Writing the field as a fixed-width uint32_t instead of a varint would remove the coupling entirely.

Confirm the failure by forcing the record to land near a page boundary.


4334-4355: LGTM!

Also applies to: 4371-4396


4629-4670: LGTM!

Source/JavaScriptCore/parser/SourceCode.h (1)

37-37: LGTM!

Source/JavaScriptCore/parser/UnlinkedSourceCode.h (1)

39-39: LGTM!

Source/JavaScriptCore/runtime/CachedBytecode.cpp (1)

78-78: LGTM!


ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: c81b4a22-ac8a-4f9f-813f-f53436d6156d

📥 Commits

Reviewing files that changed from the base of the PR and between cb61607 and bd4761862f2b28e231b86fa0268f0ac193edf443.

📒 Files selected for processing (5)
  • Source/JavaScriptCore/parser/SourceCode.h
  • Source/JavaScriptCore/parser/UnlinkedSourceCode.h
  • Source/JavaScriptCore/runtime/CachedBytecode.cpp
  • Source/JavaScriptCore/runtime/CachedTypes.cpp
  • Source/JavaScriptCore/runtime/CachedTypes.h

Included review availability: 0 reviews are currently available. Your included PR review attempts over the past 7 days set your current allowance at 1 review per hour.

Comment on lines +1538 to +1543
Vector<std::pair<const UniquedStringImpl*, uint16_t>> entries;
entries.reserveInitialCapacity(map.size());
for (const auto& it : map)
entries.append({ it.key.get(), it.value.bits() });
std::sort(entries.begin(), entries.end());
unsigned hash = StringHasher::computeHashAndMaskTop8Bits(std::span { std::bit_cast<const uint8_t*>(entries.span().data()), entries.size() * sizeof(entries[0]) });

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 The hash in encodeShared is computed over the raw bytes of Vector<std::pair<const UniquedStringImpl*, uint16_t>>, but on 64-bit that pair is 16 bytes with 6 bytes of tail padding that Vector::append leaves as unzeroed allocator garbage. StringHasher therefore reads indeterminate bytes (UB, will trip MSAN), and since sharedPrivateNameEnvironment() gates on hash equality first, identical environments almost never match — the private-name-environment sharing this PR advertises is silently defeated. Fix by hashing the members explicitly (e.g. combine each entry's pointer bits and uint16_t) or by using a padding-free key type.

Extended reasoning...

What the bug is

CachedHashMap::encodeShared builds a Vector<std::pair<const UniquedStringImpl*, uint16_t>> of the private-name environment's entries, sorts it, and then hashes the vector's raw storage:

unsigned hash = StringHasher::computeHashAndMaskTop8Bits(
    std::span { std::bit_cast<const uint8_t*>(entries.span().data()),
                entries.size() * sizeof(entries[0]) });

On 64-bit platforms sizeof(std::pair<const UniquedStringImpl*, uint16_t>) == 16: an 8-byte pointer, a 2-byte uint16_t, and 6 bytes of tail padding to satisfy the pointer's 8-byte alignment. Those 6 padding bytes per element are indeterminate, and StringHasher reads all of them.

Why the padding is indeterminate

std::pair has user-declared constructors, so entries.append({ it.key.get(), it.value.bits() }) invokes pair(const T1&, const T2&) — this member-initializes first and second only and does not zero padding (unlike aggregate value-initialization). Vector::reserveInitialCapacity allocates via fastMalloc without zeroing, and Vector::append placement-news into that raw storage (new (NotNull, end()) T(std::forward<U>(value))), invoking the pair's move constructor which again copies only first/second. std::sort then shuffles elements via move-assignment, which is likewise memberwise. So every element's 6 tail-padding bytes remain whatever the allocator returned.

Step-by-step proof

  1. A class C with private field #x has two nested methods; both carry the same m_parentPrivateNameEnvironment (one entry: #x → bits).
  2. Encoding the first method's rare data calls encodeShared. It builds entries in a fresh Vector whose 16-byte slot has, say, padding bytes AA AA AA AA AA AA from the allocator. StringHasher folds those into hash₁. No prior environment is registered, so it encodes and calls addSharedPrivateNameEnvironment(hash₁, entries, offset).
  3. Encoding the second method builds a new entries Vector in freshly allocated storage whose padding happens to be BB BB BB BB BB BB. Same pointer, same bits, but StringHasher produces hash₂ ≠ hash₁.
  4. encoder.sharedPrivateNameEnvironment(hash₂, entries) iterates the shared list; the only entry has shared.hash == hash₁, so shared.hash == hash fails and the memberwise shared.entries == entries (which would match) is never reached. It returns nullopt.
  5. The second method re-encodes the environment from scratch. The dedup never happens.

Why nothing prevents it

The equality fallback shared.entries == entries uses std::pair::operator==, which compares members not bytes — so it would catch identical environments — but it is guarded by shared.hash == hash &&, and the hash mismatch short-circuits it. Decode is unaffected: each environment is simply written independently and each decodes correctly. The bug is (a) reading indeterminate bytes is UB per [basic.indet] and will be flagged by MSAN/Valgrind in CI, and (b) the "one set of entries per distinct environment" size win the PR description lists is silently lost.

Impact

  • Sanitizer builds fail: MSAN will report a use-of-uninitialized-value in StringHasher::computeHashAndMaskTop8Bits on any encode of a class with private names.
  • Stated feature doesn't work: private-name environments are re-encoded per nested function, exactly what this PR set out to remove. No incorrect decode, just no size win from this item.

Fix

Hash the meaningful bytes only, e.g.:

StringHasher hasher;
for (auto& e : entries) {
    auto p = std::bit_cast<uintptr_t>(e.first);
    hasher.addCharacters(std::bit_cast<const uint8_t*>(&p), sizeof(p));
    hasher.addCharacters(std::bit_cast<const uint8_t*>(&e.second), sizeof(e.second));
}
unsigned hash = hasher.hashWithTop8BitsMasked();

or store the key as a padding-free struct (struct { uintptr_t ptr; uintptr_t bits; }), or memset the reserved storage before appending.

Comment on lines +4358 to +4370
{
Layout probe = layout;
VarintWriter probeWriter;
packLayout(probe, probeWriter);
packScalars(codeBlock, probeWriter);
ptrdiff_t predicted = encoder.predictOffset(sizeof(Record) + probeWriter.size() + ((layout.flags & LayoutHasChecksum) ? 2 * sizeof(uint32_t) : 0), alignof(Record));
layout.recordOffsetInRegion = safeCast<uint32_t>(predicted - regionStart);
}
packLayout(layout, writer);
packScalars(codeBlock, writer);
auto result = encoder.malloc(sizeof(Record) + writer.size(), alignof(Record));
size_t trailerBytes = (layout.flags & LayoutHasChecksum) ? 2 * sizeof(uint32_t) : 0;
auto result = encoder.malloc(sizeof(Record) + writer.size() + trailerBytes, alignof(Record));
RELEASE_ASSERT(result.offset() - regionStart == layout.recordOffsetInRegion);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 The probe layout at line 4359 is copied while recordOffsetInRegion is still 0, so packLayout(probe, ...) writes a 1-byte varint for it, but after line 4364 sets the real offset (typically ≥128), packLayout(layout, ...) writes 2–5 bytes — so writer.size() > probeWriter.size(). When the probe size fits the current encoder page but the real size does not, encoder.malloc() spills to a new page and the RELEASE_ASSERT at line 4370 crashes the encoder. Fix by iterating the prediction to a fixed point (re-probe with the predicted offset until the size stabilizes) or by writing recordOffsetInRegion as a fixed-width field.

Extended reasoning...

What the bug is

CachedCodeBlock<CodeBlockType>::create() now varint-encodes the record's offset within its region into the tail via packLayout(), which calls writer.u32(layout.recordOffsetInRegion). To place the record, the code first packs a probe layout to measure the tail size, calls encoder.predictOffset(probeSize), stores the predicted offset into layout.recordOffsetInRegion, then packs the real layout and calls encoder.malloc(realSize), asserting that the actual allocation offset matches the prediction.

The problem is that Layout probe = layout; (line 4359) copies layout while layout.recordOffsetInRegion is still its default 0. VarintWriter::u32(0) emits 1 byte. After the prediction, layout.recordOffsetInRegion is set to predicted - regionStart — the total bytes of every array written before the record (instructions, constants, identifiers, jump targets, function slots, extras). For any non-trivial function that is easily ≥128 bytes, so the real packLayout emits 2–5 bytes for it. Consequently writer.size() > probeWriter.size() for essentially every code block, and the comment "the tail is fixed-size for a given layout" is not true — recordOffsetInRegion is itself part of the varint tail and its width depends on its own value.

The code path that triggers it

Encoder::predictOffset(size, align) returns m_baseOffset + roundUp(align, m_offset) when Page::canMalloc(size) succeeds, and the aligned end-of-page otherwise. Encoder::malloc(size, align) returns the same in-page offset when canMalloc succeeds, but calls allocateNewPage() (which alignEnd()s to alignof(std::max_align_t) and starts a fresh page) when it does not.

canMalloc's returned offset is independent of size, so as long as both the probe size and the real size fit in the current page, prediction and allocation agree and the assert passes. But when the probe size fits the remaining page space and the real (larger) size does not, predictOffset returns an in-page offset while malloc spills to the next page. result.offset() - regionStart then differs from layout.recordOffsetInRegion and RELEASE_ASSERT at line 4370 aborts the process.

Why nothing else prevents it

There is no fixed-point iteration: the probe is packed exactly once with recordOffsetInRegion = 0. The trailer bytes and packScalars are identical between probe and real, so the only delta is the varint width of recordOffsetInRegion. Nothing pads the probe to account for this, and nothing retries the prediction after the real size is known.

Step-by-step example

Take a function whose arrays (instructions + constants + identifiers + …) occupy 500 bytes before the record, so recordOffsetInRegion will be ~500 → u32(500) = 2 bytes. Suppose the rest of the tail is 40 bytes, sizeof(Record) = 4, trailer = 8. Probe size = 4 + (1 + 40) + 8 = 53; real size = 4 + (2 + 40) + 8 = 54. Now suppose the current encoder page has exactly 53 bytes free after 4-alignment: canMalloc(53) succeeds and predictOffset returns the in-page offset, so layout.recordOffsetInRegion is set to that offset minus regionStart. Then encoder.malloc(54) finds canMalloc(54) fails, calls allocateNewPage(), and returns an offset on the new page. result.offset() - regionStart != layout.recordOffsetInRegion → RELEASE_ASSERT crash.

Impact

Encoder pages grow geometrically (~64 KB → ~64 MB), so a large payload has on the order of 10–15 page boundaries. The failure window at each boundary is only writer.size() - probeWriter.size() bytes (1–4), so the per-build probability is low — plausibly why the 60-file test set and the 93 MB build didn't hit it. But the trigger is deterministic on content: once a given input's layout lands in the window, every encode of that input crashes. This is a production RELEASE_ASSERT in bun --compile, the jsc disk cache, and any other encodeCodeBlock caller.

How to fix

Either iterate to a fixed point — after computing predicted, re-pack the probe with the new recordOffsetInRegion and re-predict until the size stops changing (at most a couple of rounds, since varint width is monotone in value and bounded by 5) — or reserve a fixed-width slot for recordOffsetInRegion (e.g. write it as a raw 4-byte word after the varint tail, alongside the region-size/checksum trailer) so the tail really is fixed-size for a given layout.

@github-actions

Copy link
Copy Markdown

Preview Builds

Commit Release Date
b455ea5e autobuild-preview-pr-515-b455ea5e 2026-08-25 10:59:58 UTC

@Jarred-Sumner
Jarred-Sumner merged commit 45040b8 into main Aug 25, 2026
47 checks passed
dylan-conway added a commit that referenced this pull request Aug 25, 2026
…y<CachedJSValue> for the constant pool (kind bytes as head), mallocCopy for the packed ExpressionInfo bytes
Jarred-Sumner added a commit to oven-sh/bun that referenced this pull request Aug 25, 2026
… records (WebKit 1cb96a7b) (#40417)

### What does this PR do?

Two things for `--bytecode` output, plus the WebKit bump that carries
them.

**1. `--bytecode-depth <N>` / `bytecodeDepth: number`.** Bounds how many
levels of nested functions get bytecode ahead of time.

- `0` = only each module's top-level code
- `1` = top-level code plus the functions it declares directly
- omitted = all nested functions (unchanged default)

Functions past the bound are compiled from source when first called.
Lower depth means a smaller `.jsc` / executable. For a 3-level nested
test file, `.jsc` size by depth: `0` → 312 B, `1` → 2.2 KB, `2` → 5.1
KB, all → 5.4 KB. The depth applies to user chunks (CJS and ESM) and to
the internal-module bytecode embedded by `--compile --bytecode`. For CJS
output, depth counts from the module's top level, not from the
`(function(exports, require, module, ...) {})` wrapper. Invalid values
are rejected: `--bytecode-depth=nope` exits 1; `bytecodeDepth: -1 | 1.5
| "abc" | Infinity` throws.

**2. Smaller bytecode cache records** (oven-sh/WebKit#515, merged). The
per-function records in the cached bytecode format are packed, and Bun
passes the two new encoder modes:

- `--compile` payloads: no per-record checksums and no patchable
executable records (the payload is a section of the executable).
- `.jsc` files: checksums stay on.

Measured on Claude Code's darwin-arm64 build (release builds differing
only in WebKit, same source):

| | before | after |
|---|---|---|
| binary | 220.4 MB | 203.1 MB |
| bytecode embedded | 89.0 MB | 77.9 MB |
| time to prompt (median of 15) | 266 ms | 266 ms |
| `--help` (hyperfine) | 90.0 ± 1.9 ms | 89.2 ± 1.8 ms |
| footprint at prompt | 204 MB | 204 MB |

The format is versioned by the WebKit commit hash, so older `.jsc` files
are rejected and regenerated as before.

**WebKit** goes to `1cb96a7b`: the depth parameter on
`recursivelyGenerateUnlinkedCodeBlockForProgram` / `ForModuleProgram`,
#515, and #513 (CodeCache keeps blocks decoded from cached bytecode).

### How did you verify your code works?

- `test/bundler/bun-build-api.test.ts`: `bytecodeDepth` strictly
increases `.jsc` size per level, the output still runs, invalid values
throw, and the CLI flag (`--bytecode-depth=0`, `--bytecode-depth 1`, bad
value) behaves the same.
- `test/bundler/bundler_bun.test.ts`: `itBundled` with `bytecodeDepth:
0` on both the `cli` and `api` backends; output runs and the `.jsc` is
smaller than a full-depth build.
- `expectBundled` gains a `bytecodeDepth` option and now awaits
`onAfterBundle`.
- `bun-build-api.test.ts -t bytecode`, `bundler_compile.test.ts -t
bytecode`, `bundler_bun.test.ts`, `bundler_compile_splitting.test.ts`
pass on the debug build against the WebKit branch.
- 60 JSTests/stress files bundled with `--bytecode` (`.jsc`) and run
with `BUN_JSC_verboseDiskCache=1`: every one reports a cache hit and
matches the uncached output.
- All new tests fail with `USE_SYSTEM_BUN=1` and pass on the debug
build.

---------

Co-authored-by: Dylan Conway <[email protected]>
dylan-conway added a commit that referenced this pull request Aug 27, 2026
…rce ⇒ same bytes everywhere) (#505)

* [JSC] Make the bytecode cache format independent of the encoding platform

The cache is decoded by Bun executables cross-compiled for a different OS/CPU
than the one that produced it, but two things in it depended on the encoder's
C++ ABI:

- CachedMetadataTable serialized the finalized metadata offset table, whose
  entries are byte offsets computed from sizeof(Op::Metadata). Those sizes
  differ between ABIs (everything embedding CallLinkInfo is 16 bytes larger
  under MSVC), so a table encoded on Linux/macOS and linked on Windows had
  LLInt indexing past each entry. Serialize per-opcode entry counts instead
  and lay the table out again on decode via the normal finalize() path.
- CachedStringSourceProvider's Bun-only m_sourceLength sat in the base
  class's tail padding under Itanium but not under MSVC. It didn't validate
  anything SourceCodeKey doesn't already (the key compares the source hash),
  so drop it and hand back the provider being decoded against.

Also make the encoder's output a pure function of its input so it can be
compared across platforms: fixed allocation alignment and page size instead
of alignof(max_align_t)/pageSize(), zeroed pages so struct padding is not
heap garbage, string switch tables encoded in index order rather than
StringImpl-pointer hash order, and UnlinkedHandlerInfo encoded field-wise
rather than copied with 30 bits of bit-field slack.

The two allocation entry points now static_assert what the compiler can
check about a type's portability (alignment, no destructor/array cookie,
and for verbatim-copied types: no padding or bit-field slack, no
long/wchar_t/long double).

* [JSC] CachedTypes: don't reject int64_t on LP64 where it is spelled long

The verbatim-copy check rejected `long` by name to catch the LP64/LLP64
size difference, but int64_t (EncodedJSValue) is `long` under glibc. Only
reject `long` where it is the 32-bit outlier.

* [JSC] Bytecode cache: a format the decoding platform's ABI cannot disagree with

Bun embeds this cache in executables it cross-compiles, so the bytes are decoded
by a build whose OS, CPU and C++ ABI differ from the encoder's. Two things in
the format depended on the encoder:

- The metadata table was stored as offsets (lately as offset deltas), which are
  sums of this build's sizeof(Op::Metadata); anything embedding CallLinkInfo is
  16 bytes larger under MSVC, so a table written on Linux/macOS and linked on
  Windows had LLInt index past every entry. The cache now stores per-opcode
  entry counts and UnlinkedMetadataTable::layOut() -- the one function that
  turns counts into offsets, shared with finalize() -- runs on the decoding
  side (at link() for a persistent payload, as before).

- Records are placed in the payload as C++ objects, so any byte the ABI is free
  to place (tail padding Itanium reuses and MSVC does not, bit-field units MSVC
  restarts on a type change, holes after a bool/uint8_t/uint16_t member) can
  land differently. Every type now enters the Encoder through malloc<T> /
  mallocArray<T> / mallocCopy<T>, which static_assert isPortableRecord<T>():
  trivially destructible, alignment <= 8, no long/wchar_t/pointers, and
  has_unique_object_representations -- i.e. no padding and no bit-field slack,
  so the layout is fully determined by the declared field sizes. The dozen
  records that had holes get their fields reordered/widened or an explicit
  zeroed m_padding; UnlinkedHandlerInfo, VariableEnvironmentEntry,
  PrivateNameEntry and SymbolTableEntry are encoded through Cached* records
  instead of copied; CachedStringSourceProvider's Bun-only m_sourceLength is
  gone (SourceCodeKey already compares hash and length).

And the output is made a pure function of the source so that platforms can be
compared byte for byte: allocation alignment and encoder page size are
constants instead of max_align_t/pageSize(), and hash maps/sets and TDZ
environments are written in key order instead of table order (which follows
SymbolImpl's per-process hash counter, or a robin-hood table's own address).

* UnlinkedMetadataTable::layOut: Layout::end includes the 32-bit table displacement, as the table's last entry does

totalSize() of a table backed by persistent entry counts used it as-is and
under-allocated the linked buffer by s_offset32TableSize for functions large
enough to need 32-bit offsets (ASAN: heap-buffer-overflow writing
OpPutToScope::Metadata in CodeBlock::finishCreation).

* CachedStringSourceProvider: keep comparing the source length before standing in the runtime provider

Now a plain uint32_t after a base without tail padding, so both ABIs place it
at the same offset (the reason the earlier revision dropped it).

* jsc shell: bytecodeCacheFor(source, kind); stress test that two encodings of one source are identical

* layOut(): 64-bit running offset with a bound, so entry counts out of a payload cannot wrap it; EncodingOrder: order equal-content keys by symbol kind

* BytecodeGenerator: allocate an instruction's value profile indices in operand order, not argument-evaluation order

op_iterator_open, op_iterator_next, op_async_iterator_open and op_instanceof
took their two or three value-profile indices as nextValueProfileIndex()
calls in one emit() argument list, so which operand got which index was up
to the compiler's argument evaluation order: left-to-right under clang for
SysV targets, right-to-left under the MSVC ABI. The bytecode was equivalent
either way, but not byte-identical across platforms, which the bytecode
cache now promises.

* Bytecode cache: make the payload a function of the source alone

Two encodings of the same source could differ:

- hash maps/sets and TDZ environments were written in table order, which for
  SymbolImpl keys follows a per-process hash counter and for robin-hood tables
  (string switch jump tables) the table's own address; they are now written in
  key order (EncodingOrder);
- UnlinkedHandlerInfo was copied with the 30 unspecified bits next to its
  2-bit HandlerType; it is encoded field by field (CachedHandlerInfo);
- allocation alignment was alignof(std::max_align_t) and encoder pages were
  pageSize(), both of which vary by platform and show up as padding; they are
  constants;
- op_iterator_open/op_iterator_next/op_async_iterator_open/op_instanceof took
  their value-profile indices as several nextValueProfileIndex() calls in one
  argument list, so which operand got which index followed the compiler's
  argument evaluation order (reversed under the MSVC ABI); they are sequenced.

jsc shell: bytecodeCacheFor(source, kind) returns the payload as a Uint8Array;
JSTests/stress/bytecode-cache-deterministic.js encodes a corpus twice and
compares.

* Bytecode cache: no ABI-placed or unwritten bytes in records; parser: SourceProviderCache transparent to what gets encoded

Records: everything enters the Encoder through malloc<T> / mallocArray<T> /
mallocCopy<T>, which static_assert isPortableRecord<T>() -- fixed-width
scalars, no padding, no bit-field slack (has_unique_object_representations) --
so every byte in the payload is a named, initialized field and a record's
layout follows from its declaration alone. The records that had holes get
fields reordered/widened or explicit zeroed m_padding; VariableEnvironmentEntry,
PrivateNameEntry and SymbolTableEntry go through Cached* records.

Parser (from #433, plus one more case): whether a nested function's body was
skipped through the SourceProviderCache changed what the parser recorded for it
and for what follows it, and a full collection part-way through generation
could drop that cache, so the payload depended on GC timing:
- an expression-bodied arrow function's end line/column came from the token
  after the body when parsed but from the body's last token when skipped;
  both now use the last token;
- NoEvalCacheFeature for a tagged template inside a skipped body was lost;
  the cache item records and replays it;
- after skipping a body whose last token spans lines (a template literal) the
  lexer resumed on the line that token started on, so every later function's
  line numbers were short by the lines it spanned (visible in stack traces,
  not only in the cache); the cache item records where the token ended;
- recursivelyGenerateUnlinkedCodeBlock() and the builtin-executable path hold
  the provider's cache for their duration, and VM::clearSourceProviderCaches()
  keeps caches that are in use.

The stress test also runs under --collectContinuously=1 and
--useSourceProviderCache=0.

* Parser: keep m_lastTokenEndPosition out of the hot-field cache lines (verifyLayout() on ARM64 release)

* Process state that reached generated bytecode: Annex B hoisting order, registry-symbol hashes, atom width; and ** folding through libm

- Parser: sloppy-mode block function hoisting candidates were a HashMap keyed
  by FunctionMetadataNode* and iterated to declare the hoisted vars, so their
  registers / scope offsets followed arena addresses (ASLR): two runs of
  '{ function a(){} function b(){} }' inside any sloppy function encoded
  differently. Kept in declaration order now.
- SymbolImpl: registered and private symbols hashed by a process-global
  counter, so a VariableEnvironment holding computed-class-field keys (or
  builtin @NAMEs) past its inline capacity iterated -- and the generator
  assigned scope offsets -- in an order set by how many symbols the process had
  made. They hash by contents (as StaticSymbolImpl already does); plain
  Symbol() keeps the counter.
- Encoder: a Latin-1 string is written 8-bit even when this thread's atom for
  it is 16-bit because an equal 16-bit string was atomized first; and
  CachedImmutableButterfly stores indexingMode(), not the cell-lock bits that
  share its byte.
- ASTBuilder folds 'a ** b' only on operationMathPow's exact integer-exponent
  path; the other cases call the C library's pow(), which rounds differently
  across platforms, and left unfolded they get the pow() of where the code runs.
- Parser::restoreLexerState restores the last token's end line too.

Stress-test corpus gains block functions, >9 computed class fields and pow
folds; on main it encodes differently on every run.

* Scope: keep the hoisting-candidate vector out of the hot cache line (verifyLayout() on ARM64 release)

* SourceProviderCacheItem: pair the new end-position fields flag:1/value:31 like the rest of the struct

* Cache entry records the encoder's reserved callee-save locals; a decoder whose CPU reserves a different number treats the payload as foreign

BytecodeGenerator numbers a code block's locals after the LLInt/baseline
callee-save area, whose size comes from the encoding CPU's register set. It is
4 registers on x86-64 and arm64 alike, which is what makes payloads
interchangeable between them; this makes that dependency explicit instead of
coincidental.

* Reduce this branch to the portability change alone

Cross-decoding needs exactly two things, and this branch is now only those:

- records placed in the payload have one layout under every ABI: everything
  enters the Encoder through malloc<T>/mallocArray<T>/mallocCopy<T>, which
  static_assert isPortableRecord<T>() (fixed-width scalars, no padding, no
  bit-field slack), and the records that had holes are corrected;
- the metadata table is stored as per-opcode entry counts, and
  UnlinkedMetadataTable::layOut() computes offsets on the decoding side,
  because sizeof(Op::Metadata) belongs to the decoder.

Plus the cache entry recording the encoder's reserved callee-save locals.

The determinism work (hash-table order, encoder constants, parser /
SourceProviderCache, symbol hashing, Annex B order, ** folding, the jsc test)
moves out to #505; none of it is required for a payload to decode correctly on
another platform.

* Metadata portability as the smallest change to main's steps: a step carries an entry count

Keep UnlinkedMetadataTable and CachedMetadataSteps exactly as on main except:
- a step is (opcode << 24 | entry count) instead of (index << 24 | offset delta);
- expandSteps() lays counts out with this build's metadataSize()/metadataAlignment(),
  the same loop finalize() runs, and returns the end offset (so totalSize() and
  the 16/32-bit decision come from it instead of from the encoder);
- CachedMetadataSteps::compute() is finalize()'s inverse, checked against the
  original table in debug builds.
finalize() itself is untouched.

* Rework on top of the WebKit upgrade as the additive form

CachedTypes.cpp starts again from main and only adds: isPortableRecord<T>() and a
static_assert of it in each of main's existing typed entry points into the
payload (Encoder::malloc<T>/mallocFor<T>, VariableLengthObject::allocate<T>/
allocateFor<T>, the trivially-copyable CachedArray/CachedVector paths,
encodeArrayForTail<T>); the padding/widening those asserts demand in the
records that fail them; CachedMetadataSteps as (opcode, count); the callee-save
check in GenericCacheEntry. Encoder's allocation API is main's, unchanged.

* CachedHashMap::encode: sort entries by reference now that values may be move-only (merge with main's encodeRange)

* CachedPair spells out its own padding, so the entry wrapper records (and the VariableEnvironment.h friend) go away

CachedPair<First, Second> gets explicit, zero-cost-when-empty padding members
sized from First/Second, which makes every pair padding-free regardless of the
value type; VariableEnvironmentEntry, PrivateNameEntry and SymbolTableEntry are
stored as on main again.

* Encoder: the untyped allocation is private; records reach a page only through the checked malloc<T>/mallocFor<T>/mallocArray<T>

That check then covers the program/module code block records (allocated raw
before), whose CachedVariableEnvironment had two padding bytes after its bools.

* Route #515's two new allocations through the checked path: mallocArray<CachedJSValue> for the constant pool (kind bytes as head), mallocCopy for the packed ExpressionInfo bytes

* Restore this branch's parser/generator/SymbolImpl/test changes after merging the portability branch (whose reduction commit had reverted them here)

* Fold non-integer ** only when not generating for a bytecode cache

CodeGenerationMode::BytecodeCache is set by recursivelyGenerateUnlinkedCodeBlockFor*
(what every cache producer goes through) and now reaches the Parser/ASTBuilder
alongside the other code-generation modes; makePowNode consults it. Ordinary
parsing folds exactly as before. SourceCodeKey ignores the bit, so a block
generated for a cache serves any request for that source.

* isPortableRecord: also reject polymorphic types (a vptr is a pointer into this process)

* Review: keep CodeGenerationMode::BytecodeCache out of UnlinkedCodeBlock (Bun compares a precompiled block's mode with the global's); content-hash registered symbols only

* mallocPlaced: predict a fresh page's base with encoderMaxAlignment, which is what alignEnd() rounds to

* Reduce to the metadata table fix

Drop the layout rule (isPortableRecord, the typed allocators, the struct
padding changes): the records lay out the same on every 64-bit target we
build for today, and Bun's cross-platform golden-hash test is what catches a
future divergence. What remains is the one thing that is actually different
across ABIs -- the metadata table's offsets, computed from the encoder's
sizeof(Op::Metadata) -- now stored as per-opcode entry counts and laid out
by the decoder, plus the callee-save-locals check in the entry.

* Private-name environment sharing: hash the entries' values, not their bytes (the pairs have padding), so equal environments are always shared

* CachedMetadataSteps: refuse an entry count that does not fit the step word in release builds too

* Shape: only re-create a 16-bit string as 8-bit when it actually is all Latin-1 (no copy of genuine 16-bit strings)

* Private-name environment sharing: compare the (name, bits) pairs, not their bytes

Vector<std::pair<const UniquedStringImpl*, uint16_t>>::operator== compares
with memcmp (both halves are 'simple' types), and each pair carries six
bytes of padding whose contents depend on the allocator and on how the
compiler stores the pair. Two identical environments then compared unequal
on some machines and equal on others, so whether a nested function's
parent private-name environment was shared with the previous identical one
-- and with it the payload's size -- varied from machine to machine for
the same source. Compare with std::ranges::equal (pair::operator==).

* Build: check that the bytecode cache's records are laid out identically on every platform

A payload encoded on one platform is decoded in place on another (bun build
--compile cross-compiles), so every record CachedTypes.cpp writes must have
the same size, alignment and member offsets under the Itanium and Microsoft
C++ ABIs and on every architecture. Nothing enforced that; it happens to hold.

Tools/Scripts/dump-bytecode-cache-layout.py recompiles the translation unit
containing runtime/CachedTypes.cpp with -fdump-record-layouts and prints, in
a target-independent spelling, the layout of every record that ends up in a
payload: everything deriving from CachedObject<> / VariableLengthObjectBase,
the cache entry headers, and the value types those hold or store in their
tails (following members, bases and Cached containers' element types, but
not CachedObject<T>'s T, the in-memory source type). The linux, musl, macos
and windows images write it next to the libraries as bytecode-cache-layout.txt
(~3 s), and the release job diffs every platform's copy against linux-amd64
before publishing.

* dump-bytecode-cache-layout: TypeScript (bun where the image has it, node --experimental-strip-types elsewhere) instead of Python

* Review: keep program var declarations in source order in the payload (InlineMap is not sorted; its order is already deterministic); registered symbols hash purely by contents; Annex B candidates are a plain Vector; EncodingOrder is a bool less + std::sort; private-name environments hash with computeHash; SourceProviderCacheItem's new fields appended instead of reordering; shorter comments; <ranges> with the other system includes; static_assert against encoderMaxAlignment; stress test plans named; layout check fails on a missing dump and covers the freebsd and android images too

* Annex B candidates: KeyValuePair elements, so the two loops over them read as before

* Scope: hoisting-candidate Vector takes the old map's slot (+ m_closedVariableCandidates') so m_lexicalVariables stays at the cache line on ARM64

* SymbolImpl: content hash only for the private registry's symbols (the parser's synthetic names); Symbol.for() keeps the counter

* RegisteredSymbolImpl::createPrivate: take the hash from the registry string (already computed by the lookup) instead of rehashing; SymbolImpl's constructors are as upstream again

* ASTBuilder: for a bytecode cache, do not fold number ** number at all (MathCommon untouched)

* Drop CodeGenerationMode::BytecodeCache: number ** number folds as upstream; the cross-platform comparison simply avoids literal non-integer exponents (ParserModes.h, ASTBuilder.h, UnlinkedFunctionExecutable.cpp, UnlinkedCodeBlock.cpp back to upstream)

* Drop the SourceProviderCache pinning (VM.cpp, CodeCache.cpp back to upstream): with the parse/skip divergences fixed, dropping caches on a full GC no longer changes the output -- verified under --collectContinuously and a 32 KB max heap on the corpus and typescript.js

* dump-bytecode-cache-layout: only unescape \" and \\ inside quoted arguments

* UnlinkedMetadataTable: an explicit m_isBackedBySteps bit instead of testing m_steps for null (a value-profile-only table has zero steps)

* dump-bytecode-cache-layout: follow only a Cached container's element arguments (clang-cl lays out more records in this TU; pointer-like templates' arguments dragged GC types into the Windows dump)

* dump-bytecode-cache-layout: don't refer to the global Record<> (shadowed by the local type)

* CI: skip the cross-platform layout comparison step for now (it re-reads every tarball); the per-image dumps stay
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant