Code mode: two code edits of one cell in a batch corrupt the kernel graph

Open
#11,173 2 comments 0 reactions 1 assignee View on GitHub

Maintainers usually reply within 1 day

@manzt is already working on this.

Since Oct 12, 2026.

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
30/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Active
Tech stack
python
Domain
backend

Research direction

Start in AsyncCodeModeContext._dry_run_compile in marimo/_code_mode/_context.py, around the evicted[cell_id] = graph.cells[cell_id] line and the finally block that re-registers evicted cells, and check _validate_ops in marimo/_code_mode/_plan.py. Run the three cases from the reproduction script. Done means a rejected batch leaves the graph unchanged, an accepted batch matches the document, and a regression test with two code edits of one cell passes.

Written by the indexing model from the issue text.

Description

Describe the bug

When one code-mode batch edits the code of the same cell twice (two edit_cell(cid, code=...) calls, or create_cell followed by edit_cell on the new id), the dry-run validation leaves dry-run code in the real kernel graph. Three cases in the script below: (1) the batch is rejected with Multiply-defined names, yet the graph now holds the first edit and cell b has lost its parent while the document is unchanged; (2) an edit followed by a revert succeeds, but the graph keeps the intermediate code w = 5, and since the document did not change nothing repairs it; (3) a rejected batch that creates and then edits a cell leaves a definition owned by a cell that is not in the graph, so a later valid create_cell("z = 3") is rejected until the kernel restarts. Passing skip_validation=True for that later create does not help either: the cell is accepted but lands in marimo-error, because the graph still defines z in the phantom cell.

Output on 0.25.1:

python: 3.12.3
marimo: 0.25.1
case 1: batch raised RuntimeError
case 1 observed: graph a = 'w = 5', parents of b = set(), document a = 'x = 1'
case 1 expected: graph a = 'x = 1', parents of b = {'a'}, document a = 'x = 1'
edited code of cell 'a'
edited code of cell 'a'
case 2 observed: graph a = 'w = 5', defs = {'w'}, document a = 'x = 1'
case 2 expected: graph a = 'x = 1', defs = {'x'}, document a = 'x = 1'
case 3: first batch raised RuntimeError
case 3 observed: graph cells = ['a'], definitions = {'x': {'a'}, 'z': {'JVXe'}}
case 3 expected: graph cells = ['a'], definitions = {'x': {'a'}}
case 3 second batch observed: RuntimeError: Multiply-defined names: - 'z' is already defined in cell 'JVXe' To skip validation, use: async with cm.get_context(skip_validation=True) as ctx
case 3 second batch expected: ok

Expected: a rejected batch leaves the graph exactly as it was, an accepted batch leaves the graph matching the document, and no definitions point at cells that are not in the graph.

Cause, at origin/main baddf23e9: AsyncCodeModeContext._dry_run_compile in marimo/_code_mode/_context.py evicts the current cell before registering the new version with evicted[cell_id] = graph.cells[cell_id] (line 1671, same pattern for deletes at line 1658). On the second op for the same cell, graph.cells[cell_id] is the cell that the first op registered during the dry run, so the original CellImpl is overwritten. The finally block (lines 1716-1726) deletes the dry-run cells and then re-registers every evicted entry, which puts the dry-run cell back into the real graph. For a cell created in the same batch, the evicted entry is a dry-run cell that was never in the graph, and reorder_nodes(original_order) drops it from the topology while its definitions stay. _validate_ops in marimo/_code_mode/_plan.py (lines 144-182) does not reject repeated updates of one cell, and the existing test_two_config_edits_in_one_batch only edits config, so it never reaches the eviction path.

Proposed fix: record the eviction only once per cell (evicted.setdefault(cell_id, graph.cells[cell_id])), and for a cell this dry run registered itself, delete it instead of evicting it, so the finally block only restores cells that were in the graph before the dry run. A test with two code edits of one cell where the second edit fails validation, asserting the graph is unchanged, would pin it.

I can open a PR for this if the approach sounds right.

Will you submit a PR?
  • Yes
Environment
{
  "marimo": "0.25.1",
  "editable": false,
  "OS": "Linux",
  "OS Version": "7.1.5-76070105-generic",
  "Processor": "x86_64",
  "Python Version": "3.12.3",
  "Locale": "en_US",
  "Binaries": {
    "uv": "0.11.7 (x86_64-unknown-linux-gnu)"
  },
  "Dependencies": {
    "click": "8.5.0",
    "docutils": "0.23",
    "itsdangerous": "2.2.0",
    "jedi": "0.20.0",
    "markdown": "3.11",
    "narwhals": "2.26.0",
    "packaging": "26.3",
    "psutil": "7.2.2",
    "pygments": "2.21.0",
    "pymdown-extensions": "11.0.2",
    "pyyaml": "6.0.3",
    "starlette": "1.7.0",
    "tomlkit": "0.15.1",
    "typing-extensions": "4.16.0",
    "uvicorn": "0.54.0",
    "websockets": "17.2"
  },
  "Optional Dependencies": {
    "loro": "1.16.2"
  },
  "Experimental Flags": {
    "multi_column": true,
    "cache_panel": true,
    "isolate_apps": true
  }
}
Code to reproduce
"""Two code edits of one cell in a single code-mode batch corrupt the kernel graph.

Runs an in-process kernel, no server, no network.
"""

import asyncio
import collections
import sys

