Skip to content

Commit 40510ee

Browse files
authored
perf: reduce execution map copies in run history (#12253)
**This pull request was authored by a coding agent.** ## 📝 Summary Stacked on #12180. Capture each execution as it arrives and reuse its run’s private member map until the next display frame. The first write after publication copies the map so an earlier frame keeps its original entries. A local replay sent 1,000 cells through queued, running, and completed states on both revisions. With one display frame per 32 messages, median time from transport-message handling through frame publication fell from 320 ms on #12180 to 243 ms on this branch. This branch was faster in all 12 paired replays. Both revisions published the same 94 frames, and earlier snapshots kept their original records. The base constructed 3,000 history member maps and copied 2,499,500 entries. This branch constructed 94 and copied 77,841 entries. In a 500-cell control that published after every message, both versions copied the same number of entries. The replay used one subscriber and excluded browser rendering. History still scans the live executions on each update. Part of [MO-8797](https://linear.app/marimo/issue/MO-8797/fix-find-dialogs-scroll-outline-and-remaining-per-event-helpers). ## 📋 Pre-Review Checklist <!-- These checks need to be completed before a PR is reviewed --> - [ ] For large changes, or changes that affect the public API: this change was discussed or approved through an issue, on [Discord](https://marimo.io/discord?ref=pr), or the community [discussions](https://github.com/marimo-team/marimo/discussions) (Please provide a link if applicable). - [ ] Any AI generated code has been reviewed line-by-line by the human PR author, who stands by it. - [ ] Video or media evidence is provided for any visual changes. <!-- PR is more likely to be merged if functionality is tested thoroughly --> ## ✅ Merge Checklist - [ ] I have read the [contributor guidelines](https://github.com/marimo-team/marimo/blob/main/CONTRIBUTING.md). - [ ] Documentation has been updated where applicable, including docstrings for API changes. - [ ] Tests have been added for the changes made.
1 parent d0bcfc5 commit 40510ee

3 files changed

Lines changed: 52 additions & 22 deletions

File tree

‎frontend/src/core/notebook/replica/__tests__/frame.test.ts‎

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import { atom, createStore, type Getter } from "jotai/vanilla";
66
import { expect, it, onTestFinished, vi } from "vitest";
77
import { mockAnimationFrames } from "@/__mocks__/animation-frames";
88
import { MockExecutions } from "@/__mocks__/executions";
9-
import { cellId } from "@/__tests__/branded";
9+
import { cellId, runId } from "@/__tests__/branded";
1010
import {
1111
cellExecutionAtom,
1212
cellOutputAtom,
@@ -99,6 +99,28 @@ it("updates commands and observers immediately, publishing a coherent display on
9999
expect(changed).toHaveBeenCalledOnce();
100100
});
101101

102+
it("keeps a published run's executions stable across later frames", async () => {
103+
const { store, frame, receive, advanceFrame } = await setup();
104+
const [run, first, second, ...updates] = fixtureMessages("run-cells.sse");
105+
receive(run);
106+
receive(first);
107+
advanceFrame();
108+
109+
const published = store.get(frame.runHistoryAtom);
110+
const id = runId("run-cells");
111+
const members = published.get(id)!.executions;
112+
receive(second);
113+
updates.forEach(receive);
114+
expect(store.get(frame.runHistoryAtom)).toBe(published);
115+
advanceFrame();
116+
117+
const latest = store.get(frame.runHistoryAtom).get(id)!;
118+
expect([...members.keys()]).toEqual(["e12"]);
119+
expect(members.get("e12")?.record.state.status).toBe("queued");
120+
expect([...latest.executions.keys()]).toEqual(["e12", "e13"]);
121+
expect(latest.executions.get("e12")?.record.state.status).toBe("completed");
122+
});
123+
102124
it.each([false, true])(
103125
"retains an intermediate matching analysis (previous analysis: %s)",
104126
async (hasPrevious) => {

‎frontend/src/core/notebook/replica/frame.ts‎

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ export function createReplicaFrame(
2929
replica: FrameSource,
3030
{ signal }: { signal: AbortSignal },
3131
): ReplicaFrame {
32-
const runHistoryAtom = createRunHistory(store, replica, { signal });
32+
const snapshotRunHistory = createRunHistory(store, replica, { signal });
3333
const currentAtom = atom((get) => ({
3434
notebook: get(replica.notebookAtom),
3535
generation: get(replica.generationAtom),
@@ -39,13 +39,15 @@ export function createReplicaFrame(
3939
executions: get(replica.executionsAtom),
4040
results: get(replica.resultsAtom),
4141
runtime: get(replica.runtimeAtom),
42-
runHistory: get(runHistoryAtom),
4342
}));
44-
const frameAtom = atom(store.get(currentAtom));
45-
const publish = oncePerFrame(
46-
() => store.set(frameAtom, store.get(currentAtom)),
47-
{ signal },
48-
);
43+
const snapshot = () => ({
44+
...store.get(currentAtom),
45+
runHistory: snapshotRunHistory(),
46+
});
47+
const frameAtom = atom(snapshot());
48+
const publish = oncePerFrame(() => store.set(frameAtom, snapshot()), {
49+
signal,
50+
});
4951
if (!signal.aborted) {
5052
const unsubscribe = store.sub(currentAtom, publish);
5153
signal.addEventListener("abort", unsubscribe, { once: true });

‎frontend/src/core/notebook/replica/run-history.ts‎

Lines changed: 20 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
/* Copyright 2026 Marimo. All rights reserved. */
22

33
import type * as Protocol from "@marimo-team/client/protocol";
4-
import { type Atom, atom, type createStore } from "jotai/vanilla";
4+
import { atom, type createStore } from "jotai/vanilla";
55
import { completedAt, sourceForCell, startedAt } from "./execution-state";
66
import type { NotebookReplica } from "./replica";
77
import type { Document } from "./resources/document";
@@ -36,6 +36,11 @@ export type RunHistory = ReadonlyMap<Protocol.RunId, RetainedRun>;
3636

3737
const EMPTY: RunHistory = new Map();
3838

39+
type DraftMembers = WeakMap<
40+
RetainedRun["executions"],
41+
Map<Protocol.ExecutionId, RetainedExecution>
42+
>;
43+
3944
/** The records the history reads from the stream's executions. */
4045
type Reported = Pick<Executions, "runs"> & {
4146
readonly executions: ReadonlyMap<
@@ -48,21 +53,18 @@ function milliseconds(createdAt: string | null): number {
4853
return createdAt === null ? Number.NEGATIVE_INFINITY : Date.parse(createdAt);
4954
}
5055

51-
/** Add what the stream reports now to the history, which only eviction shrinks. */
56+
/** Capture the reported records. Only unpublished member maps can be reused. */
5257
export function retainRuns(
5358
history: RunHistory,
5459
{ runs, executions }: Reported,
5560
document: Document | null,
61+
drafts: DraftMembers = new WeakMap(),
5662
): RunHistory {
5763
let next: Map<Protocol.RunId, RetainedRun> | undefined;
5864
const put = (run: RetainedRun) => {
5965
next ??= new Map(history);
6066
next.set(run.id, run);
6167
};
62-
const copied = new Map<
63-
Protocol.RunId,
64-
Map<Protocol.ExecutionId, RetainedExecution>
65-
>();
6668
// The stream can still report a run that was evicted, which is older than
6769
// every run kept.
6870
const oldest =
@@ -87,7 +89,7 @@ export function retainRuns(
8789
if (retained?.record === record && retained.source === source) {
8890
continue;
8991
}
90-
let members = copied.get(runId);
92+
let members = run && drafts.get(run.executions);
9193
if (members === undefined) {
9294
const createdAt = run
9395
? run.createdAt
@@ -99,7 +101,7 @@ export function retainRuns(
99101
continue;
100102
}
101103
members = new Map(run?.executions);
102-
copied.set(runId, members);
104+
drafts.set(members, members);
103105
put({ id: runId, createdAt, run: run?.run ?? null, executions: members });
104106
}
105107
members.set(record.id, { record, source });
@@ -124,7 +126,7 @@ export function retainRuns(
124126
}
125127

126128
/**
127-
* Keep the runs a replica reports, from now until `signal` aborts.
129+
* Keep the runs a replica reports and return a function that snapshots them.
128130
*
129131
* The history reads the replica itself. A frame can miss an execution that
130132
* arrives and leaves between two of its publications.
@@ -136,8 +138,9 @@ export function createRunHistory(
136138
"notebookAtom" | "executionsAtom" | "shownDocumentAtom"
137139
>,
138140
{ signal }: { signal: AbortSignal },
139-
): Atom<RunHistory> {
140-
const historyAtom = atom(EMPTY);
141+
): () => RunHistory {
142+
let history = EMPTY;
143+
let drafts: DraftMembers = new WeakMap();
141144
// Read together, so a reset never pairs one notebook's id with another's runs.
142145
const reportedAtom = atom((get) => ({
143146
notebookId: get(replica.notebookAtom)?.id ?? null,
@@ -148,13 +151,12 @@ export function createRunHistory(
148151

149152
function retain() {
150153
const { notebookId, executions, document } = store.get(reportedAtom);
151-
let history = store.get(historyAtom);
152154
// The id is null while disconnected or resetting, which keeps the history.
153155
if (notebookId !== null && notebookId !== followed) {
154156
history = followed === null ? history : EMPTY;
155157
followed = notebookId;
156158
}
157-
store.set(historyAtom, retainRuns(history, executions, document));
159+
history = retainRuns(history, executions, document, drafts);
158160
}
159161

160162
if (!signal.aborted) {
@@ -163,5 +165,9 @@ export function createRunHistory(
163165
once: true,
164166
});
165167
}
166-
return historyAtom;
168+
return () => {
169+
// Once a frame can read these maps, future updates must copy them.
170+
drafts = new WeakMap();
171+
return history;
172+
};
167173
}

0 commit comments

Comments
 (0)