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: rtc code duplication and disconnection, other syncing bugfixes (#3989)

Myles Scolnickaab90ce02b11
diff --git a/frontend/src/components/editor/cell/code/cell-editor.tsx b/frontend/src/components/editor/cell/code/cell-editor.tsx
index 069ca112a8..487d32b042 100644
--- a/frontend/src/components/editor/cell/code/cell-editor.tsx
+++ b/frontend/src/components/editor/cell/code/cell-editor.tsx
@@ -270,8 +270,12 @@ const CellEditorInternal = ({
const handleInitializeEditor = useEvent(() => {
// If rtc is enabled, use collaborative editing
- if (getFeatureFlag("rtc")) {
- const rtc = realTimeCollaboration(cellId);
+ if (getFeatureFlag("rtc_v2")) {
+ const rtc = realTimeCollaboration(cellId, (code) => {
+ // It's not really a formatting change,
+ // but this means it won't be marked as stale
+ updateCellCode({ cellId, code, formattingChange: true });
+ });
extensions.push(rtc.extension);
code = rtc.code;
}
@@ -291,8 +295,12 @@ const CellEditorInternal = ({
const handleReconfigureEditor = useEvent(() => {
invariant(editorViewRef.current !== null, "Editor view is not initialized");
// If rtc is enabled, use collaborative editing
- if (getFeatureFlag("rtc")) {
- const rtc = realTimeCollaboration(cellId);
+ if (getFeatureFlag("rtc_v2")) {
+ const rtc = realTimeCollaboration(cellId, (code) => {
+ // It's not really a formatting change,
+ // but this means it won't be marked as stale
+ updateCellCode({ cellId, code, formattingChange: true });
+ });
extensions.push(rtc.extension);
}
@@ -310,8 +318,16 @@ const CellEditorInternal = ({
const handleDeserializeEditor = useEvent(() => {
invariant(serializedEditorState, "Editor view is not initialized");
- if (getFeatureFlag("rtc")) {
- const rtc = realTimeCollaboration(cellId, code);
+ if (getFeatureFlag("rtc_v2")) {
+ const rtc = realTimeCollaboration(
+ cellId,
+ (code) => {
+ // It's not really a formatting change,
+ // but this means it won't be marked as stale
+ updateCellCode({ cellId, code, formattingChange: true });
+ },
+ code,
+ );
extensions.push(rtc.extension);
}
@@ -529,6 +545,6 @@ function WithWaitUntilConnected<T extends {}>(
return WaitUntilConnectedComponent;
}
-export const CellEditor = getFeatureFlag("rtc")
+export const CellEditor = getFeatureFlag("rtc_v2")
? WithWaitUntilConnected(memo(CellEditorInternal))
: memo(CellEditorInternal);
diff --git a/frontend/src/core/cells/__tests__/cells.test.ts b/frontend/src/core/cells/__tests__/cells.test.ts
index a5be6ca636..1dca862861 100644
--- a/frontend/src/core/cells/__tests__/cells.test.ts
+++ b/frontend/src/core/cells/__tests__/cells.test.ts
@@ -1331,6 +1331,51 @@ describe("cell reducer", () => {
});
});
+ it("can can add a new cell with/without stale code", () => {
+ actions.setCellCodes({
+ codes: ["new code"],
+ ids: ["2"] as CellId[],
+ codeIsStale: false,
+ });
+
+ expect(state.cellData["2" as CellId].code).toBe("new code");
+ expect(state.cellData["2" as CellId].edited).toBe(false);
+ expect(state.cellData["2" as CellId].lastCodeRun).toBe("new code");
+
+ actions.setCellCodes({
+ codes: ["new code 2"],
+ ids: ["9"] as CellId[],
+ codeIsStale: true,
+ });
+
+ expect(state.cellData["9" as CellId].code).toBe("new code 2");
+ expect(state.cellData["9" as CellId].edited).toBe(true);
+ expect(state.cellData["9" as CellId].lastCodeRun).toBe(null);
+ });
+
+ it("can partial update cell codes", () => {
+ actions.createNewCell({ cellId: firstCellId, before: false });
+ actions.createNewCell({ cellId: "1" as CellId, before: false });
+
+ expect(state.cellIds.inOrderIds).toEqual(["0", "1", "2"]);
+ expect(state.cellData["0" as CellId].code).toBe("");
+ expect(state.cellData["1" as CellId].code).toBe("");
+ expect(state.cellData["2" as CellId].code).toBe("");
+
+ // Update cell 1
+ actions.setCellCodes({
+ codes: ["new code 2"],
+ ids: ["1"] as CellId[],
+ codeIsStale: false,
+ });
+
+ expect(state.cellIds.inOrderIds).toEqual(["0", "1", "2"]);
+ expect(state.cellData["0" as CellId].code).toBe("");
+ expect(state.cellData["1" as CellId].code).toBe("new code 2");
+ expect(state.cellData["1" as CellId].edited).toBe(false);
+ expect(state.cellData["2" as CellId].code).toBe("");
+ });
+
it("can set cell codes with new cell ids, while preserving the old cell data", () => {
actions.setCellCodes({
codes: ["code1", "code2", "code3"],
diff --git a/frontend/src/core/cells/cells.ts b/frontend/src/core/cells/cells.ts
index 333833827d..382cd27bfa 100644
--- a/frontend/src/core/cells/cells.ts
+++ b/frontend/src/core/cells/cells.ts
@@ -47,7 +47,7 @@ import {
type CellIndex,
MultiColumn,
} from "@/utils/id-tree";
-import { isEqual } from "lodash-es";
+import { isEqual, zip } from "lodash-es";
import { isErrorMime } from "../mime";
export const SCRATCH_CELL_ID = "__scratch__" as CellId;
@@ -797,12 +797,30 @@ const {
cellId: CellId,
) => {
if (!cell) {
- return createCell({ id: cellId, code });
+ return createCell({
+ id: cellId,
+ code,
+ lastCodeRun: action.codeIsStale ? null : code,
+ edited: action.codeIsStale && code.trim().length > 0,
+ });
}
+ // If code is stale, we don't promote it to lastCodeRun
+ const lastCodeRun = action.codeIsStale ? cell.lastCodeRun : code;
+
+ // Mark as edited if the code has changed
+ const edited = lastCodeRun
+ ? lastCodeRun.trim() !== code.trim()
+ : Boolean(code);
+
// No change
if (cell.code.trim() === code.trim()) {
- return cell;
+ return {
+ ...cell,
+ code: code,
+ edited,
+ lastCodeRun,
+ };
}
// Update codemirror if mounted
@@ -811,24 +829,18 @@ const {
updateEditorCodeFromPython(cellHandle.editorView, code);
}
- // If code is stale, we don't promote it to lastCodeRun
- const lastCodeRun = action.codeIsStale ? cell.lastCodeRun : code;
-
return {
...cell,
code: code,
- // Mark as edited if the code has changed
- edited: lastCodeRun
- ? lastCodeRun.trim() !== code.trim()
- : Boolean(code),
+ edited,
lastCodeRun,
};
};
- for (let i = 0; i < action.codes.length; i++) {
- const cellId = action.ids[i];
- const code = action.codes[i];
-
+ for (const [cellId, code] of zip(action.ids, action.codes)) {
+ if (cellId === undefined || code === undefined) {
+ continue;
+ }
nextState = {
...nextState,
cellData: {
diff --git a/frontend/src/core/codemirror/rtc/__tests__/cell-manager.test.ts b/frontend/src/core/codemirror/rtc/__tests__/cell-manager.test.ts
index c539735585..4ec3165fc3 100644
--- a/frontend/src/core/codemirror/rtc/__tests__/cell-manager.test.ts
+++ b/frontend/src/core/codemirror/rtc/__tests__/cell-manager.test.ts
@@ -19,7 +19,10 @@ import { connectionAtom } from "@/core/network/connection";
// Mock dependencies
vi.mock("y-websocket", () => ({
- WebsocketProvider: vi.fn(),
+ WebsocketProvider: vi.fn().mockImplementation(() => ({
+ on: vi.fn(),
+ destroy: vi.fn(),
+ })),
}));
vi.mock("@/core/kernel/session", () => ({
@@ -34,6 +37,7 @@ describe("CellProviderManager", () => {
doc: {
getText: vi.fn(),
},
+ on: vi.fn(),
destroy: vi.fn(),
};
const mockYText = {};
@@ -72,6 +76,7 @@ describe("CellProviderManager", () => {
params: {
session_id: "test-session",
},
+ resyncInterval: 5000,
},
);
expect(provider).toBe(mockProvider);
@@ -110,6 +115,7 @@ describe("CellProviderManager", () => {
session_id: "test-session",
file: "/path/to/file.py",
},
+ resyncInterval: 5000,
},
);
});
diff --git a/frontend/src/core/codemirror/rtc/cell-manager.ts b/frontend/src/core/codemirror/rtc/cell-manager.ts
index b6754e0b80..cb5b76b689 100644
--- a/frontend/src/core/codemirror/rtc/cell-manager.ts
+++ b/frontend/src/core/codemirror/rtc/cell-manager.ts
@@ -7,6 +7,7 @@ import { getSessionId } from "@/core/kernel/session";
import { connectionAtom } from "@/core/network/connection";
import { WebSocketState } from "@/core/websocket/types";
import { store } from "@/core/state/jotai";
+import { Logger } from "@/utils/Logger";
const DOC_KEY = "code";
const LANGUAGE_KEY = "language";
@@ -39,17 +40,12 @@ export class CellProviderManager {
};
}
- // Wait for connection to be established
- // while (store.get(connectionAtom).state !== WebSocketState.OPEN) {
- // await new Promise((resolve) => setTimeout(resolve, 100));
- // }
-
const ydoc = new Y.Doc();
const ytext = ydoc.getText(DOC_KEY);
const ylanguage = ydoc.getText(LANGUAGE_KEY);
-
- // Replace
- if (initialCode && ytext.length === 0) {
+ // Handle initial code. This is only used if a cell is brought back
+ // from being deleted.
+ if (initialCode) {
ytext.doc?.transact(() => {
ytext.delete(0, ytext.length);
ytext.insert(0, initialCode);
@@ -65,8 +61,21 @@ export class CellProviderManager {
params.file = filePath;
}
- const provider = new WebsocketProvider("ws", cellId, ydoc, { params });
+ const provider = new WebsocketProvider("ws", cellId, ydoc, {
+ params,
+ // This serves as a heartbeat to keep the connection alive
+ // otherwise, the connection will close and can lead to data loss
+ // or duplicate code from an awkward rsync.
+ resyncInterval: 5000,
+ });
+
this.providers.set(cellId, provider);
+ provider.on("connection-close", () => {
+ Logger.warn("RTC: connection closed. This could lead to data loss.");
+ });
+ provider.on("connection-error", () => {
+ Logger.warn("RTC: connection error. This could lead to data loss.");
+ });
return { provider, ytext, ylanguage };
}
diff --git a/frontend/src/core/codemirror/rtc/extension.ts b/frontend/src/core/codemirror/rtc/extension.ts
index eba59bde50..fefef43a1b 100644
--- a/frontend/src/core/codemirror/rtc/extension.ts
+++ b/frontend/src/core/codemirror/rtc/extension.ts
@@ -16,6 +16,7 @@ import { Logger } from "@/utils/Logger";
export function realTimeCollaboration(
cellId: CellId,
+ updateCellCode: (code: string) => void,
initialCode = "",
): { extension: Extension; code: string } {
if (isWasm()) {
@@ -26,7 +27,42 @@ export function realTimeCollaboration(
}
const manager = CellProviderManager.getInstance();
- const { ytext, ylanguage } = manager.getOrCreateProvider(cellId, initialCode);
+ const { ytext, ylanguage, provider } = manager.getOrCreateProvider(
+ cellId,
+ initialCode,
+ );
+
+ // Code sync plugin
+ const codeSync = ViewPlugin.define((view) => {
+ const handleSync = (isSynced: boolean) => {
+ Logger.debug(`RTC: sync=${isSynced}, ytext.length=${ytext.toJSON()}`);
+
+ // If it's not synced, update the editor code
+ if (!isSynced) {
+ const code = ytext.toJSON();
+ view.dispatch({
+ changes: {
+ from: 0,
+ to: view.state.doc.length,
+ insert: code,
+ },
+ });
+ }
+
+ // If it's synced, update the cell code
+ if (isSynced) {
+ updateCellCode(ytext.toJSON());
+ }
+ };
+
+ // Wait for provider to connect before initializing with local code
+ provider.on("sync", handleSync);
+ return {
+ destroy() {
+ provider.off("sync", handleSync);
+ },
+ };
+ });
// Create a view plugin to observe language changes
const languageObserver = ViewPlugin.define((view) => {
@@ -70,7 +106,12 @@ export function realTimeCollaboration(
}
});
- const extension = [languageObserver, languageListener, yCollab(ytext, null)];
+ const extension = [
+ languageObserver,
+ languageListener,
+ codeSync,
+ yCollab(ytext, null),
+ ];
return {
code: ytext.toJSON(),
diff --git a/frontend/src/core/config/feature-flag.tsx b/frontend/src/core/config/feature-flag.tsx
index 341e7d21ce..16e65dcf80 100644
--- a/frontend/src/core/config/feature-flag.tsx
+++ b/frontend/src/core/config/feature-flag.tsx
@@ -11,7 +11,7 @@ export interface ExperimentalFeatures {
inline_ai_tooltip: boolean;
wasm_layouts: boolean;
scratchpad: boolean;
- rtc: boolean;
+ rtc_v2: boolean;
reactive_tests: boolean;
// Add new feature flags here
}
@@ -21,18 +21,13 @@ const defaultValues: ExperimentalFeatures = {
inline_ai_tooltip: import.meta.env.DEV,
wasm_layouts: false,
scratchpad: true,
- rtc: false,
+ rtc_v2: false,
reactive_tests: false,
};
export function getFeatureFlag<T extends keyof ExperimentalFeatures>(
feature: T,
): ExperimentalFeatures[T] {
- // Disable "rtc", regardless of the user's configuration, until
- // it is more stable.
- if (feature === "rtc") {
- return false;
- }
return (
(getResolvedMarimoConfig().experimental?.[
feature
diff --git a/marimo/_server/api/endpoints/ws.py b/marimo/_server/api/endpoints/ws.py
index 3beccffce1..92fb2968e5 100644
--- a/marimo/_server/api/endpoints/ws.py
+++ b/marimo/_server/api/endpoints/ws.py
@@ -92,7 +92,7 @@ async def websocket_endpoint(
config = app_state.config_manager_at_file(file_key).get_config()
- rtc_enabled: bool = config.get("experimental", {}).get("rtc", False)
+ rtc_enabled: bool = config.get("experimental", {}).get("rtc_v2", False)
auto_instantiate = config["runtime"]["auto_instantiate"]
await WebsocketHandler(
@@ -150,9 +150,9 @@ async def send_updates(
update = await update_queue.get()
message = create_update_message(update)
await websocket.send_bytes(message)
- except Exception:
- LOGGER.debug(
- f"Could not send Y update to client for cell with ID {cell_id}",
+ except Exception as e:
+ LOGGER.warning(
+ f"RTC: Could not send Y update to client for cell with ID {cell_id}: {str(e)}",
)
@@ -164,10 +164,23 @@ async def clean_cell(
async with ycell_lock:
if cell_id_and_file_key in ycells:
ycell = ycells[cell_id_and_file_key]
+ # Double-check client count before removing
if not ycell.clients:
+ LOGGER.debug(
+ f"RTC: Removing cell {cell_id_and_file_key.cell_id} as it has no clients"
+ )
+ # Store the YDoc state before removing it
+ # This could be used to restore state for quick reconnects if needed
del ycells[cell_id_and_file_key]
+ else:
+ LOGGER.warning(
+ f"RTC: Cell {cell_id_and_file_key.cell_id} not found in ycells dict during cleanup"
+ )
except asyncio.CancelledError:
# Task was cancelled due to client reconnection
+ LOGGER.debug(
+ f"RTC: clean_cell task cancelled for cell {cell_id_and_file_key.cell_id} - likely due to reconnection"
+ )
pass
@@ -190,6 +203,7 @@ async def ycell_provider(
)
if file_key is None:
+ LOGGER.warning("RTC: Closing websocket - no file key")
await websocket.close(
WebSocketCodes.NORMAL_CLOSE, "MARIMO_NO_FILE_KEY"
)
@@ -198,6 +212,9 @@ async def ycell_provider(
manager = app_state.session_manager
session = manager.get_session_by_file_key(file_key)
if session is None:
+ LOGGER.warning(
+ f"RTC: Closing websocket - no session found for file key {file_key}"
+ )
await websocket.close(WebSocketCodes.FORBIDDEN, "MARIMO_NOT_ALLOWED")
return
await websocket.accept()
@@ -209,6 +226,9 @@ async def ycell_provider(
ydoc = ycell.ydoc
ycell.clients += 1
if ycell.cleaner is not None:
+ LOGGER.debug(
+ f"RTC: Cancelling existing cleaner for cell {cell_id}"
+ )
ycell.cleaner.cancel()
ycell.cleaner = None
else:
@@ -216,8 +236,14 @@ async def ycell_provider(
mgr = file_manager.app.cell_manager
if mgr.has_cell(cell_id):
code = mgr.cell_data_at(cell_id).code
+ LOGGER.debug(
+ f"RTC: Creating new ydoc for existing cell {cell_id} with code length {len(code)}"
+ )
else:
code = ""
+ LOGGER.debug(
+ f"RTC: Creating new ydoc for new cell {cell_id} with empty code"
+ )
ydoc = Doc[Text]()
ytext = ydoc.get("code", type=Text)
ylang = ydoc.get("language", type=Text)
@@ -239,18 +265,30 @@ async def ycell_provider(
reply = handle_sync_message(message[1:], ydoc)
if reply is not None:
await websocket.send_bytes(reply)
- except Exception:
+ except WebSocketDisconnect:
+ # Normal disconnection
+ pass
+ except Exception as e:
+ LOGGER.warning(
+ f"RTC: Exception in websocket loop for cell {cell_id}: {str(e)}"
+ )
pass
finally:
+ # Cleanup cell resources
+ # Start the cleanup task timer
task.cancel()
ydoc.unobserve(subscription)
async with ycell_lock:
ycell.clients -= 1
if not ycell.clients:
if ycell.cleaner is not None:
+ LOGGER.warning(
+ f"RTC: Cancelling existing cleaner for cell {cell_id}"
+ )
ycell.cleaner.cancel()
ycell.cleaner = None
- ycell.cleaner = asyncio.create_task(clean_cell(key, 0))
+ # Timeout of 60 seconds to allow for client reconnection
+ ycell.cleaner = asyncio.create_task(clean_cell(key, 60.0))
KIOSK_ONLY_OPERATIONS = {
diff --git a/marimo/_server/api/lifespans.py b/marimo/_server/api/lifespans.py
index 6bef4ffb71..0193759713 100644
--- a/marimo/_server/api/lifespans.py
+++ b/marimo/_server/api/lifespans.py
@@ -24,7 +24,11 @@ from marimo import _loggers
from marimo._server.api.interrupt import InterruptHandler
from marimo._server.api.utils import open_url_in_browser
from marimo._server.model import SessionMode
-from marimo._server.print import print_shutdown, print_startup
+from marimo._server.print import (
+ print_experimental_features,
+ print_shutdown,
+ print_startup,
+)
from marimo._server.utils import initialize_mimetypes
from marimo._server.uvicorn_utils import close_uvicorn
@@ -107,6 +111,8 @@ async def logging(app: Starlette) -> AsyncIterator[None]:
network=state.host == "0.0.0.0",
)
+ print_experimental_features(state.config_manager.get_config())
+
yield
# Shutdown message
diff --git a/marimo/_server/print.py b/marimo/_server/print.py
index f21005a781..4b7a4245c6 100644
--- a/marimo/_server/print.py
+++ b/marimo/_server/print.py
@@ -6,6 +6,7 @@ import sys
from typing import Optional
from marimo._cli.print import bold, green, muted
+from marimo._config.config import MarimoConfig
from marimo._server.utils import print_, print_tabbed
UTF8_SUPPORTED = False
@@ -99,3 +100,29 @@ def _colorized_url(url_string: str) -> str:
def _utf8(msg: str) -> str:
return msg if UTF8_SUPPORTED else ""
+
+
+def print_experimental_features(config: MarimoConfig) -> None:
+ if "experimental" not in config:
+ return
+
+ keys = set(config["experimental"].keys())
+
+ # These experiments have been released
+ finished_experiments = {
+ "rtc",
+ "chat_sidebar",
+ "multi_column",
+ "scratchpad",
+ "tracing",
+ "markdown",
+ "sql_engines",
+ }
+ keys = keys - finished_experiments
+
+ if len(keys) == 0:
+ return
+
+ print_tabbed(
+ f"{_utf8('🧪')} {green('Experimental features (use with caution)')}: {', '.join(keys)}"
+ )
diff --git a/tests/_server/api/endpoints/test_ws.py b/tests/_server/api/endpoints/test_ws.py
index 9c241357ea..fcf06ea862 100644
--- a/tests/_server/api/endpoints/test_ws.py
+++ b/tests/_server/api/endpoints/test_ws.py
@@ -15,7 +15,11 @@ from starlette.websockets import WebSocketDisconnect
from marimo._config.manager import UserConfigManager
from marimo._messaging.ops import KernelCapabilities, KernelReady
-from marimo._server.api.endpoints.ws import CellIdAndFileKey, WebSocketCodes
+from marimo._server.api.endpoints.ws import (
+ CellIdAndFileKey,
+ WebSocketCodes,
+ clean_cell,
+)
from marimo._server.model import SessionMode
from marimo._server.sessions import SessionManager
from marimo._utils.parse_dataclass import parse_raw
@@ -359,7 +363,7 @@ def flush_messages(
def rtc_enabled(config: UserConfigManager):
prev_config = config.get_config()
try:
- config.save_config({"experimental": {"rtc": True}})
+ config.save_config({"experimental": {"rtc_v2": True}})
yield
finally:
config.save_config(prev_config)
@@ -513,8 +517,12 @@ async def test_ycell_cleanup_after_close(
cell_ws.close()
# Cell should still exist
- # Default timeout is 0 so it should be cleaned up immediately
- await asyncio.sleep(0.1)
+ assert key in ycells
+
+ # Wait for cleanup
+ await clean_cell(key, timeout=0.01)
+
+ # Cell should be removed
assert key not in ycells
client.post("/api/kernel/shutdown", headers=HEADERS)