Skip to content

Commit be82cf3

Browse files
ryansolidClaude via Cursorcursoragent
authored
fix(signals,web): one interaction frame per event, joinable by outside listeners (#3754) (#3877)
* fix(signals,web): one interaction frame per event, joinable by outside listeners (#3754) The runtime opened an interaction frame per listener and recorded it as soon as that handler returned, so a document-level listener (a router's anchor click) either ran outside any frame or produced a second record for the same click. InteractionRef takes an optional `event`; frames sharing it re-enter one record, which stays joinable until the next task. The web runtime keys its frames by the DOM event, and `dispatchAsInteraction` is exported so outside listeners can join. Co-authored-by: Claude via Cursor <[email protected]> Co-authored-by: Cursor <[email protected]> * fix(signals): the per-event finalize timer does not hold the Event; InteractionRef.event is a join key only (#3754) Co-authored-by: Claude via Cursor <[email protected]> Co-authored-by: Cursor <[email protected]> * size: raise the engine-enabled observe cap for #3877 (Size-Exception, accepted 2026-10-07) Co-authored-by: Claude via Cursor <[email protected]> Co-authored-by: Cursor <[email protected]> --------- Co-authored-by: Claude via Cursor <[email protected]> Co-authored-by: Cursor <[email protected]>
1 parent 7233451 commit be82cf3

11 files changed

Lines changed: 501 additions & 31 deletions
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
"@solidjs/signals": patch
3+
"@solidjs/web": patch
4+
---
5+
6+
Observe: one interaction frame per event, not per listener. `InteractionRef` takes an optional `event`; frames with the same `event` re-enter one interaction record, which stays joinable for the event's dispatch and is recorded at the next task. The web runtime keys its frames by the DOM event, and `@solidjs/web` exports `dispatchAsInteraction(e, fn)` so a listener outside the runtime (a router's `document` click handler) joins the frame of the same event — `fn()` in production builds. One anchor click is now one interaction record carrying both the `onClick` work and the navigation (#3754).

‎documentation/solid-2.0/08-dev-diagnostics.md‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1079,8 +1079,15 @@ attribution.markFlight(promise, startedAt?);
10791079
// Runtime side (`OBSERVE`, present in dev and observe builds): stamp the
10801080
// writes made synchronously inside `fn` with a user interaction. Compiled
10811081
// event bindings do this for every handler; custom renderers and test
1082-
// harnesses call it themselves. `fn()` when no engine is enabled.
1082+
// harnesses call it themselves. `fn()` when no engine is enabled. Frames
1083+
// given the same `event` are one interaction: every listener of a dispatch
1084+
// joins the record the first one opened, which is recorded at the next task.
10831085
OBSERVE.attribution.withInteraction({ type: "click", target: 'button#next "Next →"' }, fn);
1086+
// A listener the web runtime did not attach (a router's `document` click
1087+
// handler) joins the frame the runtime opened for the same event — `fn()`
1088+
// in production builds.
1089+
import { dispatchAsInteraction } from "@solidjs/web";
1090+
document.addEventListener("click", e => dispatchAsInteraction(e, () => handleAnchorClick(e)));
10841091
// A router declares a navigation around its location write — match eagerly,
10851092
// describe by the parametrized route, then write. This is the only
10861093
// router-specific line anywhere; the engine knows no router.
@@ -1178,11 +1185,12 @@ Known gap: handlers bound through the runtime (delegated events, and non-literal
11781185
11791186
The interaction is the unit a person experiences: one click, and everything it cost until the screen had the answer. Every downstream fact is already keyed to the interaction frame — writes stamp it, re-runs trace to it through their causes, holds and navigations carry it — and `feedback().interactions` folds those by interaction _name_. `history("interaction")` keeps one `InteractionEvent` per dispatch instead (delivered on `OBSERVE.records.subscribe("interaction", …)` as it settles), with a start, an end, and the pieces attached, so a consumer building a span per interaction (an APM adapter) neither infers the end from an idle gap nor sums quantized per-run times to approximate the wall clock:
11801187
1181-
- `name`, `target`, `at` — what the runtime described to `withInteraction` (`at` the event's own `timeStamp` when it was given, else the dispatch); `inputDelayMs` — the browser's queueing from `at` to the handler's entry, present when `at` predates it; `handlerMs` — the handler itself, entry to return.
1188+
- One record per **event**, not per listener: the web runtime hands the engine the DOM event as the frame's join key (`InteractionRef.event`), so the delegated listener of every root, each runtime-attached listener and any outside listener wrapped in `dispatchAsInteraction(e, fn)` (a router's `document` click handler) add their work to the record the first one opened. That record stays joinable for the event's whole dispatch — browsers run microtasks between listeners, so it is finalized at the next task, not at a microtask — and is recorded no earlier, at the instant it settled. The same event dispatched again after that is a new interaction. A frame without an `event` (a test harness's `withInteraction`) is its own record and settles as it closes.
1189+
- `name`, `target`, `at` — what the runtime described to `withInteraction` for the event's first frame (`at` the event's own `timeStamp` when it was given, else the dispatch); `inputDelayMs` — the browser's queueing from `at` to the first handler's entry, present when `at` predates it; `handlerMs` — the handlers themselves, the first one's entry to the last one's return.
11821190
- `writes` — root writes attributed to the frame: the handler's, and those of frames it opened (a navigation).
11831191
- `runs` and `created` — re-runs traced back to it, and computations _created_ in those runs or in its flushes (the "create 1,000 rows" work, which no `RerunEvent` describes); `runMs` sums the self-time of both.
11841192
- `holds` — the `HoldEvent`s its writes waited in; `navigations` — the `NavigationEvent`s performed under it. The same objects as in `history("hold")`/`history("navigation")`.
1185-
- `settledMs` and `outcome`, once everything is through: `idle` (the handler wrote nothing — settles as the frame closes), `committed` (its writes went through in drains no transition held — settles at the end of the last such drain), `held` (at least one write waited in a transition — settles at the last hold's commit). A navigation under it must settle first.
1193+
- `settledMs` and `outcome`, once everything is through: `idle` (the handlers wrote nothing — settles as the last frame closes, recorded at the next task for an event's frames), `committed` (its writes went through in drains no transition held — settles at the end of the last such drain), `held` (at least one write waited in a transition — settles at the last hold's commit). A navigation under it must settle first.
11861194
- `origin` — the frame object every downstream record carries as `interaction`; join by identity.
11871195
11881196
Runs are counted while the record is open; an async landing the interaction caused that arrives after its writes committed (a fetch behind a `Loading` boundary that showed its fallback) is attributed to it on the `RerunEvent` but is not the interaction's wait — the boundary answered.

‎packages/signals/src/core/attribution-hooks.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -251,6 +251,21 @@ export interface InteractionRef {
251251
target?: string;
252252
/** Dispatch time on the `performance.now()` clock; defaults to now. */
253253
at?: number;
254+
/**
255+
* The dispatch this frame handles — the DOM `Event` itself. Frames with the
256+
* same `event` are one interaction: the first opens the record (its `type`,
257+
* `target` and `at` describe it) and every later one re-enters it, so each
258+
* listener of one dispatch adds its work to one record. Such a record stays
259+
* open for joining until the next task — every listener of a dispatch runs
260+
* within its task — and is recorded no earlier; a frame for the event after
261+
* that opens a new interaction. Without `event` the record is the frame's
262+
* alone and can settle as it closes.
263+
*
264+
* A join key only, compared by identity and held weakly: it is never
265+
* recorded — no `InteractionEvent`, origin or other record carries it — and
266+
* the engine keeps no strong reference to it.
267+
*/
268+
event?: object;
254269
}
255270

256271
/**

‎packages/signals/src/core/attribution.ts‎

Lines changed: 51 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -873,13 +873,20 @@ function targetLabel(target: string): string {
873873

874874
function interactionStart(ref: InteractionRef): void {
875875
interactionStack.push(currentInteraction);
876+
// No `ref.event`: the WeakMap answers undefined.
877+
const joined = eventInteractions.get(ref.event!);
878+
if (joined?.joinable && openInteractions.has(joined)) {
879+
joined.open = true;
880+
currentInteraction = joined.event.origin;
881+
return;
882+
}
876883
// One clock read: the frame opens now; the interaction began at `ref.at`
877884
// when the runtime dated it (the event's own timestamp), else now too.
878885
const opened = now();
879886
const origin: ChangeOrigin = { kind: "interaction", name: ref.type, at: ref.at ?? opened };
880887
if (ref.target) origin.target = targetLabel(ref.target);
881888
currentInteraction = origin;
882-
openInteraction(origin, opened);
889+
openInteraction(origin, opened, ref.event);
883890
}
884891

885892
function interactionEnd(returned?: unknown): void {
@@ -3811,10 +3818,11 @@ function settleNavigation(
38113818
//
38123819
// A record settles once, by the same drain clock navigations use: `idle` —
38133820
// the handler performed no root write (nothing to wait for; settles when the
3814-
// frame closes); `committed` — its writes went through in drains no
3815-
// transition held (the last such drain's `flushEnd` is the instant); `held`
3816-
// — at least one of its writes waited in a transition (the last hold's commit
3817-
// is the instant, each HoldEvent attached). A navigation the frame performed
3821+
// frame closes — for an `event`'s frames, recorded at the next task with the
3822+
// instant the last one closed); `committed` — its writes went through in
3823+
// drains no transition held (the last such drain's `flushEnd` is the
3824+
// instant); `held` — at least one of its writes waited in a transition (the
3825+
// last hold's commit is the instant, each HoldEvent attached). A navigation the frame performed
38183826
// is attached too and must settle before the interaction does. Runs are
38193827
// counted while the record is open:
38203828
// re-runs whose cause chain reaches the frame, plus computations CREATED in
@@ -3837,7 +3845,11 @@ export interface InteractionEvent {
38373845
* INP counts as input delay. Present only when `at` predates the frame.
38383846
*/
38393847
inputDelayMs?: number;
3840-
/** Wall time of the handler itself, entry to return. */
3848+
/**
3849+
* Wall time of the handler itself, entry to return — for the frames of one
3850+
* event (`InteractionRef.event`), the first listener's entry to the last
3851+
* one's return, as Event Timing measures processing.
3852+
*/
38413853
handlerMs: number;
38423854
/** Root writes attributed to the frame: the handler's, and those of frames it opened (a navigation). */
38433855
writes: number;
@@ -3860,7 +3872,8 @@ export interface InteractionEvent {
38603872
outcome?: "idle" | "committed" | "held";
38613873
/**
38623874
* The handler returned a thenable (`async () => { await save(); … }`) and
3863-
* the record waited for it: handler return → the promise settling, in
3875+
* the record waited for it: handler return → the promise settling (the last
3876+
* one, when several listeners of one event returned one), in
38643877
* milliseconds, capped at `ASYNC_HANDLER_CAP_MS`. The continuation runs
38653878
* with no frame on the stack, so writes it makes are not attributed to
38663879
* this interaction — only its duration is. Absent when the handler
@@ -3889,17 +3902,23 @@ interface InteractionState {
38893902
held: boolean;
38903903
/** Root writes to excluded subjects (the observer's own store): not the app's. */
38913904
excludedWrites: number;
3892-
/** The handler returned a thenable that has not settled; the record waits for it. */
3893-
awaiting: boolean;
3905+
/** Thenables its handlers returned that have not settled; the record waits for them. */
3906+
awaiting: number;
38943907
/** An action step ran under the frame: the handler's async work is an action's, tracked as such. */
38953908
actioned: boolean;
3909+
/** Another frame for its event may still join it (until the next task). */
3910+
joinable: boolean;
3911+
/** When it last could have settled while joinable — the instant it settles at. */
3912+
settleAt?: number;
38963913
}
38973914
const interactionStates = new WeakMap<ChangeOrigin, InteractionState>();
3915+
/** `InteractionRef.event` → the record its frames join (while `joinable`). Weak: the Event is never held. */
3916+
const eventInteractions = new WeakMap<object, InteractionState>();
38983917
/** Opened, not yet settled. */
38993918
const openInteractions = new Set<InteractionState>();
39003919
let interactionLog: InteractionEvent[] = [];
39013920

3902-
function openInteraction(frame: ChangeOrigin, opened: number): void {
3921+
function openInteraction(frame: ChangeOrigin, opened: number, key?: object): void {
39033922
const event: InteractionEvent = {
39043923
name: frame.name!,
39053924
at: frame.at!,
@@ -3925,13 +3944,24 @@ function openInteraction(frame: ChangeOrigin, opened: number): void {
39253944
heldIn: new Set(),
39263945
held: false,
39273946
excludedWrites: 0,
3928-
awaiting: false,
3929-
actioned: false
3947+
awaiting: 0,
3948+
actioned: false,
3949+
joinable: key !== undefined
39303950
};
39313951
interactionStates.set(frame, state);
39323952
openInteractions.add(state);
39333953
interactionLog.push(event);
39343954
if (interactionLog.length > options.historyLimit) interactionLog.shift();
3955+
if (key !== undefined) {
3956+
eventInteractions.set(key, state);
3957+
// A microtask is too early: native dispatch runs microtasks between
3958+
// listeners. The callback must not close over `key`: a throttled timer
3959+
// would hold the Event strongly long past its dispatch.
3960+
setTimeout(() => {
3961+
state.joinable = false;
3962+
if (openInteractions.has(state)) maybeSettleInteraction(state, state.settleAt);
3963+
});
3964+
}
39353965
}
39363966

39373967
/**
@@ -3959,17 +3989,17 @@ function closeInteraction(frame: ChangeOrigin, returned?: unknown): void {
39593989
? (returned as PromiseLike<unknown>)
39603990
: null;
39613991
if (thenable !== null) {
3962-
state.awaiting = true;
3992+
state.awaiting++;
39633993
let done = false;
39643994
let timer: ReturnType<typeof setTimeout> | undefined;
39653995
const settle = (): void => {
39663996
if (done) return;
39673997
done = true;
39683998
if (timer !== undefined) clearTimeout(timer);
3969-
if (!openInteractions.has(state)) return;
3970-
state.awaiting = false;
3999+
if (!openInteractions.has(state) || --state.awaiting > 0) return;
39714000
const at = now();
3972-
state.event.continuationMs = at - end;
4001+
// From the last handler's return: the frames of one event share a record.
4002+
state.event.continuationMs = at - (state.opened + state.event.handlerMs);
39734003
checkUntrackedAsyncHandler(state);
39744004
maybeSettleInteraction(state, at);
39754005
};
@@ -4085,12 +4115,16 @@ function settleInteractionsHeld(t: Transition, hold: HoldEvent | undefined): voi
40854115

40864116
function maybeSettleInteraction(state: InteractionState, end: number = now()): void {
40874117
const event = state.event;
4088-
if (state.open || state.awaiting || state.heldIn.size > 0) return;
4118+
if (state.open || state.awaiting > 0 || state.heldIn.size > 0) return;
40894119
// A drain must have committed the last write (the handler's, or a redirect
40904120
// hop's after the click's own drain) — the handler returning is not the
40914121
// screen having it.
40924122
if (event.writes > 0 && drainSeq <= state.writeDrain) return;
40934123
for (const nav of event.navigations) if (nav.outcome === undefined) return;
4124+
if (state.joinable) {
4125+
state.settleAt = end;
4126+
return;
4127+
}
40944128
openInteractions.delete(state);
40954129
// Every write went to an excluded subject and nothing of the app's ran: the
40964130
// click was on the observer's own UI (a devtools panel's button). Not a

‎packages/signals/tests/attribution-interactions.test.ts‎

Lines changed: 74 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@
22
* Interactions as first-class records, and the typed record channel.
33
*
44
* Claim under test: every `withInteraction` frame yields one `InteractionEvent`
5-
* that settles exactly once when everything the person waited on is through
5+
* (frames sharing an `event`, one between them, recorded no earlier than the
6+
* next task) that settles exactly once when everything the person waited on is through
67
* — the handler's return when it wrote nothing (`idle`), the drain that
78
* committed its writes (`committed`), or the commit of the last hold they
89
* waited in (`held`) — with the re-runs, creations, holds and navigations it
@@ -296,6 +297,78 @@ describe("InteractionEvent", () => {
296297
});
297298
});
298299

300+
describe("frames for one event (`InteractionRef.event`)", () => {
301+
afterEach(() => {
302+
vi.useRealTimers();
303+
});
304+
305+
it("are one record, joinable until the next task", () => {
306+
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
307+
const { interactionLog } = arm();
308+
const [count, setCount] = createSignal(0, { name: "count" });
309+
createRoot(() => createEffect(count, () => {}, { name: "reader" }));
310+
flush();
311+
const event = {};
312+
313+
OBSERVE!.attribution.withInteraction({ ...CLICK, event }, () => {});
314+
flush();
315+
// A later listener of the same dispatch, with a target described from
316+
// where it listens: the first frame's description stands.
317+
OBSERVE!.attribution.withInteraction({ type: "click", target: "a", event }, () => setCount(1));
318+
flush();
319+
expect(interactionLog()).toHaveLength(0);
320+
expect(attribution.history("interaction")).toHaveLength(1);
321+
322+
vi.advanceTimersByTime(1);
323+
const [e] = interactionLog();
324+
expect(interactionLog()).toHaveLength(1);
325+
expect(e).toMatchObject({ target: CLICK.target, writes: 1, runs: 1, outcome: "committed" });
326+
expect(e.settledMs).toBeGreaterThanOrEqual(e.handlerMs);
327+
});
328+
329+
it("open a fresh record once the event's frame was finalized", () => {
330+
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
331+
const { interactionLog } = arm();
332+
const event = {};
333+
OBSERVE!.attribution.withInteraction({ ...CLICK, event }, () => {});
334+
vi.advanceTimersByTime(1);
335+
OBSERVE!.attribution.withInteraction({ ...CLICK, event }, () => {});
336+
vi.advanceTimersByTime(1);
337+
expect(interactionLog()).toHaveLength(2);
338+
expect(interactionLog().map(e => e.outcome)).toEqual(["idle", "idle"]);
339+
expect(interactionLog()[0].origin).not.toBe(interactionLog()[1].origin);
340+
});
341+
342+
it("wait for every listener's returned promise", async () => {
343+
const { interactionLog } = arm();
344+
const event = {};
345+
let first!: () => void;
346+
let second!: () => void;
347+
OBSERVE!.attribution.withInteraction(
348+
{ ...CLICK, event },
349+
() => new Promise<void>(r => (first = r))
350+
);
351+
OBSERVE!.attribution.withInteraction(
352+
{ ...CLICK, event },
353+
() => new Promise<void>(r => (second = r))
354+
);
355+
await wait(5);
356+
first();
357+
await wait(5);
358+
expect(interactionLog()).toHaveLength(0);
359+
second();
360+
await until(() => interactionLog().length === 1, "both continuations to settle the record");
361+
expect(interactionLog()[0].continuationMs).toBeGreaterThanOrEqual(5);
362+
});
363+
364+
it("leave a frame without one settling as it closes", () => {
365+
const { interactionLog } = arm();
366+
OBSERVE!.attribution.withInteraction(CLICK, () => {});
367+
OBSERVE!.attribution.withInteraction(CLICK, () => {});
368+
expect(interactionLog()).toHaveLength(2);
369+
});
370+
});
371+
299372
describe("a handler that returns a promise", () => {
300373
function armWithFindings(
301374
holds: { infoMs: number; warnMs: number } | false = { infoMs: 0, warnMs: 0 }

0 commit comments

Comments
 (0)