Skip to content

fix(runtime): canary weak collections: hardening, fast path, and keys after a release - #592

Draft
edusperoni wants to merge 4 commits into
mainfrom
fix/canary-weak-collections
Draft

edusperoni wants to merge 4 commits into
mainfrom
fix/canary-weak-collections

Conversation

@edusperoni

Copy link
Copy Markdown
Collaborator

Canary-mode weak collections (#563): hardening, a fast path for keys that need no unwrap, and defined behavior after __releaseNativeCounterpart. The JS side brings over the review fixes from the Android port (NativeScript/android#2128).

weak-collections.js

  • Native methods are captured up front from primordials, uncurried, instead of super.x / NativeWeakMap.prototype.x.call resolved per call. Patching the reachable native prototype can no longer hijack them. primordials.js gains WeakMap, SymbolKeyFor, and the WeakMapPrototype{Get,Set,Has,Delete,GetOrInsert,GetOrInsertComputed} methods; the last two are guarded with typeof.
  • set/add/getOrInsert check the receiver before making a key. Before, a rejected call such as WeakMap.prototype.set.call({}, canary, 1) left a state, a key and a lifecycle token behind.
  • register(target, held, token) has length 2. Invalid targets and tokens, and target === held, go straight to the native method, so native errors apply. The receiver is probed before unwrapping.
  • getOrInsertComputed: a non-object key or non-callable callback goes to the native method. The callback gets the original key, no closure is allocated, and a throwing callback leaves no key behind.
  • WeakRef.prototype.deref skips wrap for non-objects and only allocates the keep-alive WeakRef when wrap returned a different object.
  • Non-objects skip the native unwrap.
  • Fast path: get/has/delete, WeakSet has/delete and unregister try the value as is first. They call native unwrap only on a miss, and look up again only if the key differs. set/add/getOrInsert use has(this, value) as the receiver check and skip making a key when the value is already present.
    • This is sound because a canary is a key of its own only when it can have no lifetime key, for example when its class forbids associated objects. unwrap then returns the canary too.
    • Plain JS keys and non-canary wrapper keys no longer pay a native call.

After __releaseNativeCounterpart(w)

What was keyed on a native object follows the object, not the released wrapper:

  • The release copies the object's key onto w, so map.get(w) and set.has(w) keep finding the object's entries while JS holds w. Before, they missed.
  • The key stays in the object's state. A wrapper that native code hands back later finds the same entries, and a FinalizationRegistry callback never runs while the native object is alive.
  • deref() returns undefined until native code hands the object back, and never rebuilds a wrapper on its own.
    • Before, a deref() after the release rebuilt a canary and took a new +1 on the object, so a polled WeakRef could pin an object JS had just force-released.
    • The record is marked released, and the mark is cleared when a new canary adopts the record.
  • The release path still drops the runtime's +1 unconditionally. A sole-owned object deallocates at the call, as before, even when it is a WeakMap key, a WeakSet member, a WeakRef target and registered in a FinalizationRegistry.
  • A canary released before anything keyed its object has no key to carry, so weak collections can only treat it as a plain JS key. Each such operation is now a released-object access: it counts in releasedAccesses and follows releasedObjectPolicy, firing releasednativeaccess under "report" and throwing a ReferenceError under "throw". The release marks the canary with a null key, which unwrap already reads on its miss path, so the hot paths are unchanged.

Docs

  • A new "Weak collections in canary mode" section:
    • they are subclasses;
    • a WeakRef dereferenced every frame or event can keep its object from being released;
    • keys create states, which are counted;
    • the release behavior above;
    • a prototype set later is not state.
  • The resurrections, releasedAccesses and canaryStates rows now describe what iOS counts.

Specs

  • Ported from Android: constructor entries, subclassing, no key left by a rejected call, the original key passed to getOrInsertComputed, register's signature and errors, and installed only in canary mode.

  • Release, canary only:

    • natively retained: lookups through w, the hand-back finding the earlier entries, and the registry callback waiting for the native object;
    • sole owner;
    • released-access reporting under both policies.
  • Force-release, every mode, observed through a weak NSHashTable:

    • a sole-owned object that is keyed everywhere deallocates synchronously at the release;
    • a natively retained object isn't retained again by deref()/get()/has() polling after the release.

    With main's deref() rebuild restored, the second spec fails.

Testing

2170 specs, 0 failures in canary/all, canary/extended and resurrecting/extended, and in canary/all under ASan.

- A native object's key and state are made only once the call can no
  longer fail: set, add, getOrInsert and register check their receiver
  first (WeakMap.prototype.set.call({}, canary, v) left a state and key
  behind), register leaves an invalid target or token to the native
  method, and getOrInsertComputed runs its callback with the original
  key before making the lifetime key, so a callback that throws leaves
  none. It no longer allocates a closure either.
- register keeps the native length (2) and errors: register(1, 1)
  reports the invalid target rather than target and holdings being the
  same.
- WeakRef.prototype.deref keeps the result alive for the job only when
  wrap() replaced what the native deref returned.
- The native methods are captured at startup through primordials, which
  gains WeakMap, its methods and Symbol.keyFor, instead of being
  resolved through super and the native prototype at call time.
- get, has, delete and unregister try the value as is and ask native
  code for the lifetime key only on a miss, and set, add and getOrInsert
  skip the unwrap when the value is already present: plain JS keys and
  wrappers that are not canaries no longer cost a native call. A canary
  is a key itself only when its object can have no lifetime key, and
  unwrap then returns the canary too.
…ry's object

__releaseNativeCounterpart on a live canary dropped its lifetime state,
so with the wrapper still held, map.get(w) and set.has(w) missed, and if
native code still retained the object, deref() built a new canary for
it while JS had released it.

What was keyed on the native object follows the object. Before the
release, the object's key is copied onto the released canary, so unwrap
still finds it there, and the record is marked released: wrap returns
the object's live canary once native code hands the object back (a new
canary adopts the record and clears the mark) and undefined until then,
never building a canary itself or returning the released one. The key
stays in the state, so a FinalizationRegistry callback runs only once
the object is gone and the released canary is collected.
- A section on the canary-mode weak collections: they are subclasses,
  a WeakRef dereferenced on every frame or event may keep its object
  from being released, a key creates a state counted in canaryStates,
  what was keyed on an object follows the object across a release of
  one of its wrappers, and a prototype set later is not state.
- releasedAccesses lists every use of a released wrapper it counts, and
  resurrections covers wrappers kept strong while native code owns
  their object as well as JS-extended instances.
… unkeyed

A canary released before anything keyed its native object has no key to
carry, so weak collections key it as a plain JS object that nothing
keyed on the object can find. Each weak collection operation that looks
such a wrapper up is now a released-object access: it counts in
releasedAccesses and follows releasedObjectPolicy, firing
releasednativeaccess and keeping the plain-key behavior under "report",
throwing a ReferenceError under "throw".

The release marks the canary with a null key, which unwrap already reads
on its miss path, so live canaries, other wrappers and released canaries
that carry a key are not affected.
@coderabbitai

coderabbitai Bot commented Nov 21, 2026

Copy link
Copy Markdown

Important

Draft PR not reviewed

Draft PRs are not automatically reviewed by default.

  • Trigger a manual review

To automatically review draft PRs, update your CodeRabbit configuration:

reviews:
  auto_review:
    drafts: true
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Assignees

Couldn't load assignees.