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
Let me explore the repository structure and understand the codebase first.
Assistant
Now let me understand the issue. The
get_multiply_definedmethod returnslist[Name]but the contract says it should returnlist[tuple[Name, set[CellId_t]]]. Let me look at how it's currently used.Assistant
Now let me look at the existing tests for the dataflow to understand the current expected behavior:
Assistant
Let me look at more of the test file to understand the existing tests around SQL redefinition:
Assistant
Now let me reproduce the issue from the bug report. Let me write a test script:
Assistant
Let me check if there's a way to run the tests already, or check if duckdb is installed:
Assistant
Let me try running the existing tests to see if there's a proper test setup:
Assistant
Now let me reproduce the bug from the issue:
Assistant
I reproduced the bug. Both
xx(the SQL table leaf name) is considered multiply defined. Notedfis genuinely multiply defined because both cells assign todf. Let me test with different variable names:Assistant
I've reproduced the bug. The two tables
finance.datalake.xxandfinance.information_layer.xxare considered multiply defined because they share the leaf namexx, but they have different qualified names. Now let me examine all the callers ofget_multiply_defined:Assistant
Now let me understand the callers. The callers use
graph.get_multiply_defined()as a list of names in various ways. The contract requires the function to returnlist[tuple[Name, set[CellId_t]]]. Let me look at the graph wrapper:Assistant
Now let me look at how the multiply-defined error is reported to the user:
Assistant
Now let me look at how the "redefines variables" error is shown to the user during execution. Let me search for where
register_definitionsiblings are used:Assistant
The return value of
register_definition(siblings) isn't used in graph.py. Let me search more broadly for where the "redefines" error comes from:Assistant
Now let me find where
MultipleDefinitionErroris raised (not the one in app.py, but in the runtime):Assistant
Let me look at where
check_for_multiple_definitionsis called and how the error surfaces:Assistant
Let me look at how
definitionsis exposed and how the validation flows:Assistant
Let me look at how edges are computed for SQL references:
Assistant
Let me look at the
_definemethod and howcell.defsis set:Assistant
So
_defineis called with the leaf name_table.table(e.g.,xx), and it adds the leaf name toblock.defsandblock.variable_data. Thedefined_names.add(_table.qualified_name)adds the qualified name to a separatedefined_namesset, which is used to avoid adding refs for the same name.Now let me check what
cell.defscontains. Thedefscomes from the block'sdefsset, which would contain the leaf namexx. Let me verify.Assistant
Let me check what
cell.defscontains for the SQL cell:Assistant
Let me look at the ipynb conversion usage more carefully:
Assistant
Let me look at the
delete_cellmethod and how unregister works:Assistant
Let me look at the runtime.py usage of get_defining_cells:
Assistant
Let me check the test mock for
get_multiply_defined:Assistant
This test mock sets
graph.get_multiply_defined.return_value = [name for name, defs in definitions.items() if len(defs) > 1]which is a list of strings. If I change the return type tolist[tuple[Name, set[CellId_t]]], this mock would need updating. But I can't modify tests. The contract says to ignore tests that break because they need updating.Let me look at how this mock is used in the test to understand if it would cause issues.
Assistant
Let me look at how
dependency_graph.pybuilds themultiply_definedresult:Assistant
Let me look at the
GetCellDependencyGraphOutputtype:Assistant
Let me search for tests related to
check_for_multiple_definitionsand the validate_graph:Assistant
Let me check the lint rules that use
check_for_multiple_definitions:Assistant
OK so
graph.pyin lint rules also usescheck_for_multiple_definitionsand accesseserror.name. Since I'm updatingcheck_for_multiple_definitionsto useget_multiply_defined, theMultipleDefinitionErrorstill has anamefield. Thenamewould now be the qualified name (for SQL) or leaf name (for Python). For the lint rule, the_get_variable_line_infouses the name to find the line info. For SQL, the qualified name would be used to look up the variable in the cell. Let me check if that would work...Actually, let me look at
_get_variable_line_info:Assistant
OK, so
_get_variable_line_infouses aVariableLineVisitorto find the variable definition in the cell code. If the name is a qualified SQL name (e.g.,finance.datalake.xx), the visitor might not find it (since the cell code hasCREATE TABLE finance.datalake.xx, and the visitor looks for variablefinance.datalake.xx). But there's a fallback to cell line info, so it wouldn't crash.Actually, let me check the
VariableLineVisitor:Assistant
The
VariableLineVisitorlooks for Python variable names. For SQL, the cell code isdf = mo.sql("CREATE TABLE ...")which is a Python call tomo.sql. The SQL table name wouldn't be found byVariableLineVisitor. So the fallback would be used (cell line info). That's fine - it won't crash.Now let me look at the
_code_mode/_context.pyusage more carefully to understand how to handle the set operations:Assistant
Now I have a good understanding. Let me also check the
_ast/app.pyMultipleDefinitionError:Assistant
Let me check the
NameTransformerinto_ir.py:Assistant
Let me verify the edge computation won't break. Let me check what refs the SQL cell has:
Assistant
Now I have a thorough understanding. Let me check other usages of
definitionsin graph.py that might be affected:Assistant
Let me check where
get_deleted_nonlocal_refis used:Assistant
Let me check the
dataflow/__init__.pyusage ofget_defining_cells:Assistant
Let me verify the return value of
register_definitionis not used:Assistant
Now I have a thorough understanding of the codebase. Let me implement the fix. I'll start with the core
definitions.pyfile:Assistant
Now let me rewrite the
definitions.pyfile with the fix:Assistant
Now let me update the graph.py wrapper:
Assistant
Now let me update
validate_graph.pyto use conflict-aware grouping:Assistant
Now let me update the callers. First,
_ai/_tools/tools/dependency_graph.py:Assistant
Now let me update
_code_mode/_context.py:Assistant
Now I need to update the
_code_mode/_context.py. The code does:existing_multiply_defined = set(graph.get_multiply_defined())- this creates a set of tuples, but tuples containing sets are not hashable.new_multiply_defined = set(graph.get_multiply_defined()) - existing_multiply_defined- same issue.for name in sorted(new_multiply_defined)- iterates over names, then callsgraph.get_defining_cells(name).
I need to update this to handle the new return type. The approach:
- Use
(name, frozenset(cells))for hashing in the set. - For the display loop, use the cell_ids from the tuple directly instead of
get_defining_cells.
Let me write the replacement.
Assistant
Now let me update
_ast/app.py:Assistant
Now let me update
_convert/ipynb/to_ir.py:Assistant
Now let me check if there are any other callers I missed:
Assistant
All callers are updated. Now let me also check if
CellId_tis imported ingraph.py(since I changed the return type annotation):Assistant
Good,
CellId_tis imported in theTYPE_CHECKINGblock. Now let me run the reproduction script to verify the fix:Assistant
The bug is fixed. Now
multiply_definedis empty for tables with the same leaf name in different schemas. Let me also verify the original issue case (withdfas the variable name in both cells):Assistant
The fix works correctly for all cases. Let me also test the edge case from the existing test (Python variable + SQL table with different schema):
Assistant
All edge cases work correctly. The always-add approach properly handles the tricky three-cell case. Now let me run the existing tests:
Assistant
There's a test failure related to edge computation. Let me look at the failing test:
Assistant
Let me check the cell language for these SQL cells:
Assistant
Let me check if sqlglot is installed, since SQL ref finding depends on it:
Assistant
Now with sqlglot installed, the SQL refs are properly found. Let me re-run the tests:
Assistant
This test failure is expected - it's checking the old return type (
["t1"]vs[('t1', {'0', '1'})]). Per the contract, this is a test that needs updating to reflect the return type change. Let me run all tests to see the full picture:Assistant
Only 2 tests fail, both due to the return type change (expected). The actual conflict detection behavior is correct. Let me run the other affected test files:
Assistant
All validate_graph tests pass. Let me run the AI tools tests:
Assistant
The
test_multiply_defined_variablestest fails because the mock returns a list of strings (old format), but the code now expects tuples. This is an expected failure due to the return type change. Let me verify:Assistant
This is an expected failure due to the return type change (the mock returns strings, not tuples). Let me run the code_mode tests and other relevant test suites:
Assistant
The code_mode tests fail due to a missing
inline_snapshotmodule (environment issue). Let me install it:Assistant
There are many failures. Let me check if these are pre-existing by stashing my changes and running the same tests:
Assistant
These are pre-existing failures (not related to my changes). Let me restore my changes:
Assistant
Let me check if the code_mode failures increased due to my changes by comparing the count:
Assistant
Same number of failures (56) with and without my changes - these are pre-existing failures. Let me run the ipynb conversion tests:
Assistant
All conversion tests pass. Now let me run the lint tests:
Assistant
There's 1 additional lint test failure. I notice a snapshot file was modified. Let me investigate:
Assistant
The snapshot file was auto-updated by
inline_snapshotduring a test run - the only difference is the ORDER of entries (reordering of "Bar"). This is because the oldcheck_for_multiple_definitionssorted names, but the new version usingget_multiply_defineddoesn't. Let me revert the snapshot and fix the ordering:Assistant
Now let me add sorting to
get_multiply_definedfor deterministic output:Assistant
Now let me re-run the lint snapshot test to verify the ordering is fixed:
Assistant
The snapshot test passes now. Let me verify the snapshot file wasn't modified:
Assistant
No changes to the snapshot file. Let me now re-run the full lint test suite to confirm no new failures:
Assistant
Now 23 failed, 126 passed - same as the baseline (no new failures). Let me run the validate_graph and dataflow tests once more:
Assistant
Only the 2 expected failures remain (return type change). Let me also run the app tests to verify my
app.pychange:Assistant
Same 16 failures with and without my changes - pre-existing. Let me run a broader set of runtime tests to check for regressions:
Assistant
Only the 2 expected failures remain. Let me now test edge cases - deletion behavior and re-registration:
Assistant
All edge cases work correctly:
- Deletion: Properly removes cell from
definitions,typed_definitions, andqualified_names. After deleting both cells, everything is empty. ✓ - Re-registration: After editing a cell to use the same schema, a genuine collision is detected. ✓
- Views in different schemas: No false collision. ✓
- Same view, same schema: Genuine collision detected. ✓
Let me also verify the original bug from the issue is fully fixed (the user-facing error should not appear):
- Deletion: Properly removes cell from
Assistant
The bug is fully fixed. Now let me also run the SQL visitor tests to make sure nothing is broken:
Assistant
All SQL visitor tests pass. Let me also run the edges tests and check for any test specifically testing the
register_definition/unregister_definitionsbehavior:Assistant
All tests pass except the 2 expected return-type-change failures. Let me now clean up the temporary test files and do a final review of all my changes:
Assistant
The changes look comprehensive. Let me run one more test to verify the
unregister_definitionsfix works correctly with SQL hierarchical matching (the bug fix wheretyped_definitionswasn't being cleaned up):Assistant
The
unregister_definitionsfix works correctly - stale entries are properly cleaned up fromtyped_definitions, and hierarchical matching still works.Let me now run a broader test sweep to make sure nothing else is broken by the
register_definitionalways-add change:Assistant
Only the 2 expected failures remain. Let me also run the AI tools tests and the lint snapshot tests one final time:
Assistant
The only failure is the mock-based test that needs updating for the return type change (expected). Let me verify all modified files import correctly:
Assistant
All imports work. Let me do a final comprehensive test to make sure all the scenarios from the contract are handled:
Assistant
All contract scenarios pass. Let me now do a final review of the complete diff to make sure everything is correct:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.