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.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
fix: prevent duplicate execution of nested marimo custom elements (#8286)
Myles Scolnick243e406dd8f3
diff --git a/frontend/src/plugins/core/__test__/registerReactComponent.test.ts b/frontend/src/plugins/core/__test__/registerReactComponent.test.tsnew file mode 100644index 0000000000..0425cd7540--- /dev/null+++ b/frontend/src/plugins/core/__test__/registerReactComponent.test.ts@@ -0,0 +1,204 @@+/* Copyright 2026 Marimo. All rights reserved. */++import ReactDOM from "react-dom/client";+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";+import { z } from "zod";+import {+ isCustomMarimoElement,+ registerReactComponent,+} from "../registerReactComponent";++// Each custom element name can only be registered once per jsdom window,+// so we use a counter to generate unique tag names across tests.+let tagCounter = 0;+function uniqueTag(base: string) {+ return `marimo-test-${base}-${++tagCounter}`;+}++function makePlugin(tagName: string) {+ return {+ tagName,+ validator: z.any(),+ render: () => null as never,+ };+}++describe("isCustomMarimoElement", () => {+ test("returns false for null", () => {+ expect(isCustomMarimoElement(null)).toBe(false);+ });++ test("returns false for a regular HTMLElement", () => {+ const div = document.createElement("div");+ expect(isCustomMarimoElement(div)).toBe(false);+ });++ test("returns false for a non-HTMLElement", () => {+ const svg = document.createElementNS(+ "http://www.w3.org/2000/svg",+ "circle",+ );+ expect(isCustomMarimoElement(svg as Element)).toBe(false);+ });++ test("returns true for a registered marimo custom element", () => {+ const tag = uniqueTag("is-custom");+ registerReactComponent(makePlugin(tag));+ const el = document.createElement(tag);+ expect(isCustomMarimoElement(el)).toBe(true);+ });++ test("returns false for an element with wrong __type__ value", () => {+ const div = document.createElement("div") as unknown as HTMLElement & {+ __type__: string;+ };+ div.__type__ = "something_else";+ expect(isCustomMarimoElement(div)).toBe(false);+ });+});++describe("connectedCallback - light DOM nesting detection", () => {+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ let createRootSpy: any;+ const mockRoot = {+ render: vi.fn(),+ unmount: vi.fn(),+ };++ beforeEach(() => {+ createRootSpy = vi+ .spyOn(ReactDOM, "createRoot")+ .mockReturnValue(mockRoot as unknown as ReactDOM.Root);+ });++ afterEach(() => {+ createRootSpy.mockRestore();+ mockRoot.render.mockClear();+ mockRoot.unmount.mockClear();+ });++ test("skips mounting when element is a light DOM child of another marimo element", () => {+ const parentTag = uniqueTag("parent");+ const childTag = uniqueTag("child");+ registerReactComponent(makePlugin(parentTag));+ registerReactComponent(makePlugin(childTag));++ const parent = document.createElement(parentTag);+ const child = document.createElement(childTag);+ parent.append(child);++ createRootSpy.mockClear();+ document.body.append(parent);++ // Only the parent should mount; the child is skipped because it+ // detects a marimo ancestor in the light DOM.+ expect(createRootSpy).toHaveBeenCalledTimes(1);+ expect(createRootSpy).toHaveBeenCalledWith(parent.shadowRoot);++ parent.remove();+ });++ test("mounts when element is not nested inside a marimo element", () => {+ const tag = uniqueTag("standalone");+ registerReactComponent(makePlugin(tag));++ const el = document.createElement(tag);+ createRootSpy.mockClear();++ document.body.append(el);++ expect(createRootSpy).toHaveBeenCalledTimes(1);+ expect(createRootSpy).toHaveBeenCalledWith(el.shadowRoot);++ el.remove();+ });++ test("mounts when nested inside a regular (non-marimo) element", () => {+ const tag = uniqueTag("in-div");+ registerReactComponent(makePlugin(tag));++ const wrapper = document.createElement("div");+ const el = document.createElement(tag);+ wrapper.append(el);++ createRootSpy.mockClear();+ document.body.append(wrapper);++ expect(createRootSpy).toHaveBeenCalledTimes(1);+ expect(createRootSpy).toHaveBeenCalledWith(el.shadowRoot);++ wrapper.remove();+ });++ test("skips mounting for deeply nested marimo element through non-marimo wrappers", () => {+ const outerTag = uniqueTag("outer");+ const innerTag = uniqueTag("inner");+ registerReactComponent(makePlugin(outerTag));+ registerReactComponent(makePlugin(innerTag));++ const outer = document.createElement(outerTag);+ const div = document.createElement("div");+ const inner = document.createElement(innerTag);++ // Structure: outer > div > inner+ outer.append(div);+ div.append(inner);++ createRootSpy.mockClear();+ document.body.append(outer);++ // Only outer mounts; inner is skipped because a marimo ancestor+ // is found when traversing through the intermediate div.+ expect(createRootSpy).toHaveBeenCalledTimes(1);+ expect(createRootSpy).toHaveBeenCalledWith(outer.shadowRoot);++ outer.remove();+ });++ test("mounts both sibling marimo elements (neither is a child of the other)", () => {+ const tagA = uniqueTag("sibling-a");+ const tagB = uniqueTag("sibling-b");+ registerReactComponent(makePlugin(tagA));+ registerReactComponent(makePlugin(tagB));++ const wrapper = document.createElement("div");+ const a = document.createElement(tagA);+ const b = document.createElement(tagB);+ wrapper.append(a);+ wrapper.append(b);++ createRootSpy.mockClear();+ document.body.append(wrapper);++ // Both siblings should mount since neither is a child of the other.+ expect(createRootSpy).toHaveBeenCalledTimes(2);++ wrapper.remove();+ });++ test("mounts when element is inside the shadow DOM of another marimo element", () => {+ const outerTag = uniqueTag("shadow-outer");+ const innerTag = uniqueTag("shadow-inner");+ registerReactComponent(makePlugin(outerTag));+ registerReactComponent(makePlugin(innerTag));++ const outer = document.createElement(outerTag);+ const inner = document.createElement(innerTag);++ // Place the inner element inside the outer element's shadow root,+ // simulating how getChildren() -> renderHTML() re-creates children+ // in the shadow DOM. parentElement traversal stays within the+ // shadow root boundary, so inner should NOT detect outer as an+ // ancestor and should mount normally.+ outer.shadowRoot?.append(inner);++ createRootSpy.mockClear();+ document.body.append(outer);++ // Both elements should mount: outer in the document, inner in the+ // shadow root (parentElement traversal doesn't cross shadow boundary).+ expect(createRootSpy).toHaveBeenCalledTimes(2);++ outer.remove();+ });+});diff --git a/frontend/src/plugins/core/registerReactComponent.tsx b/frontend/src/plugins/core/registerReactComponent.tsxindex da266ceb12..c2ca922764 100644--- a/frontend/src/plugins/core/registerReactComponent.tsx+++ b/frontend/src/plugins/core/registerReactComponent.tsx@@ -316,6 +316,15 @@ export function registerReactComponent<T>(plugin: IPlugin<T, unknown>): void {}connectedCallback() {+ // Skip mounting if this element is in the light DOM of another+ // marimo custom element. The parent element's shadow DOM will+ // re-create this element via getChildren() -> renderHTML(), so+ // this light DOM copy should remain inert to avoid duplicate+ // side-effects (e.g., mo.lazy firing load() twice).+ if (this.isLightDOMChildOfMarimoElement()) {+ return;+ }+if (!this.mounted) {// Create a React root on the shadow rootinvariant(this.shadowRoot, "Shadow root should exist");@@ -348,6 +357,30 @@ export function registerReactComponent<T>(plugin: IPlugin<T, unknown>): void {}}+ /**+ * Check if this element is in the light DOM of another marimo+ * custom element. When a marimo element (e.g. marimo-tabs) has+ * children that are also marimo elements (e.g. marimo-lazy), the+ * browser upgrades both the light DOM originals AND the shadow DOM+ * copies created by renderHTML(). The light DOM copies should not+ * mount since they are not rendered (no <slot>) and would cause+ * duplicate side-effects.+ *+ * parentElement traversal stays within the same DOM tree boundary+ * (shadow root or document), so shadow DOM copies never find a+ * marimo ancestor and correctly return false.+ */+ private isLightDOMChildOfMarimoElement(): boolean {+ let parent = this.parentElement;+ while (parent) {+ if (isCustomMarimoElement(parent)) {+ return true;+ }+ parent = parent.parentElement;+ }+ return false;+ }+/*** Reset the plugin initial value and data.* And then re-render the plugin.diff --git a/marimo/_smoke_tests/issues/5129.py b/marimo/_smoke_tests/issues/5129.pynew file mode 100644index 0000000000..a9ce448721--- /dev/null+++ b/marimo/_smoke_tests/issues/5129.py@@ -0,0 +1,34 @@+# Regression test for https://github.com/marimo-team/marimo/issues/5129+# mo.lazy inside mo.ui.tabs should only execute the function once.+# Previously, the shadow DOM created a duplicate marimo-lazy element+# which fired a second load() request.++import marimo++__generated_with = "0.13.14"+app = marimo.App(width="medium")+++def _():+ import marimo as mo++ def lazy_tab():+ import time++ print("LAZYTAB 1")+ time.sleep(1)+ print("LAZYTAB 2")+ return mo.md("Finish loading lazy tab !")++ mo.ui.tabs(+ {+ "normal-tab": mo.md("This is a normal tab"),+ "lazy-tab": mo.lazy(lazy_tab),+ }+ )+ return+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_smoke_tests/nested.py b/marimo/_smoke_tests/nested.pynew file mode 100644index 0000000000..ad0f461cd4--- /dev/null+++ b/marimo/_smoke_tests/nested.py@@ -0,0 +1,405 @@+# Smoke tests for nested marimo custom elements.+# Verifies that interactive widgets, lazy loading, and layout components+# work correctly when nested inside each other (especially inside shadow DOM).+# Related: https://github.com/marimo-team/marimo/issues/5129++import marimo++__generated_with = "0.19.11"+app = marimo.App(width="medium")+++def _():+ import marimo as mo++ return (mo,)++[email protected](hide_code=True)+def _(mo):+ mo.md("""+ # Nested components smoke tests+ """)+ return++[email protected](hide_code=True)+def _(mo):+ mo.md("""+ ## Table inside tabs+ """)+ return+++def _(mo):+ import pandas as pd++ df = pd.DataFrame({"name": ["Alice", "Bob", "Charlie"], "age": [25, 30, 35]})+ table_in_tabs = mo.ui.tabs(+ {+ "Table": mo.ui.table(df),+ "Plain": mo.md("No table here"),+ }+ )+ table_in_tabs+ return (pd,)++[email protected](hide_code=True)+def _(mo):+ mo.md("""+ ## Table inside accordion+ """)+ return+++def _(mo, pd):+ df2 = pd.DataFrame({"x": [1, 2, 3], "y": [4, 5, 6]})+ mo.accordion(+ {+ "Show table": mo.ui.table(df2),+ "Show text": mo.md("Just text"),+ }+ )+ return++[email protected](hide_code=True)+def _(mo):+ mo.md("""+ ## Lazy inside tabs (issue #5129)+ """)+ return+++def _(mo):+ call_count_1 = []+++ def lazy_fn_1():+ call_count_1.append(1)+ print(f"lazy_fn_1 called (total: {len(call_count_1)}x)")+ return mo.md(f"Loaded! Call count: {len(call_count_1)}")+++ lazy_tabs = mo.ui.tabs(+ {+ "Normal": mo.md("This tab is normal"),+ "Lazy": mo.lazy(lazy_fn_1, show_loading_indicator=True),+ }+ )+ lazy_tabs+ return++[email protected](hide_code=True)+def _(mo):+ mo.md("""+ ## Lazy inside accordion+ """)+ return+++def _(mo):+ call_count_2 = []+++ def lazy_fn_2():+ call_count_2.append(1)+ print(f"lazy_fn_2 called (total: {len(call_count_2)}x)")+ return mo.md(f"Loaded! Call count: {len(call_count_2)}")+++ mo.accordion(+ {+ "Click to lazy load": mo.lazy(lazy_fn_2, show_loading_indicator=True),+ }+ )+ return++[email protected](hide_code=True)+def _(mo):+ mo.md("""+ ## Tabs with `lazy=True`+ """)+ return+++def _(mo, pd):+ df3 = pd.DataFrame({"a": range(10), "b": range(10, 20)})++ auto_lazy_tabs = mo.ui.tabs(+ {+ "Tab A": mo.md("First tab content"),+ "Tab B": mo.ui.table(df3),+ "Tab C": mo.md("Third tab content"),+ },+ lazy=True,+ )+ auto_lazy_tabs+ return++[email protected](hide_code=True)+def _(mo):+ mo.md("""+ ## Accordion with `lazy=True`+ """)+ return+++def _(mo):+ mo.accordion(+ {+ "Section 1": mo.md("Content 1"),+ "Section 2": mo.md("Content 2"),+ "Section 3": mo.md("Content 3"),+ },+ lazy=True,+ )+ return++[email protected](hide_code=True)+def _(mo):+ mo.md("""+ ## Interactive widgets inside tabs+ """)+ return+++def _(mo):+ slider = mo.ui.slider(0, 100, value=50, label="Slider in tab")+ checkbox = mo.ui.checkbox(label="Checkbox in tab")+ dropdown = mo.ui.dropdown(+ ["Option A", "Option B", "Option C"], label="Dropdown in tab"+ )+ text_input = mo.ui.text(placeholder="Type here...", label="Text in tab")+ return checkbox, dropdown, slider, text_input+++def _(checkbox, dropdown, mo, slider, text_input):+ widget_tabs = mo.ui.tabs(+ {+ "Slider": mo.vstack([slider, mo.md(f"Value: {slider.value}")]),+ "Checkbox": mo.vstack([checkbox, mo.md(f"Checked: {checkbox.value}")]),+ "Dropdown": mo.vstack(+ [dropdown, mo.md(f"Selected: {dropdown.value}")]+ ),+ "Text": mo.vstack([text_input, mo.md(f"Typed: {text_input.value}")]),+ }+ )+ widget_tabs+ return++[email protected](hide_code=True)+def _(mo):+ mo.md("""+ ## Tabs inside tabs+ """)+ return+++def _(mo):+ inner_tabs = mo.ui.tabs(+ {+ "Inner A": mo.md("Inner tab A"),+ "Inner B": mo.md("Inner tab B"),+ }+ )+ outer_tabs = mo.ui.tabs(+ {+ "Outer 1": inner_tabs,+ "Outer 2": mo.md("Outer tab 2"),+ }+ )+ outer_tabs+ return++[email protected](hide_code=True)+def _(mo):+ mo.md("""+ ## Accordion inside tabs+ """)+ return+++def _(mo):+ mo.ui.tabs(+ {+ "With accordion": mo.accordion(+ {+ "Section A": mo.md("Accordion content A"),+ "Section B": mo.md("Accordion content B"),+ }+ ),+ "Plain tab": mo.md("Just a plain tab"),+ }+ )+ return++[email protected](hide_code=True)+def _(mo):+ mo.md("""+ ## Tabs inside accordion+ """)+ return+++def _(mo):+ mo.accordion(+ {+ "Open for tabs": mo.ui.tabs(+ {+ "Tab X": mo.md("Tab X content"),+ "Tab Y": mo.md("Tab Y content"),+ }+ ),+ }+ )+ return++[email protected](hide_code=True)+def _(mo):+ mo.md("""+ ## Lazy table inside tabs+ """)+ return+++def _(mo, pd):+ def lazy_table():+ print("lazy_table called")+ df = pd.DataFrame({"col1": range(5), "col2": range(5, 10)})+ return mo.ui.table(df)+++ mo.ui.tabs(+ {+ "Normal": mo.md("Normal content"),+ "Lazy table": mo.lazy(lazy_table, show_loading_indicator=True),+ }+ )+ return++[email protected](hide_code=True)+def _(mo):+ mo.md("""+ ## Deeply nested: lazy inside accordion inside tabs+ """)+ return+++def _(mo):+ def deep_lazy_fn():+ print("deep_lazy_fn called")+ return mo.md("Deeply nested lazy content loaded!")+++ mo.ui.tabs(+ {+ "Top tab": mo.accordion(+ {+ "Open for lazy": mo.lazy(+ deep_lazy_fn, show_loading_indicator=True+ ),+ }+ ),+ "Other tab": mo.md("Other"),+ }+ )+ return++[email protected](hide_code=True)+def _(mo):+ mo.md("""+ ## hstack/vstack inside tabs+ """)+ return+++def _(mo):+ mo.ui.tabs(+ {+ "Horizontal": mo.hstack(+ [mo.md("**Left**"), mo.md("**Center**"), mo.md("**Right**")],+ justify="space-between",+ ),+ "Vertical": mo.vstack(+ [mo.md("**Top**"), mo.md("**Middle**"), mo.md("**Bottom**")],+ gap=1,+ ),+ }+ )+ return++[email protected](hide_code=True)+def _(mo):+ mo.md("""+ ## Callout inside tabs+ """)+ return+++def _(mo):+ mo.ui.tabs(+ {+ "Info": mo.callout(mo.md("This is an info callout"), kind="info"),+ "Warning": mo.callout(mo.md("This is a warning callout"), kind="warn"),+ "Danger": mo.callout(mo.md("This is a danger callout"), kind="danger"),+ }+ )+ return++[email protected](hide_code=True)+def _(mo):+ mo.md("""+ ## Form inside tabs+ """)+ return+++def _(mo):+ form = mo.ui.text(placeholder="Enter name").form()+ return (form,)+++def _(form, mo):+ mo.ui.tabs(+ {+ "Form tab": form,+ "Result tab": mo.md(f"Submitted: {form.value}"),+ }+ )+ return+++if __name__ == "__main__":+ app.run()