import marimo
from marimo._ast.app_config import _AppConfig
from marimo._code_mode._context import AsyncCodeModeContext
from marimo._config.config import DEFAULT_CONFIG
from marimo._messaging.notebook.document import (
    NotebookCell,
    NotebookDocument,
    notebook_document_context,
)
from marimo._messaging.streams import (
    ThreadSafeStderr,
    ThreadSafeStdin,
    ThreadSafeStdout,
    ThreadSafeStream,
)
from marimo._messaging.types import KernelStreams
from marimo._runtime.commands import AppMetadata, ExecuteCellCommand
from marimo._runtime.kernel_lifecycle import KernelArgs, kernel_session
from marimo._session.model import SessionMode


class NullStream(ThreadSafeStream):
    def __init__(self, *args, **kwargs):
        import threading

        self.pipe = None
        self.input_queue = None
        self.redirect_console = False
        self.cell_id = None
        self.stream_lock = threading.Lock()
        self.console_msg_cv = threading.Condition(threading.Lock())
        self.console_msg_queue = collections.deque()

    def write(self, data):
        pass


def new_kernel():
    stream = NullStream()
    streams = KernelStreams(
        stream=stream,
        stdout=ThreadSafeStdout(stream),
        stderr=ThreadSafeStderr(stream),
        stdin=ThreadSafeStdin(stream),
    )
    args = KernelArgs(
        streams=streams,
        debugger=None,
        configs={},
        app_metadata=AppMetadata(
            query_params={},
            filename=None,
            cli_args={},
            argv=None,
            app_config=_AppConfig(),
        ),
        user_config=DEFAULT_CONFIG,
        mode=SessionMode.EDIT,
        control_queue=asyncio.Queue(),
        set_ui_element_queue=asyncio.Queue(),
        virtual_file_storage="in_memory",
    )
    return kernel_session(args)


def document_for(k):
    return NotebookDocument(
        [
            NotebookCell(id=cid, code=c.code, name="", config=c.config)
            for cid, c in k.graph.cells.items()
        ]
    )


async def main():
    print(f"python: {sys.version.split()[0]}")
    print(f"marimo: {marimo.__version__}")

    # Case 1: the second edit is rejected, the graph is still rewritten.
    with new_kernel() as (k, _):
        await k.run(
            [
                ExecuteCellCommand(cell_id="a", code="x = 1"),
                ExecuteCellCommand(cell_id="b", code="y = x + 1"),
            ]
        )
        doc = document_for(k)
        with notebook_document_context(doc):
            ctx = AsyncCodeModeContext(k, skip_staleness_check=True)
            try:
                async with ctx as nb:
                    nb.edit_cell("a", code="w = 5")
                    nb.edit_cell("a", code="y = 5")  # clashes with cell b
            except Exception as e:
                print(f"case 1: batch raised {type(e).__name__}")
        print(f"case 1 observed: graph a = {k.graph.cells['a'].code!r}, "
              f"parents of b = {k.graph.parents['b']}, "
              f"document a = {doc.get_cell('a').code!r}")
        print("case 1 expected: graph a = 'x = 1', parents of b = {'a'}, "
              "document a = 'x = 1'")

    # Case 2: edit then revert in one batch succeeds, graph keeps the first edit.
    with new_kernel() as (k, _):
        await k.run([ExecuteCellCommand(cell_id="a", code="x = 1")])
        doc = document_for(k)
        with notebook_document_context(doc):
            ctx = AsyncCodeModeContext(k, skip_staleness_check=True)
            async with ctx as nb:
                nb.edit_cell("a", code="w = 5")
                nb.edit_cell("a", code="x = 1")
        cell = k.graph.cells["a"]
        print(f"case 2 observed: graph a = {cell.code!r}, defs = {set(cell.defs)}, "
              f"document a = {doc.get_cell('a').code!r}")
        print("case 2 expected: graph a = 'x = 1', defs = {'x'}, "
              "document a = 'x = 1'")


    # Case 3: create + edit of the new cell in a failed batch leaves a phantom
    # definition, so a later valid create of the same name is rejected.
    with new_kernel() as (k, _):
        await k.run([ExecuteCellCommand(cell_id="a", code="x = 1")])
        doc = document_for(k)
        with notebook_document_context(doc):
            ctx = AsyncCodeModeContext(k, skip_staleness_check=True)
            try:
                async with ctx as nb:
                    cid = nb.create_cell("z = 1")
                    nb.edit_cell(cid, code="z = 2")
                    nb.create_cell("x = 9")  # clashes with cell a
            except Exception as e:
                print(f"case 3: first batch raised {type(e).__name__}")
            print(f"case 3 observed: graph cells = {sorted(k.graph.cells)}, "
                  f"definitions = {dict(sorted(k.graph.definitions.items()))}")
            print("case 3 expected: graph cells = ['a'], "
                  "definitions = {'x': {'a'}}")
            ctx = AsyncCodeModeContext(k, skip_staleness_check=True)
            try:
                async with ctx as nb:
                    nb.create_cell("z = 3")
                print("case 3 second batch: ok")
            except Exception as e:
                msg = " ".join(str(e).split())
                print(f"case 3 second batch observed: {type(e).__name__}: {msg}")
            print("case 3 second batch expected: ok")


asyncio.run(main())
Dominant language
Python
Stars
22.9k
Forks
1.3k
Avg merge
1d 10h
Merged PRs (30d)
380

Getting set up

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from marimo-team/marimo

All issues in marimo-team/marimo

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.