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: non-deterministic random object-ids for session caching (#3874)

Myles Scolnick046d6dcd9b6f
diff --git a/frontend/src/core/dom/uiregistry.ts b/frontend/src/core/dom/uiregistry.ts
index db890f80ba..bcce235878 100644
--- a/frontend/src/core/dom/uiregistry.ts
+++ b/frontend/src/core/dom/uiregistry.ts
@@ -1,4 +1,5 @@
/* Copyright 2024 Marimo. All rights reserved. */
+import { Logger } from "@/utils/Logger";
import type { CellId, UIElementId } from "../cells/ids";
import {
type ValueType,
@@ -134,7 +135,9 @@ export class UIElementRegistry {
buffers: string[] | undefined | null,
): void {
const entry = this.entries.get(objectId);
- if (entry !== undefined) {
+ if (entry === undefined) {
+ Logger.warn("UIElementRegistry missing entry", objectId);
+ } else {
const base64ToDataView = (base64: string) => {
const bytes = window.atob(base64);
const buffer = new ArrayBuffer(bytes.length);
@@ -176,7 +179,9 @@ export class UIElementRegistry {
value: ValueType,
): void {
const entry = this.entries.get(objectId);
- if (entry !== undefined) {
+ if (entry === undefined) {
+ Logger.warn("UIElementRegistry missing entry", objectId);
+ } else {
entry.value = value;
entry.elements.forEach((element) => {
if (element !== initiator) {
diff --git a/marimo/_plugins/ui/_core/ui_element.py b/marimo/_plugins/ui/_core/ui_element.py
index b1742c3fc6..27010b41dc 100644
--- a/marimo/_plugins/ui/_core/ui_element.py
+++ b/marimo/_plugins/ui/_core/ui_element.py
@@ -114,7 +114,14 @@ class UIElement(Html, Generic[S, T], metaclass=abc.ABCMeta):
_value_frontend: S
_value: T
- _random_seed = random.Random(42)
+ # We want this to be fully random in production,
+ # otherwise cached session state could use incorrect object-ids.
+ # And changing object-ids are a way to force a re-render.
+ #
+ # This does mean that snapshotting exports in CI will produce
+ # different object-ids. If this is a problem, we can allow a
+ # fixed seed via an environment variable.
+ _random_seed = random.Random()
def __init__(
self,
diff --git a/tests/conftest.py b/tests/conftest.py
index 971874c67f..c293d4c38f 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -43,6 +43,17 @@ if TYPE_CHECKING:
register_formatters()
[email protected](autouse=True)
+def patch_random_seed(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Patch UIElement._random_seed to use a fixed seed for testing"""
+ import random
+
+ from marimo._plugins.ui._core.ui_element import UIElement
+
+ # Patch the random seed to be deterministic for testing
+ monkeypatch.setattr(UIElement, "_random_seed", random.Random(42))
+
+
@dataclasses.dataclass
class _MockStream(ThreadSafeStream):
"""Captures the ops sent through the stream"""