Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

fix: serialize anywidget model messages until acknowledged (#11578)

Myles Scolnickb638ae58ae3e
diff --git a/frontend/src/plugins/impl/anywidget/__tests__/registry.test.ts b/frontend/src/plugins/impl/anywidget/__tests__/registry.test.ts
index e405a345b0..344d1a7ce7 100644
--- a/frontend/src/plugins/impl/anywidget/__tests__/registry.test.ts
+++ b/frontend/src/plugins/impl/anywidget/__tests__/registry.test.ts
@@ -8,6 +8,8 @@ import {
type MockInstance,
vi,
} from "vitest";
+import { Deferred } from "@/utils/Deferred";
+import { Logger } from "@/utils/Logger";
import { getMarimoInternal, Model } from "../model";
import { handleWidgetMessage, WidgetRegistry } from "../registry";
import type { EsmSpec, ModelState, WidgetModelId } from "../types";
@@ -155,6 +157,155 @@ describe("WidgetRegistry models", () => {
);
});
+ describe("outgoing messages", () => {
+ async function openModel(id = testId) {
+ await handleWidgetMessage(registry, {
+ model_id: id,
+ message: {
+ method: "open",
+ state: {},
+ buffer_paths: [],
+ buffers: [],
+ },
+ });
+ return registry.getModel(id);
+ }
+
+ afterEach(() => {
+ mockSendModelValue.mockReset().mockResolvedValue(null);
+ vi.restoreAllMocks();
+ });
+
+ it("waits for each acknowledgement before sending the next update", async () => {
+ const model = await openModel();
+ const responses = [new Deferred<null>(), new Deferred<null>()];
+ for (const response of responses) {
+ mockSendModelValue.mockReturnValueOnce(response.promise);
+ }
+ const states = [
+ { card: "A", seq: 5 },
+ { card: "", seq: 6 },
+ { card: "B", seq: 7 },
+ ];
+ for (const state of states) {
+ model.set("selection", state);
+ model.save_changes();
+ }
+
+ await vi.waitFor(() =>
+ expect(mockSendModelValue).toHaveBeenCalledTimes(1),
+ );
+ for (const [index, response] of responses.entries()) {
+ response.resolve(null);
+ await vi.waitFor(() =>
+ expect(mockSendModelValue).toHaveBeenCalledTimes(index + 2),
+ );
+ }
+ expect(mockSendModelValue.mock.calls).toEqual(
+ states.map((selection) => [
+ {
+ modelId: testId,
+ message: {
+ method: "update",
+ state: { selection },
+ bufferPaths: [],
+ },
+ buffers: [],
+ },
+ ]),
+ );
+ });
+
+ it("orders custom messages with updates and waits before calling callbacks", async () => {
+ const model = await openModel();
+ const response = new Deferred<null>();
+ mockSendModelValue.mockReturnValueOnce(response.promise);
+ const callback = vi.fn();
+ const sent = model.send({ action: "first" }, callback);
+ model.set("count", 1);
+ model.save_changes();
+ const last = model.send({ action: "last" });
+
+ await vi.waitFor(() =>
+ expect(mockSendModelValue).toHaveBeenCalledTimes(1),
+ );
+ expect(callback).not.toHaveBeenCalled();
+ response.resolve(null);
+ await Promise.all([sent, last]);
+ expect(callback).toHaveBeenCalledExactlyOnceWith();
+ expect(
+ mockSendModelValue.mock.calls.map(([request]) => request.message),
+ ).toEqual([
+ { method: "custom", content: { action: "first" } },
+ { method: "update", state: { count: 1 }, bufferPaths: [] },
+ { method: "custom", content: { action: "last" } },
+ ]);
+ });
+
+ it("continues sending after a failed update", async () => {
+ const model = await openModel();
+ const response = new Deferred<null>();
+ mockSendModelValue.mockReturnValueOnce(response.promise);
+ const logError = vi
+ .spyOn(Logger, "error")
+ .mockImplementation(() => undefined);
+ model.set("count", 1);
+ model.save_changes();
+ model.set("count", 2);
+ model.save_changes();
+ const last = model.send({ action: "done" });
+
+ await vi.waitFor(() =>
+ expect(mockSendModelValue).toHaveBeenCalledTimes(1),
+ );
+ const error = new Error("Network failure");
+ response.reject(error);
+ await last;
+ expect(mockSendModelValue).toHaveBeenCalledTimes(3);
+ expect(logError).toHaveBeenCalledWith(
+ "[anywidget] Failed to save model changes",
+ error,
+ );
+ });
+
+ it("allows different models to send independently", async () => {
+ const first = await openModel();
+ const secondId = asModelId("second-model");
+ const second = await openModel(secondId);
+ const response = new Deferred<null>();
+ mockSendModelValue.mockReturnValueOnce(response.promise);
+
+ const firstSend = first.send({ value: 1 });
+ await second.send({ value: 2 });
+ expect(
+ mockSendModelValue.mock.calls.map(([request]) => request.modelId),
+ ).toEqual([testId, secondId]);
+ response.resolve(null);
+ await firstSend;
+ });
+
+ it("drops queued messages when the model closes", async () => {
+ const model = await openModel();
+ const response = new Deferred<null>();
+ mockSendModelValue.mockReturnValueOnce(response.promise);
+ const first = model.send({ value: 1 });
+ model.set("count", 2);
+ model.save_changes();
+ const last = model.send({ value: 3 });
+
+ await vi.waitFor(() =>
+ expect(mockSendModelValue).toHaveBeenCalledTimes(1),
+ );
+ await handleWidgetMessage(registry, {
+ model_id: testId,
+ message: { method: "close" },
+ });
+ response.resolve(null);
+ await Promise.all([first, last]);
+ expect(mockSendModelValue).toHaveBeenCalledTimes(1);
+ });
+ });
+
describe("static mode", () => {
beforeEach(() => {
mockIsStatic.mockReturnValue(true);
diff --git a/frontend/src/plugins/impl/anywidget/model.ts b/frontend/src/plugins/impl/anywidget/model.ts
index b53a06cce5..f5638bb0e6 100644
--- a/frontend/src/plugins/impl/anywidget/model.ts
+++ b/frontend/src/plugins/impl/anywidget/model.ts
@@ -157,7 +157,9 @@ export class Model<T extends ModelState> implements AnyModel<T> {
// Clear the dirty fields to avoid sending again.
this.#dirtyFields.clear();
- this.#comm.sendUpdate(partialData);
+ this.#comm.sendUpdate(partialData).catch((error) => {
+ Logger.error("[anywidget] Failed to save model changes", error);
+ });
}
/**
diff --git a/frontend/src/plugins/impl/anywidget/registry.ts b/frontend/src/plugins/impl/anywidget/registry.ts
index 9a7dfa1aae..2355b9e627 100644
--- a/frontend/src/plugins/impl/anywidget/registry.ts
+++ b/frontend/src/plugins/impl/anywidget/registry.ts
@@ -1,6 +1,7 @@
/* Copyright 2026 Marimo. All rights reserved. */
import type { NotificationMessageData } from "@/core/kernel/messages";
import { getRequestClient } from "@/core/network/requests";
+import type { ModelRequest } from "@/core/network/types";
import { isStaticNotebook } from "@/core/static/static-state";
import { assertNever } from "@/utils/assertNever";
import {
@@ -10,6 +11,7 @@ import {
} from "@/utils/json/base64";
import { Logger } from "@/utils/Logger";
import { repl } from "@/utils/repl";
+import { Semaphore } from "@/utils/semaphore";
import { viewStateAtom } from "@/core/mode";
import { store } from "@/core/state/jotai";
import { createHost, type WidgetResolver } from "./host";
@@ -191,6 +193,20 @@ export async function handleWidgetMessage(
}
registry.createModel(modelId, (signal) => {
+ // Wait for the server to acknowledge queueing each message before
+ // sending the next one, preserving order within this model.
+ const sends = new Semaphore(1);
+ const sendMessage = (request: ModelRequest): Promise<void> =>
+ sends.run(async () => {
+ if (signal.aborted) {
+ Logger.debug(
+ `[Model] ${request.message.method} suppressed for model=${modelId} (signal aborted)`,
+ );
+ return;
+ }
+ await getRequestClient().sendModelValue(request);
+ });
+
// In static exports there is no kernel, so comm calls are no-ops.
const comm: MarimoComm<ModelState> = isStaticNotebook()
? {
@@ -199,28 +215,16 @@ export async function handleWidgetMessage(
}
: {
async sendUpdate(changeData) {
- if (signal.aborted) {
- Logger.debug(
- `[Model] sendUpdate suppressed for model=${modelId} (signal aborted)`,
- );
- return;
- }
const { state, buffers, bufferPaths } =
serializeBuffersToBase64(changeData);
- await getRequestClient().sendModelValue({
+ await sendMessage({
modelId,
message: { method: "update", state, bufferPaths },
buffers,
});
},
async sendCustomMessage(content, buffers) {
- if (signal.aborted) {
- Logger.debug(
- `[Model] sendCustomMessage suppressed for model=${modelId} (signal aborted)`,
- );
- return;
- }
- await getRequestClient().sendModelValue({
+ await sendMessage({
modelId,
message: { method: "custom", content },
buffers: buffers.map(dataViewToBase64),