Repository navigation
Conversation
…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).
1bbd937 to
6d1e451
Compare
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info
WalkthroughStructure 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. ChangesDictionary transitions
Priority: ➖ Normal Merge Risk: ⚪ Minimal · up to
|
|
Preview build of 6d1e451: |
There was a problem hiding this comment.
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 aninsite 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 PutByStatuscontinueat PutByStatus.cpp:239-240.Why this was flagged
An
x in osite 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 newif (structure->isDepartedDictionary()) continuefor 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 osite 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.
| 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); |
There was a problem hiding this comment.
🔴 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.
| const rounds = 5; | ||
| const iterationsPerRound = 400; | ||
| const iterations = rounds * iterationsPerRound; |
There was a problem hiding this comment.
🟡 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.
Related to oven-sh/bun#44583
Problem
delete object.key0; object.key0 = ion 1000 properties runs 2278 ms per 100000 pairs, node 50 to 115 ms.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.previousIDchain.isDepartedDictionary). The DFG status computations skip it, noPropertyConditionholds or is watchable on it, and the type profiler reads the object's structure instead.allocated 24755 bytes per iteration), about 25000 filteredrun-javascriptcore-testsruns locally with the same failures as main, and the CI test lanes (every mode of the runner).Background
Downsides
Structurecell: 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%).delete globalThis.x, and a read site the DFG compiles after a delete: same as main (Notes).size). The common transition path gets oneisDictionary()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
jscshell 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.delete globalThis.xprocess.env. In Bun,process.envwith more than 128 variables is such an object: one table perdelete process.env.Xwith 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 thatremoveNewPropertyTransitioncreates from a cacheable dictionary is a cacheable dictionary too, unpinned, withpreviousIDset 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'sPropertyTable::destroysamples). 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.deletePropertyin the chain check, and sizes its loops withtestLoopCount. A departed structure in aPutByIdReplacecache now yields the slow status instead ofNoInformation, 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.getStructureTransitionListlength 1, checked in the stress test);PropertyCondition::isWatchableWhenValidno 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, thecopyPropertyTableForPinningpath (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.envis named above and covered by the Bun test.Who could read a departed dictionary's table.
GetByStatus,PutByStatus,InByStatusandComplexGetStatuscallgetConcurrentlyon 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::isStillValidand the adaptive watchpoints readobject()->structure(), the live one, but a compiler thread holds that pointer across the two reads ofisWatchable, 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. TheRELEASE_ASSERT(isWatchable)callers inDFGAdaptiveStructureWatchpointandLLIntPrototypeLoadAdaptiveStructureWatchpointrun on the main thread with the live structure.TypeProfilerLog::processLogEntriesreads a logged structure later on the main thread throughforEachPropertyConcurrently, which does not materialize: a departed one gave an empty shape, now it uses the object's structure. ThestructureEnsuresValiditycallers in the DFG pass structures withConcurrency::ConcurrentThread, which never materializes.ObjectPropertyConditionSetgeneration,presenceConditionIfConsistentandtryGetConstantPropertyread live structures. The inline cache compiler callsstartWatchingPropertyForReplacementswith an offset, not a name.tryCacheDeleteByandtryCachePutByreturn before any table read when the old structure is a dictionary.checkOffsetConsistencyruns 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,
definePropertyattribute flips mixed with adds and deletes,setPrototypeOf,seal,freezeandpreventExtensionsfrom a dictionary, symbol keys and accessors,delete globalThis.xin 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.