ISSUE DESCRIPTION 🐛 Bug ❓: Variable name collision for SQL cells using same table name…
- User
ISSUE DESCRIPTION
🐛 Bug ❓: Variable name collision for SQL cells using same table name in different schemas
Discussed in https://github.com/marimo-team/marimo/discussions/9734
Originally posted by EED85 May 31, 2026
Description
When using multiple SQL cells in marimo with DuckDB, creating tables with the same name in different schemas leads to a variable redefinition error.
Although the tables are fully qualified and valid in DuckDB, marimo raises an error due to internal variable name collisions.
Minimal Reproducible Example
-- Cell 1 CREATE TABLE finance.datalake.xx (id INT);-- Cell 2 CREATE TABLE finance.information_layer.xx (id INT);ERROR
This cell wasn't run because it has errors This cell redefines variables from other cells. 'xx' was also defined by: dl Fix: Wrap in a function Why can't I redefine variables?Expected Behavior
Since the tables are created in different schemas, both statements should execute without conflict:
Environment
requires-python = ">=3.13" dependencies = [ "duckdb", "ipykernel>=7.2.0", "marimo>=0.23.8", "pandas>=3.0.3", "plotly>=6.7.0", "polars>=1.41.2", "pyarrow>=24.0.0", "pydantic-ai>=1.104.0", "ruff>=0.15.15", "sqlglot<30", "tabulate>=0.10.0", ]That is my opinion. What is the marimo way, to handle this?
Best Eric
Evaluation contract
Track SQL definitions by their complete qualified identity. Tables with the same leaf name in different schemas or catalogs are not multiply defined; the same fully qualified name, or the same unqualified name, still is. Preserve the user-facing table variable, defining-cell ownership, deletion behavior, and conflict reporting for genuine collisions.
Interface
Type: Function Name: get_multiply_defined Path: marimo/_runtime/dataflow/definitions.py Input: self Output: list[tuple[Name, set[CellId_t]]] Description: Returns a list of (name, cell_ids) tuples for names that are defined in multiple cells. Uses conflict-aware grouping so that qualified SQL names (e.g., schema.table) with the same leaf name are not considered multiply defined unless they share the exact same qualified name.
ADDITIONAL ADVICE
Since you are given a git repository, you can use git commands to simplify your work. For example, if you made a mistake and want to revert your changes, you can use
git checkout <file>to restore the file to its original state. You can also reset all changes in the repository using command. Additionally, you can use and to temporarily save your changes and restore them later. Finally, you can see the changes that you've made (which will be submitted when you call ) using or commands. However you don't need to use or before submitting your changes. In fact, only submits currently unstaged changes because it uses to get the changes that need to be submitted. Assistant
I'll start by exploring the repository structure and understanding the relevant files.
Assistant
I need to make one command at a time.
Assistant
Now let me understand the issue. Let me look at the relevant files to understand the data structures.
Assistant
Now let me look at the graph.py to understand how
register_definitionandget_multiply_definedare used.Assistant
Now let me look at the visitor to understand how SQL definitions are created and what
namevsqualified_nameare.Assistant
Now let me find all callers of
get_multiply_definedto understand the impact of changing the return type.Assistant
Let me look at the existing tests for the definitions module.
Assistant
Let me look at the callers in detail to understand how to handle the return type change.
Assistant
Assistant
Assistant
Assistant
OK this is getting complex. Let me reconsider the approach. I want to minimize risk while satisfying the contract.
The contract specifically defines the interface for
get_multiply_defined:Output: list[tuple[Name, set[CellId_t]]] Description: Returns a list of (name, cell_ids) tuples for names that are defined in multiple cells. Uses conflict-aware grouping so that qualified SQL names (e.g., schema.table) with the same leaf name are not considered multiply defined unless they share the exact same qualified name.So I need to:
- Track definitions by qualified identity.
Assistant
Let me find where the "redefines variables" / "was also defined by" error originates.
Assistant
Let me find where the
register_definitionreturn value (siblings) is used to produce the error message.Assistant
The
register_definitionreturn value (siblings) doesn't seem to be used in graph.py (line 102). Let me check the full register_cell to see if the return value is used.Assistant
So the return value of
register_definition(siblings) is NOT used. It's discarded. Good. So I don't need to worry about that.Now let me find where the "redefines variables from other cells" / "was also defined by" error comes from.
Assistant
So the error displayed in the frontend is
MultipleDefinitionErrorwhich hasnameandcellsfields. Let me look at the MultipleDefinitionError structure.Assistant
Now let me find where
MultipleDefinitionError(the messaging one) is created, to understand how the error gets to the frontend.Assistant
Assistant
Assistant
Assistant
Assistant
Good,
check_for_multiple_definitionsis the only place that does the conflict check vialen > 1. And I'll rewrite it. Let me also check the lintMultipleDefinitionsRule.Assistant
Good.
MultipleDefinitionsRuleusescheck_for_multiple_definitions. So fixingcheck_for_multiple_definitionsfixes the lint rule too.Now let me reproduce the bug first. Let me write a reproduction script.
Assistant
Now let me write a reproduction script.
Assistant
I need to install the dependencies. Let me install the package properly.
Assistant
I've reproduced the bug. Note:
- For the two-schema case:
definitions['xx'] = {'1','2'}andget_multiply_definedreturns['xx', 'df'](df is also flagged because both cells assigndf = mo.sql(...)— that's a real Python conflict, expected). check_for_multiple_definitionsreportsMultipleDefinitionError(name='xx', ...)ANDname='df'. The 'df' one is a genuine conflict (both cells assign to Python ). The 'xx' one is the bug.
- For the two-schema case:
Assistant
So
_defineaddsname(leaf "xx") toblock.defs. Socell.defscontains "xx" (leaf). Andcell.variable_data["xx"]has the VariableData with qualified_name="finance.datalake.xx".OK so the reproduction is accurate. The bug is the 'xx' conflict. The 'df' conflict in my repro is because I used
df = mo.sql(...)in both cells (genuine). Let me make a cleaner repro without the df assignment to match the issue exactly. But actually, in a real marimo notebook, SQL cells are pure SQL. Let me check how to parse a pure SQL cell. Actuallycompile_cellwith a string that's SQL... marimo detects SQL cells. Let me check.Actually, for the test, the existing tests use
df = mo.sql(...). Let me check if there's a way to register a pure SQL cell. Let me look at how the cell language is determined and whetherparse_cellcan take raw SQL.Actually, it doesn't matter much. The core bug is the 'xx' conflict reported by
check_for_multiple_definitionsandget_multiply_defined. Let me focus on the fix.Let me make a cleaner repro using a SQL cell. Let me check
compile_cellfor SQL.Assistant
compile_cellparses Python code. For SQL cells, the frontend sends SQL which is converted tomo.sql(...). So my repro usingdf = mo.sql(...)is the right approach. The 'df' conflict is a genuine one in my repro (both assign df). To match the issue exactly (no Python variable conflict), I should use different Python variable names or no assignment. But the issue's cells don't assign to anything. In marimo, a SQL cell without assignment still creates a result variable. Let me check.Actually, let me look at how a SQL cell with no LHS is handled. In the frontend, SQL cells get wrapped. Let me not go down this path. The key point: the bug is the 'xx' (table leaf) being flagged as multiply-defined. My repro confirms it. The 'df' is a separate genuine conflict that I introduced.
Let me adjust my repro to use different variable names per cell to avoid the df conflict, isolating the xx bug.
Assistant
Now I've cleanly reproduced the bug. With
dl = mo.sql(...)andil = mo.sql(...), the only multiply-defined name is 'xx' (the table leaf), which is the bug. The expected behavior is no conflict.Now let me implement the fix. Let me look at the full definitions.py once more and design.
My plan:
- Add conflict-identity tracking to the registry.
- Implement returning using conflict-aware grouping.
Assistant
Assistant
Assistant
Let me find where update_cell (re-registering a cell with new code) happens. Let me search the runtime.
Assistant
So
_deactivate_cellis called when re-registering. Let me check_deactivate_cell— does it calldelete_cell?Assistant
Assistant
Assistant
Let me check how
_xis classified. Let me look at the visitor's_on_defor where underscore vars become "temporary".Assistant
Let me check where
_xgets classified as a "temporary" vs "defs". Let me look at the visitor's handling of defs to understand if_xends up indefsortemporaries.Assistant
So
is_local(name)determines if a name is "local" (private/underscore).nonlocals = {name for name in v.defs if not is_local(name)}.temporaries = v.defs - nonlocals. Anddefs=nonlocals(the CellImpl.defs). So_x(whichis_localreturns True for) goes totemporaries, NOTdefs. Socell.defsdoesn't include_x. Andregister_celliteratescell.variable_data.items()— which is{name: ... for name in nonlocals}. So_xis NOT invariable_dataeither (since variable_data only has nonlocals). So_xis never registered. So no conflict. ✓ My fix doesn't affect this.Good. So
test_underscore_variables_are_privatestill passes.Now let me verify
is_local:Assistant
Good. So
_xis local → not incell.defs/variable_data→ not registered. My fix doesn't affect underscore variables.Now let me implement. Let me start with definitions.py.
Let me re-read the current definitions.py once more and write the new version.
Actually, I have the full file content already. Let me write the new version using the
editcommand orcreate. Let me useopentheneditto make targeted changes.Let me make the changes to definitions.py:
- Add new dataclass fields.
- Add
_conflict_identitystatic method. - Update
register_definitionto track conflict identities. - Update
unregister_definitionsto clean up conflict tracking. - Update
get_multiply_definedto return tuples with conflict-aware grouping.
Let me open the file and make edits.
Assistant
Now let me make the edits. First, the dataclass fields:
Assistant
Now let me update
register_definitionto track conflict identities and add the helper method:Assistant
Now let me update
unregister_definitionsto clean up conflict tracking:Assistant
Now let me update
get_multiply_defined:Assistant
Now let me update the
graph.pywrapper's return type annotation:Assistant
Let me open graph.py and edit the line directly.
Assistant
Now let me update
check_for_multiple_definitionsin validate_graph.py:Assistant
Now let me update the caller in
app.py:Assistant
Now let me update the
_code_mode/_context.pycaller:Assistant
Assistant
The test
test_ctx_create_cell_multiply_definedexpects:RuntimeError: Multiply-defined names: - 'x' is already defined in cell 'cell_a' (cell_a)So with
cell_idsfor the conflict group {cell_a (existing), new_cell (registered)},cell_ids - registered_ids= {cell_a}. Soexisting = {cell_a}, labels = "cell_a (cell_a)". Message: " - 'x' is already defined in cell 'cell_a' (cell_a)". ✓This matches the expected snapshot. Good. So using
cell_idsworks for this test.Let me now write the edit for _context.py.
Assistant
There's a duplicate
if new_cycles:block (lines 1631-1638). Let me remove the duplicate.Assistant
Now the duplicate is removed. Now let me update the
to_ir.pycaller:Assistant
Now let me update the
_ai/_tools/tools/dependency_graph.pycaller:Assistant
Now let me run my reproduction script to verify the fix:
Assistant
The bug is fixed. Now
get_multiply_definedreturns[]andcheck_for_multiple_definitionsreturns{}for the two-schema case. Let me verify the conflict cases still work correctly:Assistant
All cases work as expected:
- Same qualified name → conflict ✓
- Unqualified SQL + Python → conflict ✓
- Python + qualified SQL → no conflict ✓
- Two unqualified SQL same leaf → conflict ✓
- Python x twice → conflict ✓
- Unregister removes conflict ✓
- catalog.schema.table vs schema.table same leaf, different identity → no conflict ✓
Now let me run the existing tests to check for regressions. Let me run the relevant test files.
Assistant
Assistant
test_multiply_defined_variablesfailed. Let me check it — it's probably asserting the old format.Assistant
The test
_make_tool_with_graphcreates a mock graph withdefinitions={"x": {"c1", "c2"}}but it's a MOCK — it doesn't go throughregister_definition, soconflict_definitionsis empty (the mock doesn't populate it). Let me look at how the test sets up the graph.Assistant
The test mocks
graph.get_multiply_defined.return_value = [name for name, defs in definitions.items() if len(defs) > 1](a list of NAMES, the old format). My caller code now unpacks tuples (the new contract format). So this mock-based test is outdated — it needs updating to return tuples. Per the instructions, I leave it (can't modify tests), and it's in the "needs updating" category.Let me verify my
dependency_graph.pychange is correct and robust for a REAL graph (avoiding the set-sorting TypeError that the naivesorted(graph.get_multiply_defined())would hit):Assistant
Good — the edge case of two different qualified identities with the same leaf name both being conflicts works without TypeError. The sorting logic
sorted(name for name, _ in md)correctly avoids comparing sets.Now let me run the broader test suites to check for other regressions. Let me run test_app, test_cli_export, and a subset of test_runtime that's relevant.
Assistant
Several
test_appfailures related todefsoverrides. Let me check if these are due to my change or pre-existing. Let me look at one.Assistant
These failures are due to missing
pytest-asyncio(async tests not natively supported), NOT due to my change. The config hasasyncio_modewhich requirespytest-asyncio. Let me install it to confirm these are pre-existing/environmental failures.Assistant
So with
pytest-asyncioinstalled, on the BASE (stashed) code, these tests pass. Now let me run them WITH my changes to see if they still pass (now that async is supported).Assistant
Those failures were purely environmental (missing
pytest-asyncio). Let me run the fulltest_app.pynow with async support:Assistant
All
test_app.pytests pass. Now let me run thetest_dataflow.pyandtest_dependency_graph.pyagain to confirm only the expected API-change failures remain, plustest_cli_exportandtest_runtime:Assistant
Let me check the
test_cli_export.pyfailures —test_export_watch_*— to see if they're related to my change or environmental.Assistant
The
test_cli_export.py::test_export_watch_*failures are PRE-EXISTING (they fail on the base code too, due to "Static files not found, skipping mount" — an environmental issue). Not related to my change.So the only failures related to my change are:
Assistant
Let me check the SQL-related tests that were skipped (require SQL deps). The skip says "SQL deps not available" — let me check what that means and install if needed.
Assistant
Let me look at the full TestSQL class to find tests that exercise SQL definition conflict scenarios:
Assistant
These tests pass. Let me also run the scratchpad integration test that tests the
_code_mode/_context.pydry-run path (test_ctx_create_cell_multiply_defined), since I modified that code.Assistant
The scratchpad integration tests pass, confirming my
_code_mode/_context.pychanges work correctly (the dry-run multiply-defined detection still produces the expected error message).Now let me run the lint tests for the
MultipleDefinitionsRuleto make sure it still works:Assistant
There's a snapshot test failure in
test_mixed_issues_snapshot. Let me check if this is pre-existing or due to my change.Assistant
The test passes on the base code, but fails with my change. AND it modified the snapshot file
tests/_lint/snapshots/mixed_issues_errors.txt(inline_snapshot auto-updated it). I need to revert that snapshot file change since I shouldn't modify tests/snapshots. Let me first understand WHY my change affected this lint snapshot test.Assistant
So
mixed_issues.pyhas two cells definingBar(both Python classBar), and one cell definingos. TheBardefinitions are a genuine multiple-definition conflict (two cells defineBar). My change shouldn't affect that — both are Python, identity "Bar", conflict group {c1, c2}.Wait, but the test failed. Let me look at the actual diff between expected and actual. The earlier output showed extra content being added. Let me look more carefully.
Assistant
So my output (with changes) produces multiple-definitions for 'a', 'c', 'b', 'foo', 'Bar', 'os'. Let me compare with the expected snapshot.
Assistant
The expected snapshot order:
a,b,c,foo,Bar,os. My output order:a,c,b,foo,Bar,os. Sobandcare swapped — an ordering difference. The OLDcheck_for_multiple_definitionsiterated sorted leaf names; my NEW version iteratesconflict_definitionsinsertion order. Let me look at how the rule engine orders diagnostics.Assistant
So
_validate_graphbuildsnames: dict[str, list[_ErrorInfo]]keyed byerror.name(the leaf). It iteratesvalidation_errors.items()(cell_id -> error_list). For each error, it doesnames.setdefault(error.name, []).append(...). So the ORDER ofnamesdict (insertion order) depends on the order errors are encountered.Assistant
Assistant
Interesting! The BASE code produces
Bar a b c foo os(sorted leaf names: "Bar" < "a" < "b" ... in ASCII). But the SNAPSHOT showsa b c foo Bar os!Wait, that contradicts. The base code produces "Bar a b c foo os" but the snapshot expects "a b c foo Bar os". Yet the snapshot test PASSES on base?! Let me look at the full
snapshot()function in test_snapshot.py — maybe it does order-insensitive comparison.Assistant
So the
snapshot()function does an EXACT text comparison (result != expected). It's order-sensitive. And it auto-WRITES the result if it differs (write_result()thenpytest.fail). That's why my earlier run "updated" the snapshot file (which I reverted).So the snapshot is exact and order-sensitive. The base code produces "Bar a b c foo os" per my show_lint. But the snapshot file contains "a b c foo Bar os". And the test PASSED on base. Contradiction! Let me carefully re-verify by reverting the snapshot, stashing my changes, and checking everything together:
Assistant
Now it's consistent! The original snapshot order IS "Bar a b c foo os" (ASCII-sorted by leaf name). I had misread earlier. The base produces "Bar a b c foo os" and matches. My change produces "a c b foo Bar os" (insertion order) — which differs and breaks the snapshot.
To preserve the existing deterministic order (and not break the snapshot), I should make
get_multiply_definedreturn results sorted by the user-facing leaf name. This reproduces the OLDcheck_for_multiple_definitionsbehavior (which iterated sorted leaf names). Let me update:Assistant
Now let me verify the snapshot test passes and the bug is still fixed:
Assistant
The snapshot tests pass now. Let me re-run the full lint test suite and confirm only the expected API-change failures remain:
Assistant
All lint tests pass. Let me re-run the repro scripts to confirm the bug fix still holds:
Assistant
All good. Now let me re-run the broader test suites to confirm only the expected API-change failures remain:
Assistant
So the only failures are the 3 expected API-change-related tests:
test_sql_table_schema_to_python_ref— asserts old["t1"]format.test_sql_table_schema_to_python_ref_rev— asserts old["t1"]format.test_multiply_defined_variables— mock returns old format (names instead of tuples).
These are all "tests that need updating to reflect the API change" required by the contract. Per the instructions, I leave them unmodified and they're ignored by the evaluation.
Let me double-check there are no other usages of
get_multiply_definedI might have missed across the whole repo:Assistant
All non-test callers are updated. Let me check test usages to understand the full picture:
Assistant
Let me look at the test_dataflow.py tests around those lines to fully understand them:
Assistant
So:
test_redefine_sql_table_diff_schema: Pythont1+ SQLschema1.t1→assert multiply_defined == []. My change:[]. ✓ PASSES.test_sql_table_schema_to_python_ref: SQL unqualifiedt1+ Pythont1→assert multiply_defined == ["t1"]. My change:[('t1', {'0','1'})]. ✗ FAILS (old format — needs updating).test_sql_table_schema_to_python_ref_rev: same. ✗ FAILS (old format — needs updating).
The 2 that fail assert the old
["t1"]format. These need updating to[("t1", {"0", "1"})]. Per instructions, ignored.Let me run a broader regression sweep to be thorough — test_save (uses
graph.definitions) and convert tests:Assistant
That looks like a crash (segfault) — possibly environmental (pyarrow/numpy). Let me run them separately and on a smaller scope:
Assistant
The crash is environmental (a segfault during collection, likely from importing something with pyarrow/numpy). Let me verify it's environmental by stashing and running the same:
Assistant
The crash happens on the BASE code too — it's purely environmental (a segfault during test collection). NOT related to my change. Let me run test_convert alone:
Assistant
test_convert passes (187 passed). The
to_ir.pychange works fine. The_save/crash is environmental (happens on base too).Let me run the messaging and JSON encoder tests for
MultipleDefinitionErrorserialization:Assistant
All pass. Now let me do a final review of my complete diff to ensure correctness and clean code:
Assistant
The diff looks good. Let me review the other files' diffs:
Assistant
All diffs look correct and clean. Let me review the
_context.pydiff:Assistant
All changes look correct and clean.
Now, let me reconsider one subtle point in
_context.py. The original logic for the diff was by NAME. My version also diffs by name (preserving semantics). And I changedexisting = graph.get_defining_cells(name) - registered_idstoexisting = cell_ids - registered_ids, which is more precise (only reports actual conflicting cells, not non-conflicting same-leaf cells in different schemas). This aligns with the contract ("conflict reporting for genuine collisions").Let me run the full scratchpad integration tests to be safe (they use inline_snapshot which auto-updates — I need to make sure I don't accidentally leave snapshot changes):
Assistant
All 10 scratchpad tests pass. Let me verify no snapshot/test files were accidentally modified by the test runs:
Assistant
Only the 7 source files I intended to modify are changed. No test/snapshot files modified.
Let me double-check there are no other places that treat
len(definitions[name]) > 1as a conflict (which would still falsely report the two-schema case):Assistant
That's a completely unrelated
definitions(jedi completion), not the registry. So no other place treatsdefinitions[leaf]len > 1 as a conflict.So my fix is complete and correct. The only conflict-detection paths are:
get_multiply_defined(now conflict-aware) ✓check_for_multiple_definitions(now uses get_multiply_defined) ✓
Both are fixed.
Let me do a final comprehensive run of the most relevant test files to confirm the state:
Assistant
All pass. Let me do a final confirmation of the issue fix and the expected API-change test failures:
Assistant
Everything is as expected:
- The issue is fixed: two SQL cells with the same table name in different schemas no longer conflict (
get_multiply_definedreturns[],check_for_multiple_definitionsreturns{}). - The 2
test_dataflowfailures are because they assert the OLD return type["t1"](now[("t1", {"0","1"})]per the contract's requiredlist[tuple[Name, set[CellId_t]]]return type). These are tests that need updating to reflect the API change, which the instructions say to leave unmodified.
Let me verify the final repo state has only my intended source changes (no test/snapshot modifications):
- The issue is fixed: two SQL cells with the same table name in different schemas no longer conflict (
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.