Skip to content

[JSC] A transition from a dictionary structure takes its property table instead of copying it - #874

Open
robobun wants to merge 1 commit into
mainfrom
robobun/a5aa7b8b/dictionary-delete-in-place
Open

robobun wants to merge 1 commit into
mainfrom
robobun/a5aa7b8b/dictionary-delete-in-place

Conversation

@robobun

@robobun robobun commented Oct 22, 2026 •

Copy link
Copy Markdown
Collaborator

Related to oven-sh/bun#44583

Problem

  • A delete on an object with more than 128 named properties costs O(n) and allocates a table of n entries: delete object.key0; object.key0 = i on 1000 properties runs 2278 ms per 100000 pairs, node 50 to 115 ms.
  • The object has a cacheable dictionary structure with a pinned table. A delete moves it to a new structure, and Structure::takePropertyTableOrCloneIfPinned (Structure.cpp:929) copied the table. Attribute changes, seal, freeze, preventExtensions, prototype changes, private brands and the uncacheable transition copied it too.

Fix

  • Structure::takePropertyTableFrom: every transition gets its table through it. A dictionary's table moves into the transition and is pinned there. Other pinned tables are still copied.
  • Correct because a dictionary structure belongs to one object, and nothing rebuilds a table through a dictionary after the object leaves: a dictionary has no previousID chain.
  • The dictionary is departed then (isDepartedDictionary). The DFG status computations skip it, no PropertyCondition holds or is watchable on it, and the type profiler reads the object's structure instead.
  • Verified: two new tests (the stress test fails on main with allocated 24755 bytes per iteration), about 25000 filtered run-javascriptcore-tests runs locally with the same failures as main, and the CI test lanes (every mode of the runner).

