Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
99 changes: 99 additions & 0 deletions changelog.d/7927-thenable-probe-fast-negative.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
### perf(runtime): answer the promise-assimilation `then` probe without a property lookup

Resolving a promise with an **object** cost **+78.5 % instructions** versus
resolving with a **number** on byte-identical promise/microtask/closure
topology. The only differing counter was `thenable_probe`: 0 vs 24 000. The
cost is ECMA-262 27.2.1.3.2's `Get(resolution, "then")`, which every promise
resolution performs and which — for a plain object — answers `undefined` after
a `setjmp` exception frame, a re-intern of the literal `"then"`
(`js_string_from_bytes` + `core::str::from_utf8`), the fully generic dynamic
getter's preamble, a linear own-key scan with a `js_string_key_matches` per
key, and a recursive `js_object_get_field_by_name` walk into
`Object.prototype` for the miss. Roughly 72 000 times on
`gc-handoff/apps/asyncpipe.ts`, answering `undefined` every time — about 9 % of
that program (`gc-handoff/ASYNC2-NOTES.md` §4).

`crates/perry-runtime/src/promise/then_probe.rs` answers that probe directly
when — and only when — it can prove the answer. Both `get_then_action` (the
`Promise.resolve` / spec-resolve path) and `assimilate_via_then_property` (the
`await` path) consult it first.

**The hard part here is not speed, it is that a wrong answer HANGS.** A fast
path that misses a genuine thenable does not print a wrong value; the awaiting
promise simply never settles, which surfaces as a timed-out CI job someone
reruns. So the module fails CLOSED — every predicate returns "unknown" for
anything it cannot prove — and the proof is in two halves.

**Half 1, the receiver, is re-proved on every single probe and never cached.**
The value must be an arena-classified `GC_TYPE_OBJECT` with
`OBJECT_TYPE_REGULAR`, no `OBJ_FLAG_HAS_DESCRIPTORS` /
`OBJ_FLAG_ARRAY_DESCRIPTORS` / `OBJ_FLAG_TYPED_ARRAY_PROTO`, an admissible
class id, no own `then` key (a direct dense scan of the keys array — this is
the common real thenable and must always be found), and either
`OBJ_FLAG_NULL_PROTO` or no per-instance `setPrototypeOf` / `__proto__`
override. A `then` on the resolution object itself, or a prototype swapped onto
it, is therefore found immediately no matter how long the fast path has been
running.

**Half 2, `Object.prototype`, is cached under a signature** —
`(proto_addr, keys_array_addr, keys_array_len, header_flags, class_id,
PROP_PLAN_EPOCH, VTABLE_GEN)` — and the verdict itself is computed by calling
the REAL lookup, so it cannot disagree with the spec path at compute time.
Only staleness is a hazard, and the signature covers every route:

* `Object.prototype.then = f` (plain assignment, `Reflect.set`,
`Object.assign`) — a new own data key must land in the keys array, so either
`keys_len` moves or the array is transitioned to a different address;
* `Object.defineProperty` / `defineProperties` / `Reflect.defineProperty`, and
`delete` — `prop_plan_epoch_bump()` (`object/descriptor_state.rs`,
`object/delete_rest.rs`);
* `setPrototypeOf` / `__proto__` — `prop_plan_epoch_bump()`
(`object/prototype_chain.rs`);
* a vtable getter/method named `then` — `VTABLE_GEN`;
* any garbage collection — the epoch is bumped by the intern-table root scan
and the dead-owner prune, both of which run in every collection flavour.

Reusing `PROP_PLAN_EPOCH` rather than growing a parallel counter is deliberate:
its mutation hooks are already exercised by the store-plan and read-plan
caches, so this change adds no new invalidation hook that could be forgotten.
`ProtoSignature` derives `PartialEq` and is compared whole, so a route covered
by a new field cannot be dropped at the comparison site — and
`every_signature_field_invalidates_the_verdict` fails if any single field stops
participating.

Four residuals found by an arm-by-arm sweep of the entire `[[Get]]` path are
closed explicitly rather than argued away:

1. An **accessor** `then` on `Object.prototype` whose getter returns
`undefined` reads as "no then" but is observable. Memoizing that would
suppress every later invocation. The verdict now records the conservative
answer whenever `get_accessor_descriptor(Object.prototype, "then")` exists,
so the getter keeps running on every probe.
2. `js_object_get_field_by_name_f64` forwards a MISSED read to an aliased
native handle (`http.Server.call(this, …)`), a layer above the lookup being
modelled. `native_this_alias::alias_active()` now declines the fast path.
3. `subclass_backing_promise`'s `__perry_promise_backing__` probe is an
INHERITED read that reaches `Object.prototype`, so
`PROMISE_SUBCLASS_EVER` declines the fast path once any `class X extends
Promise` has been constructed.
4. Admitting anonymous-**shape** class ids used to rest on two compile-time
facts nothing checks at runtime. `class_id_admissible` now requires both
`is_anon_shape_class_id` (positive set membership, which excludes every
reserved builtin id) **and** `class_registry_inert` — no vtable entry, no
class prototype object of either flavour, no parent edge, i.e. the entire
input to the `class_id != 0` arms — memoized per
`(class_id, VTABLE_GEN, PROP_PLAN_EPOCH)`.

