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 start by understanding the issue. The problem is that when using multiple SQL cells with DuckDB, creating tables with the same name in different schemas leads to a variable redefinition error. For example:
CREATE TABLE finance.datalake.xx (id INT);-- Cell 2 CREATE TABLE finance.information_layer.xx (id INT);This should be allowed since they're in different schemas, but marimo treats them as conflicting because it extracts just the table name
xxwithout considering the schema.Let me explore the codebase to understand how SQL definitions are handled.
- Assistant
Let me look at the definitions.py file to understand how definitions are tracked.
- Assistant
Let me see the rest of the file.
- Assistant
Let me explore how SQL definitions are created and what
qualified_namelooks like. - Assistant
Let me look at the visitor and sql_visitor files to understand how definitions are tracked.
- Assistant
Let me search for the visitor.py file.
- Assistant
Let me look at the VariableData structure to understand what fields are available.
- Assistant
Let me understand the flow better. I need to look at:
- How SQL definitions are created (what name and qualified_name are set to)
- How
get_multiply_definedworks - How the conflict detection uses
definitionsdict
Let me trace through the code more carefully.
- Assistant
Let me see how SQL definitions are handled:
- Assistant
Let me understand the key part. When a SQL cell defines a table like
finance.datalake.xx, the visitor calls:self._define( None, _table.table, # This is just "xx" (the leaf name) VariableData( "table", qualified_name=_table.qualified_name # This is "finance.datalake.xx" ), )So the
_definemethod is called with:name = "xx"(just the leaf name)VariableDatawithqualified_name = "finance.datalake.xx"
The problem is in
register_definitionindefinitions.py. Let me look at it again:Examining the logic where the code checks if a name is already defined and handles duplicate definitions by comparing qualified names or language types...
I'm realizing the core issue: when two different cells define tables with the same leaf name but different qualified names, the code only adds to the definitions dict if they're exact duplicates, but then it always updates the typed_definitions dict regardless. This creates an inconsistency where the leaf name tracking and the typed definition tracking get out of sync. and the condition fails. The real problem is that isn't distinguishing between same table names in different schemas—it treats all "xx" as one entry regardless of the full qualified name. I need to check if has the same issue, and then figure out how to make the detection schema-aware.
- Assistant
Let me look at the
SQLDefsclass andfind_sql_defs: - Assistant
Let me look at the SQLDefs and SQLRef classes in detail:
- Assistant
Let me look at the SQLRef class:
- Assistant
Let me look at the
_definemethod: - Assistant
Wait, the
_definemethod is in the visitor file. Let me check. - Assistant
Hmm, let me search more specifically in the visitor.py file.
- Assistant
Hmm, that's showing lines from sql_visitor.py? Let me look directly.
- Assistant
Now let me understand the issue. In visitor.py, for SQL tables, the code does:
self._define( None, _table.table, # "xx" VariableData( "table", qualified_name=_table.qualified_name # "finance.datalake.xx" ), )So the name used for
definitionsdict is always the leaf name "xx", while the qualified_name is stored in the VariableData. This means both cells end up defining the name "xx" inself.definitions, causing the conflict.Let me now look at
get_multiply_definedmore carefully and trace the logic inregister_definition: - Assistant
Now I understand the issue clearly. Let me trace through what happens:
- Cell 1 defines
CREATE TABLE finance.datalake.xx→_define(None, "xx", VariableData("table", qualified_name="finance.datalake.xx")) - Cell 2 defines
CREATE TABLE finance.information_layer.xx→_define(None, "xx", VariableData("table", qualified_name="finance.information_layer.xx"))
Both use the leaf name "xx" as the definition name in
self.definitions, but have different qualified names. Inregister_definition:- Cell 1: "xx" not in definitions → else branch → adds cell_1
- Cell 2: "xx" in definitions, typed_def ("xx", "table") IS in typed_definitions → condition is
True AND False= False → else branch → adds cell_2
So both end up in
self.definitions["xx"]andget_multiply_definedreturns ["xx"].Now let me see how
get_multiply_definedis called to understand the full impact: - Cell 1 defines
- Assistant
Let me see how
get_multiply_definedis called from the graph and what the caller expects. - Assistant
Let me look at how
get_multiply_definedis used in the graph: - Assistant
Let me see how the result is used in the app module and elsewhere:
- Assistant
Now let me look at the edges.py file for
register_definition: - Assistant
Let me search for how register_definition is called.
- Assistant
Let me look at how register_definition is called in graph.py:
- Assistant
Now let me look at the graph.py
get_multiply_defined: - Assistant
Now I have a thorough understanding of the issue. Let me look at how
register_definitionworks more closely: - Assistant
Now I need to understand how SQL cells' references work. Let me check the edges computation:
- Assistant
Let me look at the full edges.py file:
- Assistant
Now I have a thorough understanding of the issue. Let me trace through the exact logic:
-
Cell 1 creates
finance.datalake.xx→_define(None, "xx", VariableData("table", qualified_name="finance.datalake.xx"))- In
register_definition:name="xx"not in definitions → else branch → adds cell_1
- In
-
Cell 2 creates
finance.information_layer.xx→_define(None, "xx", VariableData("table", qualified_name="finance.information_layer.xx"))- In
register_definition:name="xx"IS in definitions,typed_def=("xx","table")IS in typed_definitions → conditionTrue AND False = False→ else branch → adds cell_2
- In
-
self.definitions["xx"] = {cell_1, cell_2}→get_multiply_defined()returns["xx"]
The issue is that the current code always adds cell_2 to
self.definitions["xx"]in theelsebranch when the same leaf name and kind already exist, even though they have different fully qualified names.The fix needs to be in
get_multiply_defined- it should be smarter about what constitutes a genuine collision. Two SQL tables with the same leaf name but different fully qualified names should NOT be considered multiply defined. -
- Assistant
Let me now look at all the callers of
get_multiply_defined: - Assistant
Let me look at the to_ir.py caller:
- Assistant
Let me also look at how app.py uses the result:
- Assistant
Now let me also look at how the error is reported in the runtime:
- Assistant
Now let me look at the runtime to see how the multiply-defined error is raised:
- Assistant
Let me look at the kernel/runtime to see where the error is raised:
- Assistant
Let me check the tests to understand the current behavior:
- Assistant
Let me look at the test for multiply defined names:
- Assistant
Let me look at the existing tests for this:
- Assistant
I see! There's already a test
test_redefine_sql_table_diff_schemathat shows the case where a SQL tableschema1.t1coexists with a Python variablet1. This works because the kinds are different ("variable" vs "table") and the existing logic handles that.But the bug is about two SQL tables with the same leaf name in different schemas. The existing logic doesn't handle this because:
- Cell 1: kind="table", qualified_name="finance.datalake.xx" → adds to definitions["xx"]
- Cell 2: kind="table", qualified_name="finance.information_layer.xx" → typed_def IS in typed_definitions → falls to else → adds to definitions["xx"]
- Both end up in
self.definitions["xx"]→ multiply defined
Now let me look at the existing tests and create a reproducer:
- Assistant
Let me install msgspec first or check how to run tests.
- Assistant
Let me try again to reproduce the issue.
- Assistant
Let me try installing the development dependencies:
- Assistant
Now let me reproduce the issue:
- Assistant
Hmm, it's returning empty. Let me check if the sql is parsed correctly:
- Assistant
The issue is that the SQL is wrapped in
mo.sql(...), so the cell is definingdfanddf2as Python variables (the result of the SQL query). The SQL table definitions are tracked differently - they're not in the defs.Let me look more carefully at how SQL cells work in the actual runtime. Let me check if the SQL table definition is tracked somewhere else.
- Assistant
I need to understand how SQL cells work in marimo. The issue says "SQL cells" - let me look at how SQL cells are compiled differently from Python cells. In marimo, SQL cells have a different compilation path. Let me look for how SQL cells are compiled.
- Assistant
Let me look at the compiler.py file more carefully to understand how SQL cells are compiled:
- Assistant
Let me look at how the issue manifests. The test uses
mo.sql()wrapping, which creates a cell with defs including both the Python variable (df) AND the SQL table name (xx). Let me verify: - Assistant
- Assistant
Hmm, interesting. The SQL table
t1is not showing up in the cell defs at all! Let me look more carefully at how the visitor handles SQL. - Assistant
The cell has language="sql" but defs only has "df" and no SQL table defs. That's surprising. Let me check how SQL cells are handled differently.
Wait, the test I see says
test_redefine_sql_table_diff_schemapasses, but in my test the SQL cell doesn't seem to have the table definition in its defs. Let me look at how the compile_cell works for SQL cells.Let me check the visitor more carefully.
- Assistant
Interesting - the SQL table definitions (
t1) are NOT showing up in the visitor's defs. Let me look at the visitor code more carefully to see where SQL table definitions are extracted.Looking at the visitor code I saw earlier:
for _table in sql_defs.tables: self._define( None, _table.table, # "xx" VariableData( "table", qualified_name=_table.qualified_name ), )This should add the table name to the visitor's defs. But it's not showing up. Let me check if there's a condition that prevents this from happening.
Wait, I think the issue might be that the SQL processing only happens when the cell is a "SQL cell" (i.e., the language is "sql"), and maybe the table definitions are being added but then removed or not included in the final cell.
Let me look at the visitor code more carefully to understand the flow.
Actually, looking at the visitor code from earlier:
self.language = "sql" - Assistant
Let me look at the visit_Call method more closely to understand how SQL is handled:
- Assistant
Let me see more of the visit_Call method:
- Assistant
Now I see - when the SQL is inside
mo.sql(), the visitor processes it and callsself._define()for the table. Let me check if this is working correctly: - Assistant
Interesting - the SQL table defs are NOT showing up. Let me debug this more carefully. The
_defineis called with_table.tablewhich should be "t1", and the VariableData should have kind="table". Let me check whatfind_sql_defsreturns for this SQL. - Assistant
Interesting - the SQL defs are empty for the schema-qualified table name. Let me check what happens:
- Assistant
Hmm,
find_sql_defsreturns empty tables. Let me investigate: - Assistant
Ah, duckdb is not installed! That's why the SQL defs are empty. Let me install it.
- Assistant
Now let me reproduce the issue with duckdb installed:
- Assistant
Now I've reproduced the bug! The issue is clear:
- Cell 0 defines
xxwithqualified_name='finance.datalake.xx' - Cell 1 defines
xxwithqualified_name='finance.information_layer.xx' - Both end up in
self.definitions['xx']={'0', '1'} get_multiply_defined()returns['xx']
Now let me look at the
register_definitionlogic: - Cell 0 defines
- Assistant
Now I have a complete understanding of the problem. Let me implement the fix.
Plan:
- Add a
definition_qualified_namesdict toDefinitionRegistryto track(name, cell_id) -> qualified_name - Update
register_definitionto store qualified names - Update
unregister_definitionsto clean up qualified names - Update
get_multiply_definedto returnlist[tuple[Name, set[CellId_t]]]with conflict-aware logic - Update
graph.pyreturn type - Update all callers
- Add a
- Assistant
Now let me update graph.py to change the return type:
- Assistant
Now let me update graph.py's
get_multiply_defined: - Assistant
Now let me update all callers. Let me start with app.py:
- Assistant
Now let me update app.py to handle the new return type:
- Assistant
Now let me update _context.py:
- Assistant
I need to update
_context.pyto handle the new return type. The key changes are:existing_multiply_defined = set(graph.get_multiply_defined())→ needs to extract namesset(graph.get_multiply_defined()) - existing_multiply_defined→ needs to extract namesfor name in sorted(new_multiply_defined):→ this iterates over names
Let me update this file:
- Assistant
I also need to update the line that computes
new_multiply_defined: - Assistant
Now let me update dependency_graph.py:
- Assistant
I need to update the dependency_graph.py file. The
multiply_definedis used in several places. Let me look at how it's used:multiply_defined = sorted(graph.get_multiply_defined())- this creates a sorted list of names- It's passed to
GetCellDependencyGraphOutputasmultiply_defined=multiply_defined - It's passed to
_build_next_stepswhich expectsmultiply_defined: list[str]
I need to extract the names from the tuples. Let me update this file.
- Assistant
Now let me update to_ir.py:
- Assistant
I need to update to_ir.py. The
multiply_defined_namesis used as a list of names, but now it's a list of tuples. Let me update it: - Assistant
Now let me check if there are any other callers I need to update. Let me search for all usages of
get_multiply_defined: - Assistant
Good, I've updated all the callers. Now let me also check if there are any test files that use
get_multiply_defined: - Assistant
I need to update the test files as well. Let me look at the test files:
- Assistant
I need to update the test files to match the new return type. The tests currently expect
list[Name]but now the return type islist[tuple[Name, set[CellId_t]]].Let me update the test files:
test_redefine_sql_table_diff_schema: expects[]→ should still be[](empty list)test_sql_table_schema_to_python_ref: expects["t1"]→ should be[("t1", {"0", "1"})]or similartest_sql_table_schema_to_python_ref_rev: expects["t1"]→ should be[("t1", {"0", "1"})]or similar
Wait, but the instruction says: "UNDER NO CIRCUMSTANCES should you modify existing tests or add new tests to the repository."
So I should NOT modify the test files. But the return type has changed from
list[Name]tolist[tuple[Name, set[CellId_t]]], which will break the existing tests.Hmm, this is a conflict. The interface spec says to change the return type, but the instruction says not to modify tests.
Let me re-read the instruction more carefully: "If existing tests break because they need to be updated to reflect the changes you made, just ignore it. Evaluation system will not take it into account."
- Assistant
I see - the test_dependency_graph.py file has a mock that returns a list of names. I need to update this mock to return tuples. But the instruction says not to modify tests. Let me re-read the instruction:
"UNDER NO CIRCUMSTANCES should you modify existing tests or add new tests to the repository. This will lead to an error in the system that evaluates your performance."
But then it also says: "If existing tests break because they need to be updated to reflect the changes you made, just ignore it. Evaluation system will not take it into account."
So I should NOT modify the test files. The evaluation system will ignore broken tests.
Let me now run the tests to see what breaks and make sure my core logic is correct:
- Assistant
All my custom tests pass. Let me also test some edge cases:
- Assistant
All edge case tests pass. Now let me run the existing tests to see what breaks:
- Assistant
There's a test failure -
test_sql_chainis failing because the parents relationship is not being set up correctly. Let me look at this test: - Assistant
- Assistant
- Assistant
So the test was already failing before my changes. This is a pre-existing failure, not caused by my changes. Let me restore my changes:
- Assistant
Good, the test was already failing before my changes. Let me now run all the tests in the test_dataflow.py file, excluding the pre-existing failures:
- Assistant
Let me check if those failures are also pre-existing:
- Assistant
OK, so the pre-existing failures are:
- test_sql_tree_with_declared_df
- test_python_to_sql_ref
- test_get_referring_cells_sql_and_python
- test_referring_cells_sql_and_python
- test_attached_db
And my changes introduced 2 additional failures:
- test_sql_table_schema_to_python_ref
- test_sql_table_schema_to_python_ref_rev
These are the tests that check
multiply_defined == ["t1"]. Now with my changes, the return type islist[tuple[Name, set[CellId_t]]]so the assertion fails.Let me check the details:
test_sql_table_schema_to_python_ref: expectsmultiply_defined == ["t1"]but now gets[(t1, {0, 1})]test_sql_table_schema_to_python_ref_rev: expectsmultiply_defined == ["t1"]but now gets[(t1, {0, 1})]
These failures are expected because the return type changed. The instruction says: "If existing tests break because they need to be updated to reflect the changes you made, just ignore it. Evaluation system will not take it into account."
So I should ignore these failures.
Let me now run the dependency_graph tests to see if they pass:
- Assistant
That test failure is because the test mock returns strings instead of tuples. That's expected and I was told to ignore such failures. Let me verify the test that uses the real graph works properly:
- Assistant
The
test_redefine_sql_table_diff_schematest passes. This is the test that checks the case where a SQL table with a schema is compared with a Python variable. Let me also run the tests that are specifically about multiply_defined: - Assistant
Let me search for the test names:
- Assistant
The two failures are:
test_sql_table_schema_to_python_ref: expectsmultiply_defined == ["t1"]but now gets[(t1, {0, 1})]test_sql_table_schema_to_python_ref_rev: expectsmultiply_defined == ["t1"]but now gets[(t1, {0, 1})]
These are expected failures because the return type changed from
list[Name]tolist[tuple[Name, set[CellId_t]]]. The tests need to be updated to match the new return type, but I was told not to modify tests.Let me also check if there are any other callers I missed:
- Assistant
Let me verify the final state of all modified files:
- Assistant
The definitions.py file looks good. Let me now run a comprehensive test to make sure my changes work correctly:
- Assistant
All tests pass. Let me now run the existing tests that are not pre-existing failures to make sure I haven't broken anything:
- Assistant
All 47 tests pass. The 11 deselected tests are the ones that were already failing before my changes (pre-existing failures) plus the 2 that fail because of the return type change (which is expected).
Let me now also run the dependency_graph tests excluding the one that uses the mock:
- Assistant
All 9 tests pass. The only failing test is
test_multiply_defined_variableswhich uses a mock that returns strings instead of tuples. This is expected because the return type changed.Let me now verify the final state of all modified files and run a final comprehensive test:
- Assistant
Let me review the complete diff to make sure everything looks correct:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.