Background

  • Most structures share one property table along a chain of transitions and rebuild it when the GC clears it. A dictionary owns a pinned table and has no chain. A cacheable dictionary keeps inline caches valid by changing structure on a delete. A status computation is how the DFG reads those caches.
  • Considered converting the object to an uncacheable dictionary on the first delete (V8's dictionary mode, 50 ms). It needs a new structure bit to spare the global object, and after one flatten a second delete leaves every read on the generic path for good.

Downsides

  • Each delete on a dictionary still allocates a Structure cell: 160 bytes, 0.8 us per delete plus re-add. Objects with 100 properties are unchanged: 265 ms on main, 264 ms here per 1000000 pairs (noise about 20%).
  • Inline-cached reads after deletes, bare global reads after delete globalThis.x, and a read site the DFG compiles after a delete: same as main (Notes).
  • Text grows by 348 bytes over six object files (size). The common transition path gets one isDictionary() test.
Notes

History. This is #803 again, rebased onto d6375c7, the commit Bun's main pins, so that Bun can pin the preview build of this PR as it is. #803 was closed by an automated sweep while it waited for review, and its head commit had lost its parent in a shallow checkout, so it cannot be reopened. The diff, the review replies and the measurements are the ones of #803.

Measurements. Release jsc shell on Linux x64, this branch against its base 5d2ceba, interleaved, 3 to 5 runs each, medians. Times from $vm.monotonicTimeNow(), bytes from $vm.heapTotalBytesAllocated(), which counts a 16 KB block when it is taken, so it is an average over many iterations.

loop main this PR
delete + re-add, 1000 properties, 100000 pairs 2278 ms 78 ms
same, JIT off 3471 ms 84 ms
delete + re-add, 2000 properties, 100000 pairs 4987 ms 105 ms
delete + re-add, 100 properties, 1000000 pairs 265 ms 264 ms
bytes allocated per delete + re-add pair, 1000 properties 25090 160
bytes allocated per add + attribute change pair, 1000 properties 46051 570
10 million reads through an IC, 200 properties, after 1 delete 77 ms 78 ms
same, after 2 deletes 69 ms 82 ms (both 51 to 87)
10 million bare global reads after delete globalThis.x 32 ms 38 ms (both 32 to 49)
10 million reads, site cached before the delete, DFG compiled after it 81 ms 83 ms

process.env. In Bun, process.env with more than 128 variables is such an object: one table per delete process.env.X with 236 variables, covered by the Bun test.

Why the per-delete cost was O(n). Structure::Structure(VM&, StructureVariant, Structure* previous) copies the dictionary kind, so the structure that removeNewPropertyTransition creates from a cacheable dictionary is a cacheable dictionary too, unpinned, with previousID set to the old one. The add that follows pins it in place. The next delete finds a pinned table and copies it again. So a delete plus re-add loop copies the table once per pair, and the GC frees one table per pair (the reporter's PropertyTable::destroy samples). Attribute changes with no add in between take the unpinned table along a growing chain and do not copy, which is why the sibling case is an attribute change after an add.

Rebase. The branch was first based on 5d2ceba and measured there. It is now rebased onto main after the upstream merge (#814); the patch applied without conflicts. The first CI run failed the new stress test in the eager-JIT, no-LLInt and collect-continuously modes: the compilers' own allocations inside the measured loops, and the delete inline cache flattening the dictionary before the chain check. The test now takes the least of several rounds, deletes with Reflect.deleteProperty in the chain check, and sizes its loops with testLoopCount. A departed structure in a PutByIdReplace cache now yields the slow status instead of NoInformation, which the DFG reads as a site that never ran (review comment).

Self-review. A review of the diff raised 8 concerns, all addressed: the transitions that pinned their table with pin() on main (seal, freeze, preventExtensions, prototype, brand, dictionary kind) cut the chain to the dictionary again, so a delete chain is released at those transitions as before ($vm.getStructureTransitionList length 1, checked in the stress test); PropertyCondition::isWatchableWhenValid no longer asserts on a property that a departed dictionary lost between its two unlocked reads on a compiler thread; the stress test covers every transition kind, the copyPropertyTableForPinning path (setPrototypeOf, $vm.toCacheableDictionary) and the one-shot transitions on fresh objects; the type profiler reads a departed structure's shape from the object, with a test; process.env is named above and covered by the Bun test.

Who could read a departed dictionary's table. GetByStatus, PutByStatus, InByStatus and ComplexGetStatus call getConcurrently on structures from inline caches and bytecode metadata: they now skip a departed structure, and without the skip they returned the slow variant for the whole access. PropertyCondition::isStillValid and the adaptive watchpoints read object()->structure(), the live one, but a compiler thread holds that pointer across the two reads of isWatchable, and the object can leave the structure in between: the second read then finds no property and the condition is not watchable, where it asserted before. The RELEASE_ASSERT(isWatchable) callers in DFGAdaptiveStructureWatchpoint and LLIntPrototypeLoadAdaptiveStructureWatchpoint run on the main thread with the live structure. TypeProfilerLog::processLogEntries reads a logged structure later on the main thread through forEachPropertyConcurrently, which does not materialize: a departed one gave an empty shape, now it uses the object's structure. The structureEnsuresValidity callers in the DFG pass structures with Concurrency::ConcurrentThread, which never materializes. ObjectPropertyConditionSet generation, presenceConditionIfConsistent and tryGetConstantProperty read live structures. The inline cache compiler calls startWatchingPropertyForReplacements with an offset, not a name. tryCacheDeleteBy and tryCachePutBy return before any table read when the old structure is a dictionary. checkOffsetConsistency runs in release builds and would crash on a table rebuilt from a dictionary with no table, so the stress run above is also a check that nothing does.

Differential runs against the base build, JIT on and off, identical output: delete and re-add with reads and collections on objects of 10 to 5000 properties, defineProperty attribute flips mixed with adds and deletes, setPrototypeOf, seal, freeze and preventExtensions from a dictionary, symbol keys and accessors, delete globalThis.x in a loop with built-in reads, inline-cached reads in optimized code across deletes, deleting every property then re-adding, private brands on a dictionary, for-in with deletes and attribute changes in the loop body, spread, Object.assign, Reflect.ownKeys, JSON.stringify.

Review. A design review weighed three places for the fix: the two sites of the symptom (delete and attribute change), the dictionary policy (convert to an uncacheable dictionary on the first delete), and the helper every transition gets its table through. It picked the helper, with the departed marker for the status layer. A self-review of the diff follows in the PR.

…le instead of copying it

A dictionary structure belongs to one object. When that object deletes a
property, changes an attribute, is sealed, frozen, made non-extensible,
gets a new prototype or a private brand, it moves to a new structure.
Structure::takePropertyTableOrCloneIfPinned and copyPropertyTableForPinning
copied the dictionary's pinned table for that transition, so each of these
operations cost O(n) in the number of properties and allocated a table of
n entries. On an object with 1000 properties, delete plus re-add ran about
25 us and allocated 25 KB per pair, 60 to 130 times slower than V8.

Nothing needs a dictionary's table after its object leaves: no structure
rebuilds a table through a dictionary, as a dictionary has no previousID
chain of its own. So Structure::takePropertyTableFrom, which every
transition now gets its table through, takes the table and pins it in the
transition, as the transition cannot rebuild it either. A delete or an
attribute change keeps its previousID and name, so that it is still
listed and counted; the other transitions cut the chain with pin() as
they did before.

The dictionary is departed after that (Structure::isDepartedDictionary):
no object has it and it has no table. An inline cache, a profile or the
type profiler log can still hold it. The status computations of the DFG
skip such a structure instead of taking the slow path for the whole
access, which keeps the compiled code for a site that saw the object
before a delete as it was. No property condition holds on it, and a
condition that found the property before the dictionary departed is not
watchable on it. The type profiler reads the shape from the object's
structure instead.

Delete plus re-add on a 1000 property object: 2278 ms to 78 ms per 100000
pairs, 25090 to 160 bytes allocated per pair (the Structure cell).
@coderabbitai

coderabbitai Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Organization UI
  • Review profile: ASSERTIVE
  • Plan: Advanced
  • Run ID: 4fb8a73d-ee2f-4bb5-9bf7-832829b452ec
📥 Commits

Reviewing files that changed from the base of the PR and between 5e3554f and 6d1e451.

📒 Files selected for processing: 10
  • JSTests/stress/dictionary-transition-takes-the-property-table.js
  • JSTests/typeProfiler/dictionary-mode-after-delete.js
  • Source/JavaScriptCore/bytecode/ComplexGetStatus.cpp
  • Source/JavaScriptCore/bytecode/GetByStatus.cpp
  • Source/JavaScriptCore/bytecode/InByStatus.cpp
  • Source/JavaScriptCore/bytecode/PropertyCondition.cpp
  • Source/JavaScriptCore/bytecode/PutByStatus.cpp
  • Source/JavaScriptCore/runtime/Structure.cpp
  • Source/JavaScriptCore/runtime/Structure.h
  • Source/JavaScriptCore/runtime/TypeProfilerLog.cpp

Included review availability: This review used your included allowance. Your plan provides up to 2 included reviews per hour; 0 remain after this review.

Walkthrough

Structure transitions now transfer property tables from dictionary structures. Bytecode status computation and type profiling account for departed dictionaries. New stress and type-profiler tests check transition behavior, allocation, property access, and recorded object types.

Changes

Dictionary transitions

Layer / File(s) Summary
Transfer property tables across structure transitions
Source/JavaScriptCore/runtime/Structure.h, Source/JavaScriptCore/runtime/Structure.cpp
Structure adds departed-dictionary detection and a property-table transfer API. Property additions, deletions, attribute changes, other transitions, and brand transitions use the transfer path.
Handle departed dictionaries in status and profiling
Source/JavaScriptCore/bytecode/*Status.cpp, Source/JavaScriptCore/bytecode/PropertyCondition.cpp, Source/JavaScriptCore/runtime/TypeProfilerLog.cpp
Bytecode status computation skips or declines information for departed-dictionary structures. Type profiling uses a cell value’s current structure when its logged structure is departed.
Validate dictionary transitions and consumers
JSTests/stress/dictionary-transition-takes-the-property-table.js, JSTests/typeProfiler/dictionary-mode-after-delete.js
Stress tests check allocation bounds, property behavior, transition-chain lengths, and inline-cache operations. The type-profiler test checks recorded types before and after deletion.

Priority: ➖ Normal

Merge Risk: ⚪ Minimal · up to 6d1e4

No confirmed issue currently blocks merging. The unresolved transition paths could not be verified and should receive attention during normal validation.

Pre-merge checks: Passed 4
Check name Status Explanation
Title check Passed The title clearly and concisely describes the main change: transitions from dictionary structures move the property table instead of copying it.
Description check Passed The description provides a detailed problem statement, fix, rationale, performance data, testing results, risks, and changed behavior. It does not include the repository template’s Bugzilla URL, revie…
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.
Full details: Description check

Explanation

The description provides a detailed problem statement, fix, rationale, performance data, testing results, risks, and changed behavior. It does not include the repository template’s Bugzilla URL, reviewer line, or explicit changed-file list, but the substantive information is mostly complete.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Warning

Git: CodeRabbit could not clone the repository, so clone-backed analysis was skipped and this review may be incomplete. Verify repository clone access, such as SSH credentials, before requesting another full review. If clone access is intentionally unavailable, use path_filters to narrow the review scope.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@github-actions

Copy link
Copy Markdown

Preview build of 6d1e451: autobuild-preview-pr-874-6d1e4515

@claude claude 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.

Findings marked 🟡 are optional suggestions and need no follow-up push.

Additional findings (outside the current diff — GitHub can't attach inline comments there):

  • 🟡 Source/JavaScriptCore/bytecode/PutByStatus.cpp — nit: a put site whose only profile is a stale LLInt cache on a departed dictionary still yields NoInformation, so the DFG emits ForceOSRExit there. The IC path at PutByStatus.cpp:188-190 deliberately returns the slow status for a departed structure for that very reason, but computeFromLLInt at PutByStatus.cpp:92-94 has no such check and getConcurrently on a departed dictionary returns invalidOffset. Fix: before the table read, return a slow status (e.g. PutByStatus(LikelyTakesSlowPath)) when structure->isDepartedDictionary(), matching the IC path, so a departed structure never produces NoInformation on either path. [also at: Source/JavaScriptCore/bytecode/GetByStatus.cpp:187 - DFG code for a get site whose LLInt cache names a departed attribute-change dictionary keeps a Simple variant on that dead structure and OSR-exits every run until the exit threshold recompiles it, while the author's own departed-dictionary skip is applied only to the IC path.]

    Why this was flagged

    A function containing object.key = v runs only in the LLInt on an object with more than 128 properties, so op_put_by_id caches a Replace on its cacheable dictionary structure. The object then deletes a property, so that structure departs. A hot caller is then DFG-compiled and inlines that function; PutByStatus::computeFor finds no stub info and falls back to computeFromLLInt (PutByStatus.cpp:155-156). At PutByStatus.cpp:92 structure->getConcurrently(uid) on the departed dictionary finds no table and no chain entry, so line 94 returns PutByStatus(NoInformation). DFGByteCodeParser.cpp:7958-7959 turns a status that is not isSet() into addToGraph(ForceOSRExit), so the compiled code exits at the site. The base branch returned a replace variant whose CheckStructure also fails on the object's new structure, so the outcome is an exit either way; the author's comment at PutByStatus.cpp:188 says this NoInformation result is what the IC path was changed to avoid, and the LLInt path was not given the same treatment.

    Verification: computeFromLLInt (PutByStatus.cpp:90-94) returns PutByStatus(NoInformation) with no isDepartedDictionary check. The DFG then hits DFGByteCodeParser.cpp:7957-7959: if (!putByStatus.isSet()) addToGraph(ForceOSRExit). The IC path at PutByStatus.cpp:188-190 avoids this by returning slowVersion(summary), so the two paths are inconsistent. The base branch also OSR-exits at that site.

  • 🟣 Source/JavaScriptCore/bytecode/InByStatus.cpp — DFG code for an in site whose polymorphic inline cache holds only departed dictionary structures now gets a Simple status with no variants, and ByteCodeParser builds a MatchStructure node with an empty structure set that exits on every execution. InByStatus::computeForPropertyInlineCacheWithoutExitSiteFeedback continues past departed structures and then falls through to the Simple result at InByStatus.cpp:207 even when every AccessCase was skipped. Fix: when the departed-dictionary skips leave zero variants, return NoInformation or TakesSlowPath (as GetByStatus does via its !numVariants guard in handleGetById) rather than an empty Simple status, for InByStatus and for the sibling PutByStatus continue at PutByStatus.cpp:239-240.

    Why this was flagged

    An x in o site runs on objects with more than 128 properties whose structures are cacheable dictionaries; each delete or defineProperty on o departs the structure, so the site's PolymorphicAccess list fills with structures no object has. When the DFG compiles, the loop over access cases in InByStatus.cpp hits the new if (structure->isDepartedDictionary()) continue for every case and reaches the Simple return at InByStatus.cpp:207 with m_variants empty. DFGByteCodeParser::handleInById calls handleInByAsMatchStructure on a Simple status and emits MatchStructure with an empty MatchStructureData, which no object matches, so the site exits on each run until the exit threshold flips it to the generic path. On the base branch the stale structures were kept as variants: the node also failed, but the base never produced an empty variant list. Remedy: return NoInformation/TakesSlowPath when all cases were skipped, in InByStatus and in the PutByStatus Replace loop at PutByStatus.cpp:239-240 which has the same shape.

    Verification: pre-existing. Trigger: an x in o site whose PolymorphicAccess list holds only cacheable-dictionary structures the object has since left when the DFG compiles that site. Source/JavaScriptCore/dfg/DFGByteCodeParser.cpp:7842-7868 accepts any Simple status and emits MatchStructure with an empty variant list. However the base already fails the same way by the same route.

Comment on lines +936 to +944
PropertyTable* Structure::takePropertyTableFromDictionary(VM& vm)
{
// This must always return a property table. It can't return null.
ASSERT(isDictionary());
ASSERT(isPinnedPropertyTable());
PropertyTable* result = propertyTableOrNull();
if (result) {
if (isPinnedPropertyTable())
return result->copy(vm, result->size() + 1);
ASSERT(result);
ConcurrentJSLocker locker(m_lock);
setIsPinnedPropertyTable(false);
setPropertyTable(vm, nullptr);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔴 Memory safety: JSON.stringify can read freed memory after merging when a replacer or getter deletes properties from a serialized object that has more than 128 properties. The Holder in JSONObject.cpp:550 caches raw UniquedStringImpl* from the table and relies on the retained Structure (JSONObject.cpp:459) to keep them alive; Structure.cpp:944 now empties that structure's table on a delete, so the moved table's take() drops the key's last reference. Fix: a departed dictionary must keep its property names alive, or consumers that cache names across user code must hold RefPtr, or canPerformFastPropertyNameEnumerationForJSONStringifyWithSideEffect must reject dictionaries. Base copied the table, so the old structure kept every key.

Why this was flagged

An object with more than 128 named properties is a cacheable dictionary (Structure.h:215, 580-582), and JSONObject.cpp:541 admits it to the fast path because ObjectConstructorInlines.h:51 only rejects uncacheable dictionaries; Holder::appendNextProperty stores PropertyName raw pointers in m_propertiesAndOffsets (JSONObject.cpp:131, 550) and keeps only the Structure alive via m_objectStack (JSONObject.cpp:459). A replacer runs with the holder object as this (JSONObject.cpp:369), or a getter runs on it (JSONObject.cpp:623); either can run delete this["k"+i] for later keys, then add a property. Each delete goes through removeNewPropertyTransition, and takePropertyTableFrom (Structure.cpp:956) calls takePropertyTableFromDictionary, which nulls the old structure's table (Structure.cpp:944); transition->remove then calls PropertyTable::take, whose remove() does key->deref() (PropertyTable.h:411).

Verification: normal — use-after-free regression, triggered when JSON.stringify serializes an object with >128 named properties (cacheable dictionary) and a replacer or getter deletes a not-yet-serialized property, then a GC runs before the stringifier reaches that entry.

Comment on lines +22 to +24
const rounds = 5;
const iterationsPerRound = 400;
const iterations = rounds * iterationsPerRound;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 nit (optional): maintainers running the slow test configurations get a new stress test whose iteration count testLoopCount cannot reduce, against JSTests/README.md rules 1 and 2. The loops are sized by the fixed constants rounds and iterationsPerRound at JSTests/stress/dictionary-transition-takes-the-property-table.js:22-24, and the inline-cache loop uses Math.max(testLoopCount, 2000) at line 256, which only ever raises the count. Fix: let testLoopCount scale or cap every loop so the test stays under 200ms in the no-JIT, eager and collect-continuously configurations, while keeping enough iterations in the default run for the allocation bound to stay meaningful.

Why this was flagged

JSTests/CLAUDE.md imports JSTests/README.md, whose rules for new tests say they must run under 200ms in all configurations (rule 1) and must use testLoopCount to control iterations (rule 2). The new test fixes rounds = 5 and iterationsPerRound = 400 at JSTests/stress/dictionary-transition-takes-the-property-table.js:22-24, and at line 256 computes const count = Math.max(testLoopCount, 2000), so a small testLoopCount set by the jsc shell for a slow configuration never lowers the count. Lines 88-130 create 32 objects of 1000 properties for each of 9 transitions (288 objects, ~288,000 string-keyed puts) with a gc() per batch at line 93, and lines 160-270 call gc() nine more times while the keptAlive objects stay live. On the base branch this test does not exist; after merging, the slow configurations (no-LLInt, eager JIT, collect-continuously, debug) run all of that work unconditionally and can exceed the 200ms budget. No guard limits the work: testLoopCount is only used as a floor.

Verification: nit. Triggering condition: any run of the test suite in a configuration where the jsc shell lowers testLoopCount, since none of that reduction reaches the test's loops. Mechanism verified in JSTests/stress/dictionary-transition-takes-the-property-table.js: lines 22-24 hard-code const rounds = 5; const iterationsPerRound = 400; and line 256 const count = Math.max(testLoopCount, 2000); can only raise the count.

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