Two instruments ship with it. `PERRY_MT_PROFILE=1` gains
`thenable_fast=N` plus a bucketed `[mt-profile] then_probe:` histogram naming
which gate declined — the first arm of this change measured a flat zero and the
counter is what said why (the objects were anon shapes, not class 0), instead of
the A/B looking like a null result. `PERRY_THENABLE_VERIFY=1` re-runs the full
spec lookup on every fast negative and aborts on disagreement, so a broken
invalidation dies loudly instead of hanging.

`test-files/test_gap_thenable_fastpath_invalidation.ts` is the behavioural
gate: thirteen cases, each of which WARMS the same call site with plain objects
before mutating, so it tests invalidation rather than first-use. It is
byte-identical to `node --experimental-strip-types` on the pristine baseline as
well, so it is a control rather than a self-fulfilling test.
7 changes: 5 additions & 2 deletions crates/perry-runtime/src/gc/dead_owner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -214,8 +214,11 @@ fn fan_out(
is_dead_symbol: &dyn Fn(usize) -> bool,
) {
// Interned key pointers cached in the store-plan cache may die in this
// collection — flush every cached verdict.
crate::object::prop_plan::prop_plan_epoch_bump();
// collection — flush every cached verdict. Pointer identity only: the
// entries pruned below all belong to objects that are DEAD, so no live
// object's property lookup changes its answer. See
// `prop_plan_gc_epoch_bump`.
crate::object::prop_plan::prop_plan_gc_epoch_bump();
crate::array::prune_dead_array_named_property_owners(is_dead_owner);
crate::array::prune_dead_element_shape_owners(is_dead_owner);
crate::map::prune_dead_map_iterator_array_owners(is_dead_owner);
Expand Down
2 changes: 1 addition & 1 deletion crates/perry-runtime/src/object/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ pub(crate) use native_module_registry::nm_ctor_lookup;
// (`fs/promises` → `fs.constants`, `sys` → `util`).
pub(crate) use native_module_registry::{js_nm_install_fs, js_nm_install_util};
mod native_module_stream;
mod native_this_alias;
pub(crate) mod native_this_alias;
mod object_literal_ops;
mod object_ops;
pub(crate) use object_ops::{ensure_key_in_keys_array, install_builtin_getter};
Expand Down
42 changes: 41 additions & 1 deletion crates/perry-runtime/src/object/prop_plan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,51 @@ use std::sync::atomic::{AtomicU64, Ordering};
/// match.
static PROP_PLAN_EPOCH: AtomicU64 = AtomicU64::new(1);

/// Invalidate every cached store plan. Cheap (one relaxed add); callers are
/// The SEMANTIC half of [`PROP_PLAN_EPOCH`]: bumped by exactly the events that
/// change what a property lookup would ANSWER — descriptor installs and clears,
/// `delete`, per-instance prototype recording, class-prototype-object
/// registration, parent-static linking. Deliberately NOT bumped by garbage
/// collection.
///
/// The store/read-plan caches need the GC bump because they memoize a
/// (keys_array address, interned key pointer) → slot mapping, and a collection
/// can relocate either identity. A cache that instead re-derives its addresses
/// from live objects on every lookup — and only COMPARES them against what it
/// recorded — does not: a relocation shows up as an address mismatch, which is
/// a miss, and GC never adds or removes a property. Keying such a cache on the
/// full epoch is not merely wasteful, it is a performance CLIFF: the
/// incremental collector's root scan bumps the epoch at loop-poll cadence, so
/// the entry is invalid on essentially every lookup and the "cache" degrades
/// into an unconditional recompute. Measured on `gc-handoff/apps/asyncpipe.ts`:
/// +35 % instructions versus baseline, against −24.6 % with the recompute
/// eliminated (#7910).
static PROP_PLAN_SEMANTIC_EPOCH: AtomicU64 = AtomicU64::new(1);

/// Invalidate every cached store plan. Cheap (two relaxed adds); callers are
/// rare, cold paths by construction.
#[inline]
pub(crate) fn prop_plan_epoch_bump() {
PROP_PLAN_EPOCH.fetch_add(1, Ordering::Relaxed);
PROP_PLAN_SEMANTIC_EPOCH.fetch_add(1, Ordering::Relaxed);
}

/// Invalidate cached store plans for a reason that is NOT a semantic property
/// change: a collection moved interned keys or pruned dead owners' side-table
/// entries. Bumps only the pointer-identity epoch.
#[inline]
pub(crate) fn prop_plan_gc_epoch_bump() {
PROP_PLAN_EPOCH.fetch_add(1, Ordering::Relaxed);
}

/// Current SEMANTIC epoch — see [`PROP_PLAN_SEMANTIC_EPOCH`]. Exposed so other
/// caches whose validity rests on the same set of property-changing events can
/// key on it rather than growing a parallel counter with its own — separately
/// fallible — set of mutation hooks. First consumer: the `Object.prototype`
/// "has no `then`" verdict behind the promise assimilation fast path
/// (`promise::then_probe`, #7910).
#[inline]
pub(crate) fn prop_plan_semantic_epoch() -> u64 {
PROP_PLAN_SEMANTIC_EPOCH.load(Ordering::Relaxed)
}

#[derive(Clone, Copy)]
Expand Down
20 changes: 20 additions & 0 deletions crates/perry-runtime/src/promise/assimilate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,18 @@ pub(super) fn get_then_action(value: f64) -> Result<Option<f64>, f64> {
if is_definitely_primitive(value) {
return Ok(None);
}
// #7910: an ordinary object with no `then` anywhere on its chain is the
// overwhelmingly common resolution, and the spec's `Get(resolution,
// "then")` costs a `setjmp` frame, a re-intern of `"then"`, the generic
// dynamic getter's preamble and a miss-walk into `Object.prototype` to
// answer `undefined`. `definitely_no_then` proves that answer from the
// object's own header and keys array plus a signature-guarded verdict on
// `Object.prototype`, and declines (false) for anything it cannot prove.
// A plain object is never a native Array, so the array-prototype arm below
// is unreachable under this gate.
if super::then_probe::definitely_no_then(value) {
return Ok(None);
}
let then = combinator_catch_js(|| unsafe {
crate::value::js_dynamic_object_get_property(value, b"then".as_ptr() as *const i8, 4)
})?;
Expand Down Expand Up @@ -374,6 +386,14 @@ extern "C" fn promise_resolve_thenable_job(closure: *const crate::closure::Closu
/// its eventual state. Returns the wrapper promise, or — when `then` is absent
/// or not callable — the original `value` unchanged (resolve-plain).
pub(super) fn assimilate_via_then_property(value: f64) -> f64 {
// #7910: same fast negative as `get_then_action`. When there is provably no
// `then`, `Get` would answer `undefined`, `IsCallable(undefined)` is false,
// and this function returns `value` unchanged (resolve-plain) — which is
// exactly what the early return does, without allocating the key or paying
// the `setjmp`.
if super::then_probe::definitely_no_then(value) {
return value;
}
// `Get(value, "then")` (27.2.1.3.2 step 8). A throwing getter is an abrupt
// completion → resolve-with-thenable rejects the wrapper promise with the
// thrown value (step 9), rather than letting the exception unwind out of the
Expand Down
14 changes: 13 additions & 1 deletion crates/perry-runtime/src/promise/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ pub mod scanners;
pub mod spec_combinators;
pub mod subclass;
pub mod then;
pub(crate) mod then_probe;

// ─── Explicit named re-exports ────────────────────────────────────
// The full pre-split public surface. Anything new that needs to be
Expand Down Expand Up @@ -204,13 +205,17 @@ extern "C" fn mt_profile_atexit() {
return;
}
eprintln!(
"[mt-profile] runs={} resolved={} then={} new={} unwrap={} thenable_probe={}",
"[mt-profile] runs={} resolved={} then={} new={} unwrap={} thenable_probe={} thenable_fast={}",
MT_RUN_COUNT.load(Ordering::Relaxed),
MT_PROMISE_RESOLVED_COUNT.load(Ordering::Relaxed),
MT_PROMISE_THEN_COUNT.load(Ordering::Relaxed),
MT_PROMISE_NEW_COUNT.load(Ordering::Relaxed),
MT_INNER_PROMISE_UNWRAP_COUNT.load(Ordering::Relaxed),
MT_THENABLE_PROBE_COUNT.load(Ordering::Relaxed),
// #7910: a run where the `Get(resolution, "then")` fast negative never
// fired measured nothing about it — this counter is what tells an A/B
// its subject was live.
then_probe::MT_THENABLE_FAST_NEGATIVE.load(Ordering::Relaxed),
);
let q = MT_TIME_NS_QUEUE.load(Ordering::Relaxed);
let cb = MT_TIME_NS_CALLBACK.load(Ordering::Relaxed);
Expand All @@ -226,6 +231,13 @@ extern "C" fn mt_profile_atexit() {
MT_FAST_PATH_HIT.load(Ordering::Relaxed),
MT_FAST_PATH_MISS.load(Ordering::Relaxed),
);
// #7910: bucketed reasons the `Get(resolution, "then")` fast negative was
// or was not taken. A flat A/B with `fast=0` here says the change never
// ran; a shifted bucket says which gate stopped it.
eprintln!(
"[mt-profile] then_probe: {}",
then_probe::outcome_histogram()
);
eprintln!(
"[mt-profile] closure: alloc={} cap_singleton_hit={} cap_singleton_miss={}",
crate::closure::CLOSURE_ALLOC_COUNT.load(Ordering::Relaxed),
Expand Down
Loading
Loading