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
24 changes: 23 additions & 1 deletion frontend/src/core/notebook/replica/__tests__/frame.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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) => {
Expand Down
16 changes: 9 additions & 7 deletions frontend/src/core/notebook/replica/frame.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand All @@ -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 });
Expand Down
34 changes: 20 additions & 14 deletions frontend/src/core/notebook/replica/run-history.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -36,6 +36,11 @@ export type RunHistory = ReadonlyMap<Protocol.RunId, RetainedRun>;

const EMPTY: RunHistory = new Map();

type DraftMembers = WeakMap<
RetainedRun["executions"],
Map<Protocol.ExecutionId, RetainedExecution>
>;

/** The records the history reads from the stream's executions. */
type Reported = Pick<Executions, "runs"> & {
readonly executions: ReadonlyMap<
Expand All @@ -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<Protocol.RunId, RetainedRun> | undefined;
const put = (run: RetainedRun) => {
next ??= new Map(history);
next.set(run.id, run);
};
const copied = new Map<
Protocol.RunId,
Map<Protocol.ExecutionId, RetainedExecution>
>();
// The stream can still report a run that was evicted, which is older than
// every run kept.
const oldest =
Expand All @@ -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
Expand All @@ -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 });
Expand All @@ -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.
Expand All @@ -136,8 +138,9 @@ export function createRunHistory(
"notebookAtom" | "executionsAtom" | "shownDocumentAtom"
>,
{ signal }: { signal: AbortSignal },
): Atom<RunHistory> {
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,
Expand All @@ -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) {
Expand All @@ -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;
};
}
Loading