From 78f3654cf9c993342531851111becda396d4b2b4 Mon Sep 17 00:00:00 2001 From: Kiran Gadhave Date: Wed, 2 Dec 2026 17:11:00 -0800 Subject: [PATCH] perf: reduce execution map copies in run history Keep recording executions between display frames. Reuse private member maps until a frame takes a snapshot, then copy on the next write so earlier frames keep their records. --- .../notebook/replica/__tests__/frame.test.ts | 24 ++++++++++++- frontend/src/core/notebook/replica/frame.ts | 16 +++++---- .../src/core/notebook/replica/run-history.ts | 34 +++++++++++-------- 3 files changed, 52 insertions(+), 22 deletions(-) diff --git a/frontend/src/core/notebook/replica/__tests__/frame.test.ts b/frontend/src/core/notebook/replica/__tests__/frame.test.ts index 2423aead48e..b974925da47 100644 --- a/frontend/src/core/notebook/replica/__tests__/frame.test.ts +++ b/frontend/src/core/notebook/replica/__tests__/frame.test.ts @@ -6,7 +6,7 @@ import { atom, createStore, type Getter } from "jotai/vanilla"; import { expect, it, onTestFinished, vi } from "vitest"; import { mockAnimationFrames } from "@/__mocks__/animation-frames"; import { MockExecutions } from "@/__mocks__/executions"; -import { cellId } from "@/__tests__/branded"; +import { cellId, runId } from "@/__tests__/branded"; import { cellExecutionAtom, cellOutputAtom, @@ -99,6 +99,28 @@ it("updates commands and observers immediately, publishing a coherent display on expect(changed).toHaveBeenCalledOnce(); }); +it("keeps a published run's executions stable across later frames", async () => { + const { store, frame, receive, advanceFrame } = await setup(); + const [run, first, second, ...updates] = fixtureMessages("run-cells.sse"); + receive(run); + receive(first); + advanceFrame(); + + const published = store.get(frame.runHistoryAtom); + const id = runId("run-cells"); + const members = published.get(id)!.executions; + receive(second); + updates.forEach(receive); + expect(store.get(frame.runHistoryAtom)).toBe(published); + advanceFrame(); + + const latest = store.get(frame.runHistoryAtom).get(id)!; + expect([...members.keys()]).toEqual(["e12"]); + expect(members.get("e12")?.record.state.status).toBe("queued"); + expect([...latest.executions.keys()]).toEqual(["e12", "e13"]); + expect(latest.executions.get("e12")?.record.state.status).toBe("completed"); +}); + it.each([false, true])( "retains an intermediate matching analysis (previous analysis: %s)", async (hasPrevious) => { diff --git a/frontend/src/core/notebook/replica/frame.ts b/frontend/src/core/notebook/replica/frame.ts index 4e6c1b7a915..e79a6294e9c 100644 --- a/frontend/src/core/notebook/replica/frame.ts +++ b/frontend/src/core/notebook/replica/frame.ts @@ -29,7 +29,7 @@ export function createReplicaFrame( replica: FrameSource, { signal }: { signal: AbortSignal }, ): ReplicaFrame { - const runHistoryAtom = createRunHistory(store, replica, { signal }); + const snapshotRunHistory = createRunHistory(store, replica, { signal }); const currentAtom = atom((get) => ({ notebook: get(replica.notebookAtom), generation: get(replica.generationAtom), @@ -39,13 +39,15 @@ export function createReplicaFrame( executions: get(replica.executionsAtom), results: get(replica.resultsAtom), runtime: get(replica.runtimeAtom), - runHistory: get(runHistoryAtom), })); - const frameAtom = atom(store.get(currentAtom)); - const publish = oncePerFrame( - () => store.set(frameAtom, store.get(currentAtom)), - { signal }, - ); + const snapshot = () => ({ + ...store.get(currentAtom), + runHistory: snapshotRunHistory(), + }); + const frameAtom = atom(snapshot()); + const publish = oncePerFrame(() => store.set(frameAtom, snapshot()), { + signal, + }); if (!signal.aborted) { const unsubscribe = store.sub(currentAtom, publish); signal.addEventListener("abort", unsubscribe, { once: true }); diff --git a/frontend/src/core/notebook/replica/run-history.ts b/frontend/src/core/notebook/replica/run-history.ts index 93bdf48df58..76064d0081a 100644 --- a/frontend/src/core/notebook/replica/run-history.ts +++ b/frontend/src/core/notebook/replica/run-history.ts @@ -1,7 +1,7 @@ /* Copyright 2026 Marimo. All rights reserved. */ import type * as Protocol from "@marimo-team/client/protocol"; -import { type Atom, atom, type createStore } from "jotai/vanilla"; +import { atom, type createStore } from "jotai/vanilla"; import { completedAt, sourceForCell, startedAt } from "./execution-state"; import type { NotebookReplica } from "./replica"; import type { Document } from "./resources/document"; @@ -36,6 +36,11 @@ export type RunHistory = ReadonlyMap; const EMPTY: RunHistory = new Map(); +type DraftMembers = WeakMap< + RetainedRun["executions"], + Map +>; + /** The records the history reads from the stream's executions. */ type Reported = Pick & { readonly executions: ReadonlyMap< @@ -48,21 +53,18 @@ function milliseconds(createdAt: string | null): number { return createdAt === null ? Number.NEGATIVE_INFINITY : Date.parse(createdAt); } -/** Add what the stream reports now to the history, which only eviction shrinks. */ +/** Capture the reported records. Only unpublished member maps can be reused. */ export function retainRuns( history: RunHistory, { runs, executions }: Reported, document: Document | null, + drafts: DraftMembers = new WeakMap(), ): RunHistory { let next: Map | undefined; const put = (run: RetainedRun) => { next ??= new Map(history); next.set(run.id, run); }; - const copied = new Map< - Protocol.RunId, - Map - >(); // The stream can still report a run that was evicted, which is older than // every run kept. const oldest = @@ -87,7 +89,7 @@ export function retainRuns( if (retained?.record === record && retained.source === source) { continue; } - let members = copied.get(runId); + let members = run && drafts.get(run.executions); if (members === undefined) { const createdAt = run ? run.createdAt @@ -99,7 +101,7 @@ export function retainRuns( continue; } members = new Map(run?.executions); - copied.set(runId, members); + drafts.set(members, members); put({ id: runId, createdAt, run: run?.run ?? null, executions: members }); } members.set(record.id, { record, source }); @@ -124,7 +126,7 @@ export function retainRuns( } /** - * Keep the runs a replica reports, from now until `signal` aborts. + * Keep the runs a replica reports and return a function that snapshots them. * * The history reads the replica itself. A frame can miss an execution that * arrives and leaves between two of its publications. @@ -136,8 +138,9 @@ export function createRunHistory( "notebookAtom" | "executionsAtom" | "shownDocumentAtom" >, { signal }: { signal: AbortSignal }, -): Atom { - const historyAtom = atom(EMPTY); +): () => RunHistory { + let history = EMPTY; + let drafts: DraftMembers = new WeakMap(); // Read together, so a reset never pairs one notebook's id with another's runs. const reportedAtom = atom((get) => ({ notebookId: get(replica.notebookAtom)?.id ?? null, @@ -148,13 +151,12 @@ export function createRunHistory( function retain() { const { notebookId, executions, document } = store.get(reportedAtom); - let history = store.get(historyAtom); // The id is null while disconnected or resetting, which keeps the history. if (notebookId !== null && notebookId !== followed) { history = followed === null ? history : EMPTY; followed = notebookId; } - store.set(historyAtom, retainRuns(history, executions, document)); + history = retainRuns(history, executions, document, drafts); } if (!signal.aborted) { @@ -163,5 +165,9 @@ export function createRunHistory( once: true, }); } - return historyAtom; + return () => { + // Once a frame can read these maps, future updates must copy them. + drafts = new WeakMap(); + return history; + }; }