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
sql
-- Cell 1
CREATE TABLE finance.datalake.xx (id INT);
sql
-- Cell 2
CREATE TABLE finance.information_layer.xx (id INT);
ERROR
code
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:
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
Assistant
I'll start by exploring the repository structure to understand the codebase and locate the relevant files. Let's first check the current directory and see what's available.
Assistant
Let me look at the specific file mentioned in the issue: marimo/_runtime/dataflow/definitions.py.
Assistant
Let me see the rest of the file.
Assistant
Now let me understand the issue better. Let me look at the SQL visitor and how SQL definitions are extracted.
Assistant
Let me examine the SQL visitor to understand how SQL definitions are extracted and what data structures are used.
Assistant
Let me explore the repository to understand the codebase structure and the issue better.
Assistant
Let me understand the issue better. The problem is that when two SQL cells create tables with the same name but in different schemas (e.g., finance.datalake.xx and finance.information_layer.xx), marimo incorrectly reports them as having a variable name collision for xx. The get_multiply_defined method only looks at the leaf name xx without considering the fully qualified name.
Let me look at the current implementation and understand how definitions are tracked.
Assistant
Let me look at the visitor.py to understand VariableData structure.
Assistant
Let me look at how SQL definitions are registered in the visitor to understand the flow better.
Assistant
Let me open the file and look at the relevant section.
Assistant
Let me look at the caller of get_multiply_defined:
Assistant
Let me look at how the visitor stores SQL definitions more carefully:
Assistant
Now I understand the issue. Let me look at the test file for this module to understand expected behavior:
Assistant
Let me check what the callers of get_multiply_defined expect:
Assistant
The callers expect get_multiply_defined to return a list of names (strings). The issue asks us to change the return type to list[tuple[Name, set[CellId_t]]] for conflict-aware grouping, but that would break the callers. Let me read the issue again carefully.
The issue says:
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.
Assistant
Assistant
Now let me search for tests related to SQL schemas and definitions to understand the current behavior better:
Assistant
Let me look at the test test_redefine_sql_table_diff_schema which seems to be directly related to the issue.
Assistant
Now let me understand the core issue. Let me trace through the register_definition logic with two SQL cells creating tables with same leaf name but different schemas:
Assistant
Now let me look at how the visitor extracts SQL definitions:
Assistant
Let me look at how the SQL definitions are created and how the visitor processes them.
Assistant
Let me look at SQLRef to understand qualified_name and table.
Assistant
Let me look at the SQLRef class.
Assistant
Now I have a clear picture of the problem. Let me trace through the logic:
typed_def ("xx", "table") IS in self.typed_definitions (from Cell 1)
So the condition name in self.definitions and typed_def not in self.typed_definitions is FALSE
Falls to else branch, unconditionally adds Cell 2 to self.definitions["xx"]
Now self.definitions["xx"] = {"cell1", "cell2"} → false conflict!
The existing check for qualified names only fires when typed_def not in self.typed_definitions, but for two SQL tables with same leaf name and same kind, the typed_def IS already in typed_definitions.
Let me first reproduce the issue with a test script:
Assistant
Let me install the dependencies first.
Assistant
Let me try to reproduce the issue again:
Assistant
The df is also multiply defined. Let me adjust the test to match the issue exactly:
Assistant
Hmm, the cell isn't being parsed correctly. The issue is that mo.sql(...) is used directly without assignment, so the variable name extraction might be different. Let me check what happens with the visitor...
When using mo.sql() without assignment, the visitor won't extract a variable name. Let me try with assignment to see the real behavior:
Assistant
The SQL definitions are not being picked up. Let me check how SQL cells work in marimo - they use a special %% syntax:
Assistant
Let me look at how parse_cell works in the test:
Assistant
Let me find where parse_cell is defined.
Assistant
Let me find where parse_cell is imported from.
Assistant
Let me look at how parse_cell is defined in the test file.
Assistant
Let me look at how the test uses the SQL syntax:
Assistant
Now let me reproduce the actual issue properly. Let me first run the existing test that already handles one scenario of this:
Assistant
Let me install duckdb:
Assistant
Now let me reproduce the issue:
Assistant
I've reproduced the issue. Let me trace through the logic more carefully:
Assistant
Now I understand the issue completely. Let me look at how get_multiply_defined is used in the graph and callers:
Assistant
Let me look at other callers:
Assistant
Let me look at the other callers:
Assistant
Let me look at the last caller:
Assistant
Now I have a complete understanding of the issue. Let me also check how get_multiply_defined return value is used in the graph and callers to understand what changes are needed:
Assistant
Now I have a complete understanding. Let me look at how the register_definition handles the case where typed_def is already in typed_definitions but qualified names differ:
Assistant
Now I have a clear understanding of the bug. Let me trace through the code path:
Cell 1 defines finance.datalake.xx → registers with name="xx", qualified_name="finance.datalake.xx"
Cell 2 defines finance.information_layer.xx → registers with name="xx", qualified_name="finance.information_layer.xx"
In register_definition, when Cell 2 arrives:
name in self.definitions → True (Cell 1 already added "xx")
typed_def not in self.typed_definitions → False (Cell 1 already added ("xx", "table"))
Since both conditions aren't true, it falls through to else → adds Cell 2 to self.definitions["xx"]
This causes a false collision. The existing qualified name check only triggers when typed_def is new (different kind), not when it's the same kind with different schemas.
Now let me look at how get_multiply_defined is used by callers to understand what changes I need to make:
Assistant
Now let me look at all the relevant callers of get_multiply_defined more carefully to understand the full scope of changes needed:
Assistant
Now I have a clear understanding of the problem. Let me create a reproduction script and then implement the fix.
The core issue is in register_definition in definitions.py. When two SQL cells define tables with the same leaf name but different schemas (e.g., finance.datalake.xx and finance.information_layer.xx), both cells get added to self.definitions["xx"] unconditionally because:
The condition name in self.definitions and typed_def not in self.typed_definitions is False when typed_def IS already registered (same name+kind)
The else branch always adds to self.definitions[name] without checking if the qualified names differ
Let me also look at the existing tests to understand the expected behavior:
Assistant
There's already a pre-existing test failure. Let me check if this is related to my changes or pre-existing:
Assistant
The test failure is pre-existing (unrelated to our issue). Let me focus on implementing the fix. Let me first understand the full picture by looking at the edges module:
Assistant
Let me look at the edges code more carefully:
Assistant
Let me look at the edges code more carefully.
Assistant
Now I have a clear understanding of the problem. Let me plan the fix:
Root cause: In register_definition, when Cell 2 has the same name+kind as Cell 1 (both SQL tables named "xx"), typed_def in self.typed_definitions is True, so it falls to the else branch which unconditionally adds Cell 2 to self.definitions["xx"].
Fix needed: Track qualified names per cell, and in register_definition, check if the qualified names differ before adding to self.definitions[name]. Also update get_multiply_defined to return list[tuple[Name, set[CellId_t]]] with conflict-aware grouping.
Callers to update: All callers of get_multiply_defined need to handle the new return type.
Let me implement the fix:
Assistant
Let me see the rest of the file:
Assistant
Now I understand everything. Let me implement the fix. The approach:
Add a cell_qualified_names dict to track the qualified name for each cell+name pair
Fix register_definition to not add cells to definitions[name] when SQL definitions have different qualified names but same leaf name and kind
Update get_multiply_defined to return list[tuple[Name, set[CellId_t]]] with conflict-aware grouping
Update all callers to handle the new return type
Assistant
Let me write the full file with the fix:
Assistant
Now I need to update all the callers. Let me start with the graph wrapper:
Assistant
Let me update the graph wrapper:
Assistant
Now let me update the graph.py wrapper:
Assistant
Now let me update the callers. First, app.py:
Assistant
Now I need to update the callers. Let me look at each one and update them:
Assistant
Let me update app.py:
Assistant
Let me update _code_mode/_context.py:
Assistant
I need to update the callers. Let me look at each one carefully and update them:
Assistant
Now I need to update the callers. Let me handle each one:
_code_mode/_context.py - uses sets and iteration
_convert/ipynb/to_ir.py - iterates over names
_ai/_tools/tools/dependency_graph.py - sorts
Assistant
I need to update all callers. Let me handle them one by one. First _code_mode/_context.py:
Assistant
Now let me update _convert/ipynb/to_ir.py:
Assistant
Now let me update _ai/_tools/tools/dependency_graph.py:
Assistant
Now let me test if the fix works:
Assistant
All test cases pass. Now let me run the existing tests to make sure nothing is broken:
Assistant
Let me try without the timeout flag.
Assistant
This test was already failing before my changes. Let me verify:
Assistant
Good - this test failure is pre-existing (it fails even without my changes). Let me restore my changes and skip that test:
Assistant
Let me check if this failure is also pre-existing:
Assistant
Good, both failures are pre-existing. Let me run the rest of the tests:
Assistant
Let me check if these failures are pre-existing:
Assistant
So 4 tests were already failing before my changes, and my changes introduced 2 new failures. Let me investigate:
Assistant
The test expects ["t1"] but now gets [("t1", {"1"})] due to the return type change. Let me check the specific test that's relevant to the issue:
Assistant
The key test test_redefine_sql_table_diff_schema passes. The other failures are due to the return type change from list[Name] to list[tuple[Name, set[CellId_t]]] - the tests compare against ["t1"] but now get [("t1", {"1"})]. Per the instructions: "If existing tests break because they need to be updated to reflect the changes you made, just ignore it."
Let me run the non-SQL tests to make sure nothing else broke:
Assistant
All non-SQL tests pass. Let me also run the tests for the other files I changed:
Assistant
Let me check if this test failure is pre-existing:
Assistant
This failure is caused by my changes. Let me investigate:
Assistant
The error is in the dependency_graph.py - it's using the graph wrapper which may be a different graph object. Let me check:
Assistant
Let me check what type graph is in this context:
Assistant
Let me check what type graph is in this context:
Assistant
The error is that graph.get_multiply_defined() is still returning list[Name] instead of tuples. Let me check if graph here might be a different type:
Assistant
Let me look at the test that's failing:
Assistant
The test uses a mock graph. Let me check how the mock is set up:
Assistant
Assistant
The test uses a Mock for the graph that returns list[str] from get_multiply_defined(). The mock doesn't match the new interface. This is expected - the test needs to be updated to reflect the new interface.
Per the instructions: "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."
Let me verify that the actual behavior is correct by running a more comprehensive test.
The test uses a Mock graph that returns list[str] from get_multiply_defined() - it doesn't match the new interface. This is expected. Per the instructions: "If existing tests break because they need to be updated to reflect the changes you made, just ignore it."
Let me run the code_mode tests:
Assistant
Let me check the full error:
Assistant
Missing module. Let me install it:
Assistant
Let me run the code_mode tests now.
Assistant
Let me check if this test failure is pre-existing:
Assistant
Good, this failure is also pre-existing. Let me now verify the full picture of test failures - pre-existing vs caused by my changes:
Assistant
Good. The failures caused by my changes are test_sql_table_schema_to_python_ref, test_sql_table_schema_to_python_ref_rev, and test_multiply_defined_variables - all due to the return type change. These are expected since the tests need to be updated to match the new interface.
Let me now verify the fix resolves the original issue from the bug report:
Assistant
All tests pass. Let me do a final review of all my changes:
Assistant
Let me also check the scratchpad integration test:
Assistant
Let me check if this error is pre-existing:
Assistant
Good, that's also pre-existing. Let me now review all the changes I've made:
Assistant
The diff looks clean. Let me do one final verification - run the most relevant existing test to make sure it passes:
Assistant
All relevant SQL tests pass. Let me also run the non-SQL tests one more time:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
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 git reset --hard command.
Additionally, you can use git stash and git stash pop 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 submit) using git status or git diff commands.
However you don't need to use git add or git commit before submitting your changes. In fact,
submit only submits currently unstaged changes because it uses git diff to get the changes that need to be submitted.
CHECKLIST
Before submitting your solution, please go over the following checklist and make sure you've done everything:
If an error was reported in the issue description, I have successfully reproduced it.
If an error was reported in the issue description, I have confirmed that my fix resolves the error.
I have thought about edge cases and made sure my fix handles them as well.
I have run existing tests in the repository that might have been affected by the change I made and confirmed that they pass.
I want you to list every bullet from this checklist and write your reasoning for why you think you did it or didn't need to.
Repository has been uploaded and your shell is currently at the repository root. Time to solve the issue!
(Current directory: /marimo, current file: none) bash-$
So the interface contract says to change the return type to list[tuple[Name, set[CellId_t]]]. But changing the return type would break all callers. Let me check the callers more carefully.
Looking at the callers:
marimo/_ast/app.py:612: multiply_defined_names = self._graph.get_multiply_defined() then checks if multiply_defined_names: and accesses multiply_defined_names[0]
All callers expect a list of names (strings). If I change the return type to tuples, they'll break.
Wait, let me re-read the evaluation contract again:
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.
Hmm, but this would break all callers. Let me think about this differently. The contract says to change the interface. But maybe the callers also need to be updated? Let me look at the graph.py to see the wrapper.
Looking at the callers, the return type is used as a list of names. But the evaluation contract says the return type should be list[tuple[Name, set[CellId_t]]].
Wait, let me re-read the contract more carefully. It says:
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.
And:
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:
Change the return type of get_multiply_defined in definitions.py to list[tuple[Name, set[CellId_t]]]
Update the wrapper in graph.py to match
Update all callers to work with the new return type
But wait, the callers are using it as a list of names. If I change it to return tuples, I need to update the callers too. However, the contract says "Preserve the user-facing table variable, defining-cell ownership, deletion behavior, and conflict reporting for genuine collisions."
So I think the approach is:
Update get_multiply_defined to return tuples where the name is still the leaf name (for user-facing display) but the grouping is based on qualified names
Update callers to work with tuples
But actually, looking at the callers more carefully:
marimo/_ast/app.py: multiply_defined_names[0] - accesses the first element, which would now be a tuple
marimo/_code_mode/_context.py: set(graph.get_multiply_defined()) - creates a set of the items
marimo/_convert/ipynb/to_ir.py: uses multiply_defined_names as a list
If I change the return type to tuples, I need to update these callers to extract the name from the tuple. But the contract says to "Preserve the user-facing table variable" - so the name in the tuple should still be the leaf name for display purposes.
Actually, let me reconsider. The contract says to "Preserve the user-facing table variable" - meaning the variable name that the user sees should still be the leaf name. But the grouping should be based on the qualified name.
So for the example:
Cell 1: CREATE TABLE finance.datalake.xx (id INT); → leaf name "xx", qualified name "finance.datalake.xx"
Cell 2: CREATE TABLE finance.information_layer.xx (id INT); → leaf name "xx", qualified name "finance.information_layer.xx"
These should NOT be considered multiply defined because the qualified names are different.
But if:
Cell 1: CREATE TABLE xx (id INT); → leaf name "xx", qualified name "xx"
Cell 2: CREATE TABLE xx (id INT); → leaf name "xx", qualified name "xx"
These SHOULD be considered multiply defined because the qualified names are the same.
So the algorithm should be:
Group definitions by qualified name (for SQL) or leaf name (for Python/unqualified SQL)
If any group has more than one cell, that name is multiply defined
Return the leaf name (for user-facing) with the set of cell IDs
Wait, but what if we have:
Cell 1: CREATE TABLE xx (id INT); → leaf name "xx", qualified name "xx"
Cell 2: CREATE TABLE finance.datalake.xx (id INT); → leaf name "xx", qualified name "finance.datalake.xx"
Should these be multiply defined? According to the contract: "the same fully qualified name, or the same unqualified name, still is." So "xx" (unqualified) and "finance.datalake.xx" (qualified) are different qualified names, so they should NOT be multiply defined.
But wait, in SQL, CREATE TABLE xx creates a table in the default schema. So xx and finance.datalake.xx could potentially refer to the same table. But the contract says they're different because the qualified names are different.
OK, let me focus on the implementation. The key insight is:
In register_definition, I need to track the qualified name for each cell's definition
In get_multiply_defined, I need to group by qualified name (for SQL) or leaf name (for Python/unqualified SQL) and only report groups with more than one cell
Looking at the current register_definition:
python
def register_definition(
self,
cell_id: CellId_t,
name: Name,
variable_data: list[VariableData],
) -> set[CellId_t]:
variable = variable_data[-1] # Only the last definition matters
typed_def = (name, variable.kind)
# Check if this is a duplicate definition
if (
name in self.definitions
and typed_def not in self.typed_definitions
):
# Duplicate if the qualified name is no different
if variable.qualified_name == name or variable.language != "sql":
self.definitions[name].add(cell_id)
else:
self.definitions.setdefault(name, set()).add(cell_id)
self.typed_definitions.setdefault(typed_def, set()).add(cell_id)
self.definition_types.setdefault(name, set()).add(variable.kind)
# Return siblings (other cells that define this name)
siblings = self.definitions[name] - {cell_id}
return siblings
The current logic already tries to handle this! It checks if variable.qualified_name == name (i.e., the qualified name is the same as the leaf name, meaning it's unqualified) and if it's SQL. But the logic seems incomplete or broken.
Let me trace through the example again:
Cell 1: CREATE TABLE finance.datalake.xx (id INT);
So the problem is in the condition. The condition typed_def not in self.typed_definitions is checking if this exact (name, kind) pair has been seen before. But that's not what we want to check.
What we want to check is: is there another cell that defines a table with the SAME qualified name?
For the example:
Cell 1 defines table "finance.datalake.xx" (qualified name is different from leaf name)
Cell 2 defines table "finance.information_layer.xx" (qualified name is different from leaf name)
They have the same leaf name but different qualified names → NOT a collision
They have the same leaf name and the same qualified name → IS a collision
Or:
Cell 1 defines table "finance.datalake.xx" (qualified name is different from leaf name)
Cell 2 defines table "finance.datalake.xx" (qualified name is different from leaf name)
They have the same leaf name and the same qualified name → IS a collision
So the logic should be:
For SQL definitions where qualified_name != name (i.e., it's fully qualified), use the qualified name as the key for collision detection
For SQL definitions where qualified_name == name (i.e., unqualified), use the leaf name as the key
For Python definitions, use the leaf name as the key
But wait, the definitions dict uses the leaf name as the key. So we need to change the key to be the qualified name for SQL definitions.
Actually, I think the issue is simpler. Let me look at the condition again:
python
if (
name in self.definitions
and typed_def not in self.typed_definitions
):
# Duplicate if the qualified name is no different
if variable.qualified_name == name or variable.language != "sql":
self.definitions[name].add(cell_id)
else:
self.definitions.setdefault(name, set()).add(cell_id)
The condition typed_def not in self.typed_definitions is checking if this is a NEW type for this name. For example, if a name "xx" was previously defined as a "view", and now it's being defined as a "table", then typed_def would be ("xx", "table") which is NOT in typed_definitions, so the condition would be True.
But for our case, Cell 1 defines "xx" as a "table", so typed_def = ("xx", "table") IS in typed_definitions. So the condition is False, and we go to the else branch.
The fix should be:
When we're in the else branch and the name is already in self.definitions, we should check if the qualified names are the same
If they're different (and it's SQL), we should NOT add to self.definitions[name]
But actually, I think the better fix is to use the qualified name as the key for SQL definitions. Let me think about this more carefully.
The definitions dict maps Name (leaf name) to set[CellId_t]. But for SQL, the "variable" that the user references is the leaf name. So if you have SELECT * FROM xx, it will reference the leaf name "xx".
But if you have two tables with the same leaf name in different schemas, the user would need to use the fully qualified name to reference them. So the leaf name "xx" is ambiguous.
Hmm, but the issue says:
Since the tables are created in different schemas, both statements should execute without conflict
So the user expects that CREATE TABLE finance.datalake.xx and CREATE TABLE finance.information_layer.xx should not conflict. This makes sense because they're different tables.
But if a user writes SELECT * FROM xx, which table should it reference? It would be ambiguous. So maybe the system should still report a conflict in that case?
Wait, let me re-read the contract:
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.
So:
finance.datalake.xx and finance.information_layer.xx → NOT multiply defined (different qualified names)
xx and xx → IS multiply defined (same unqualified name)
finance.datalake.xx and finance.datalake.xx → IS multiply defined (same qualified name)
So the logic is: group by the effective key (qualified name for SQL, leaf name for Python/unqualified SQL), and if any group has more than one cell, it's multiply defined.
Now, the question is: what should get_multiply_defined return? The contract says list[tuple[Name, set[CellId_t]]]. But the callers expect list[Name].
I think the solution is:
In get_multiply_defined, group by effective key (qualified name for SQL, leaf name for Python/unqualified SQL)
For each group with more than one cell, return the leaf name and the set of cell IDs
Update the callers to work with tuples
But wait, the callers are using it as a list of names. If I change it to return tuples, I need to update the callers to extract the name from the tuple.
Actually, let me look at the callers again:
marimo/_ast/app.py:
python
multiply_defined_names = self._graph.get_multiply_defined()
if multiply_defined_names:
raise MultipleDefinitionError(
"This app can't be run because it has multiple "
f"definitions of the name {multiply_defined_names[0]}"
)
This expects multiply_defined_names[0] to be a name (string). If I change it to tuples, it would be (name, cell_ids), so I'd need to change it to multiply_defined_names[0][0].
This creates a set of the items. If the items are tuples, the set would contain tuples. But later it's used to compare with other sets, so I'd need to update the comparison logic.
This sorts the items. If they're tuples, it would sort by the first element (name).
OK, I think the cleanest approach is to change the return type to list[tuple[Name, set[CellId_t]]] and update all callers. But that's a lot of changes.
Alternatively, I could keep the return type as list[Name] but change the grouping logic. The contract says to return list[tuple[Name, set[CellId_t]]], but maybe I can interpret that as "return a list of names, but use conflict-aware grouping to determine which names are multiply defined".
Wait, let me re-read the contract again:
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.
OK, so the contract explicitly says to return tuples. But the callers expect a list of names. So I need to update the callers.
But wait, the contract also says:
Preserve the user-facing table variable, defining-cell ownership, deletion behavior, and conflict reporting for genuine collisions.
So I need to make sure the user-facing behavior is preserved. The user-facing behavior is that get_multiply_defined returns a list of names that are multiply defined. If I change it to return tuples, the callers need to be updated to extract the name from the tuple.
Let me think about this differently. The contract says to change the return type, but also says to preserve the user-facing behavior. So maybe the intent is to change the internal logic (grouping) but keep the return type the same?
Actually, I think the contract is saying: "The function should return a list of (name, cell_ids) tuples, where the grouping is based on the qualified name." But since the callers expect a list of names, I need to update them.
Let me look at the callers more carefully to understand what they do with the result.
For marimo/_ast/app.py:
python
multiply_defined_names = self._graph.get_multiply_defined()
if multiply_defined_names:
raise MultipleDefinitionError(
"This app can't be run because it has multiple "
f"definitions of the name {multiply_defined_names[0]}"
)
This raises an error with the first multiply defined name. If I change it to tuples, I'd need to change it to multiply_defined_names[0][0] to get the name.
This creates a set of the items. If the items are tuples, the set would contain tuples. But later it's used to compare with other sets, so I'd need to update the comparison logic.
Actually, let me look at the full context of the code_mode usage.
OK, I think the safest approach is to change the return type to list[tuple[Name, set[CellId_t]]] and update all callers. But I need to be careful to preserve the user-facing behavior.
Let me also think about the unregister_definitions method. It needs to clean up the new data structures.
OK, let me plan the implementation:
Add a new data structure to track the effective key for each cell's definition. For SQL definitions where qualified_name != name, the effective key is the qualified name. For all other definitions, the effective key is the leaf name.
In register_definition, use the effective key to determine if there's a collision.
In get_multiply_defined, group by effective key and return tuples of (name, cell_ids) for groups with more than one cell.
Update all callers to work with the new return type.
Update unregister_definitions to clean up the new data structures.
Wait, actually, I think there's a simpler approach. Instead of changing the key in definitions, I can add a new mapping from effective key to cell IDs, and use that for collision detection.
Let me think about this more carefully.
The definitions dict maps leaf name to cell IDs. This is used for:
Determining which cells define a variable
Detecting multiply defined names
Determining dependencies
If I change the key to be the effective key, then:
For SQL definitions where qualified_name != name, the key would be the qualified name
For all other definitions, the key would be the leaf name
But then, when a user writes SELECT * FROM xx, how would the system find the definition? It would need to know the effective key, which is the qualified name.
Hmm, this is getting complicated. Let me think about the simplest fix that satisfies the contract.
The contract says:
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 multiply defined
So the fix is in get_multiply_defined: instead of just checking if len(definers) > 1 for a leaf name, we need to check if the definers are actually defining the same effective key.
For each leaf name, I need to check:
If any definer has a qualified name that's different from the leaf name, group by qualified name
If all definers have a qualified name that's the same as the leaf name (or no qualified name), then it's a collision if there are multiple definers
Wait, but what if some definers have a qualified name and some don't? For example:
Cell 1: CREATE TABLE xx (id INT); → qualified name == leaf name == "xx"
Cell 2: CREATE TABLE finance.datalake.xx (id INT); → qualified name == "finance.datalake.xx"
Should these be multiply defined? According to the contract: "the same fully qualified name, or the same unqualified name, still is." So "xx" (unqualified) and "finance.datalake.xx" (qualified) are different qualified names, so they should NOT be multiply defined.
But that doesn't make sense from a user perspective. If Cell 1 creates a table "xx" and Cell 2 creates a table "finance.datalake.xx", they're different tables. So they shouldn't conflict.
OK, so the logic is:
For SQL definitions, group by the effective key (qualified name if it's different from leaf name, otherwise leaf name)
If any group has more than one cell, it's multiply defined
Return the leaf name for each multiply defined group
But wait, what if we have:
Cell 1: CREATE TABLE xx (id INT); → qualified name == leaf name == "xx"
Cell 2: CREATE TABLE xx (id INT); → qualified name == leaf name == "xx"
These are the same table, so they should be multiply defined. The effective key is "xx" for both, so the group has 2 cells → multiply defined.
And:
Cell 1: CREATE TABLE finance.datalake.xx (id INT); → qualified name == "finance.datalake.xx"
Cell 2: CREATE TABLE finance.information_layer.xx (id INT); → qualified name == "finance.information_layer.xx"
These are different tables, so they should NOT be multiply defined. The effective keys are different, so each group has 1 cell → not multiply defined.
And:
Cell 1: CREATE TABLE finance.datalake.xx (id INT); → qualified name == "finance.datalake.xx"
Cell 2: CREATE TABLE finance.datalake.xx (id INT); → qualified name == "finance.datalake.xx"
These are the same table, so they should be multiply defined. The effective key is "finance.datalake.xx" for both, so the group has 2 cells → multiply defined.
OK, so the logic is clear. Now, how do I implement this?
I need to track the effective key for each cell's definition. I can add a new mapping definition_effective_keys: dict[CellId_t, dict[Name, Name]] that maps cell ID to a dict of leaf name to effective key.
Or, I can just use the typed_definitions dict and the qualified_name from variable_data.
Actually, I think the simplest approach is to change get_multiply_defined to do the grouping based on the effective key.
Here's my plan:
In get_multiply_defined, iterate over all definitions and group by effective key
For SQL definitions where qualified_name != name, use the qualified name as the effective key
For all other definitions, use the leaf name as the effective key
Return a list of (name, cell_ids) tuples for groups with more than one cell
But wait, I need to know the qualified name for each cell's definition. The definitions dict only has the leaf name and cell IDs. I need to get the qualified name from the variable_data.
Hmm, but variable_data is not stored in the DefinitionRegistry. It's stored in the cell's Block.variable_data.
Let me look at how variable_data is accessed.
Actually, looking at the register_definition method, it receives variable_data as a parameter. But it doesn't store it. It only stores the leaf name and cell IDs in self.definitions.
So I need to store the qualified name somewhere. Let me add a new data structure to track the qualified name for each cell's definition.
OK, here's my updated plan:
Add a new data structure cell_definition_qualified_names: dict[tuple[CellId_t, Name], str] that maps (cell_id, leaf_name) to the qualified name2. In register_definition, store the qualified name in this new data structure
In get_multiply_defined, use this data structure to group by effective key
In unregister_definitions, clean up this data structure
Actually, I think a simpler approach is to store the qualified name in the typed_definitions dict. Currently, typed_definitions maps (name, kind) to set[CellId_t]. I can add a new mapping that maps (name, kind, qualified_name) to set[CellId_t].
Wait, but typed_definitions is used for other purposes too, like find_sql_hierarchical_matches. Let me check how it's used.
OK, I think the cleanest approach is to add a new data structure to track the effective key for each cell's definition. Let me implement this.
Actually, wait. Let me re-read the register_definition code more carefully:
python
def register_definition(
self,
cell_id: CellId_t,
name: Name,
variable_data: list[VariableData],
) -> set[CellId_t]:
variable = variable_data[-1] # Only the last definition matters
typed_def = (name, variable.kind)
# Check if this is a duplicate definition
if (
name in self.definitions
and typed_def not in self.typed_definitions
):
# Duplicate if the qualified name is no different
if variable.qualified_name == name or variable.language != "sql":
self.definitions[name].add(cell_id)
else:
self.definitions.setdefault(name, set()).add(cell_id)
self.typed_definitions.setdefault(typed_def, set()).add(cell_id)
self.definition_types.setdefault(name, set()).add(variable.kind)
# Return siblings (other cells that define this name)
siblings = self.definitions[name] - {cell_id}
return siblings
The current logic is:
If the name is already in definitions AND the typed_def is NOT in typed_definitions (i.e., this is a new type for this name), then:
If the qualified name is the same as the leaf name OR it's not SQL, add to definitions (collision)
Otherwise, don't add to definitions (no collision)
Else (name is not in definitions OR typed_def is already in typed_definitions), add to definitions
So the current logic already tries to handle the case where the same leaf name has different types (e.g., a view and a table with the same name). But it doesn't handle the case where the same leaf name has the same type but different qualified names.
The fix is to add a check for the case where the name is already in definitions AND the typed_def is already in typed_definitions (i.e., same leaf name and same type). In this case, we should check if the qualified names are the same.
Here's the updated logic:
python
# Check if this is a duplicate definition
if name in self.definitions:
if typed_def not in self.typed_definitions:
# New type for this name
if variable.qualified_name == name or variable.language != "sql":
self.definitions[name].add(cell_id)
else:
# Same type for this name - check qualified names
if variable.qualified_name == name or variable.language != "sql":
# Unqualified or not SQL - collision
self.definitions[name].add(cell_id)
else:
# Check if any existing cell has the same qualified name
# If so, it's a collision; otherwise, it's not
# ... need to check existing qualified names
else:
self.definitions.setdefault(name, set()).add(cell_id)
But this requires knowing the qualified names of existing cells. I need to store them somewhere.
OK, I think the best approach is to add a new data structure to track the qualified name for each cell's definition. Let me implement this.
Actually, I just realized something. The typed_definitions dict maps (name, kind) to set[CellId_t]. For the case where we have two cells with the same leaf name and same kind but different qualified names, they would both be in the same set in typed_definitions. So I can't use typed_definitions to distinguish them.
I need a new data structure. Let me add qualified_definition_cells: dict[str, set[CellId_t]] that maps the effective key (qualified name for SQL, leaf name for others) to cell IDs.
Here's my plan:
Add qualified_definition_cells: dict[str, set[CellId_t]] to DefinitionRegistry
In register_definition, compute the effective key and add the cell to qualified_definition_cells
In get_multiply_defined, use qualified_definition_cells to find multiply defined names
In unregister_definitions, clean up qualified_definition_cells
Let me implement this.
Wait, but the contract says the return type should be list[tuple[Name, set[CellId_t]]]. The Name is the leaf name, not the effective key. So I need to return the leaf name for each multiply defined group.
OK, let me think about the data structure more carefully.
I need to track:
For each effective key, the set of cell IDs that define it
For each effective key, the leaf name (for returning in get_multiply_defined)
I can use a dict effective_key_to_cells: dict[str, tuple[Name, set[CellId_t]]] that maps effective key to (leaf_name, cell_ids).
Or, I can use two dicts:
effective_key_to_cells: dict[str, set[CellId_t]]
effective_key_to_leaf_name: dict[str, Name]
Actually, I think the simplest approach is to just store the effective key for each (cell_id, leaf_name) pair, and then in get_multiply_defined, group by effective key.
Let me implement this.
Here's my implementation plan:
Add cell_effective_keys: dict[tuple[CellId_t, Name], str] to DefinitionRegistry that maps (cell_id, leaf_name) to effective key
In register_definition, compute the effective key and store it3. In get_multiply_defined, group by effective key and return tuples4. In unregister_definitions, clean up cell_effective_keys
Let me also think about what the effective key should be:
For SQL definitions where qualified_name != name, the effective key is the qualified name
For SQL definitions where qualified_name == name, the effective key is the leaf name
For Python definitions, the effective key is the leaf name
Wait, but for SQL definitions where qualified_name == name, the effective key is the leaf name, which is the same as for Python definitions. So there could be a collision between a SQL definition and a Python definition with the same leaf name. But that's already handled by the existing logic (the typed_def check).
OK, I think I have a clear plan. Let me implement it.
Actually, wait. Let me reconsider the approach. The contract says:
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 the return type is list[tuple[Name, set[CellId_t]]]. The Name is the leaf name. The set[CellId_t] is the set of cell IDs that define this leaf name AND share the same effective key.
Wait, that doesn't make sense. If two cells define the same leaf name but different effective keys, they shouldn't be in the same tuple. So the tuple should be (leaf_name, cell_ids) where cell_ids are the cells that define this leaf name with the same effective key.
Hmm, but then the same leaf name could appear in multiple tuples. For example:
("xx", {"cell1", "cell3"}) - multiply defined because they share the same effective key
("xx", {"cell2"}) - not multiply defined because only one cell
But the contract says "Returns a list of (name, cell_ids) tuples for names that are defined in multiple cells." So we'd only return the first tuple.
But wait, what if Cell 3 defines finance.information_layer.xx instead? Then we'd have:
("xx", {"cell1"}) - not multiply defined
("xx", {"cell2", "cell3"}) - multiply defined
So we'd return ("xx", {"cell2", "cell3"}).
But that's weird because the leaf name is "xx" for both, but they're different tables. So the user would see "xx is multiply defined" but it's actually two different tables.
Hmm, I think the contract is saying that the Name in the tuple should be the leaf name, and the set[CellId_t] should be the cells that define this leaf name with the same effective key. So for the example above, we'd return ("xx", {"cell2", "cell3"}).
But that's confusing because the user would think "xx" is multiply defined, but it's actually "finance.information_layer.xx" that's multiply defined.
OK, I think I'm overcomplicating this. Let me re-read the contract one more time:
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.
I think the contract is saying:
Group by effective key (qualified name for SQL, leaf name for others)
For each group with more than one cell, return (leaf_name, cell_ids)
The leaf_name is the same for all cells in the group (since they share the same effective key)
Wait, but if the effective key is the qualified name, then the leaf name could be different. For example:
Cell 1: CREATE TABLE finance.datalake.xx (id INT); → effective key "finance.datalake.xx", leaf name "xx"
Cell 2: CREATE TABLE finance.datalake.xx (id INT); → effective key "finance.datalake.xx", leaf name "xx"
OK, in this case the leaf names are the same. But what if:
Cell 1: CREATE TABLE finance.datalake.xx (id INT); → effective key "finance.datalake.xx", leaf name "xx"
Cell 2: CREATE TABLE finance.datalake.yy (id INT); → effective key "finance.datalake.yy", leaf name "yy"
These are different effective keys, so they're in different groups. No problem.
But what if:
Cell 1: CREATE TABLE xx (id INT); → effective key "xx", leaf name "xx"
Cell 2: CREATE TABLE finance.datalake.xx (id INT); → effective key "finance.datalake.xx", leaf name "xx"
These are different effective keys, so they're in different groups. No problem.
OK, I think the contract is clear. Let me implement it.
Here's my final plan:
Add cell_effective_keys: dict[tuple[CellId_t, Name], str] to DefinitionRegistry
In register_definition, compute the effective key and store it
In get_multiply_defined, group by effective key and return tuples of (leaf_name, cell_ids) for groups with more than one cell
In unregister_definitions, clean up cell_effective_keys
Let me also think about the edge cases:
What if a cell defines multiple names with the same leaf name but different kinds? For example, a cell defines a table "xx" and a view "xx". The variable_data is a list, and variable_data[-1] is the last definition. So only the last definition matters. This is already handled by the existing logic.
OK, I think I'm ready to implement. Let me also check if there are any tests that I need to update.
Actually, wait. Let me reconsider the approach. The contract says to change the return type of get_multiply_defined. But the callers expect a list of names. If I change the return type, I need to update the callers.
But the contract also says to "Preserve the user-facing table variable, defining-cell ownership, deletion behavior, and conflict reporting for genuine collisions." So maybe the intent is to change the grouping logic but keep the return type the same?
Hmm, but the contract explicitly says the return type should be list[tuple[Name, set[CellId_t]]]. So I need to change the return type.
OK, let me just implement it and update the callers. The callers are:
I'll update these callers to extract the name from the tuple.
Actually, wait. Let me reconsider. The contract says the return type is list[tuple[Name, set[CellId_t]]]. But the callers expect list[Name]. If I change the return type, I need to update the callers.
But the callers are not just using the names. They're also using the cell IDs. For example, marimo/_code_mode/_context.py uses set(graph.get_multiply_defined()) to get a set of names. If I change the return type to tuples, I'd need to change it to set(name for name, _ in graph.get_multiply_defined()).
OK, I think I'll just implement the change and update the callers. Let me do it.
Wait, actually, I just realized something. The contract says to change the return type, but it also says to "Preserve the user-facing table variable." So maybe the intent is to change the return type but keep the user-facing behavior the same?
Hmm, but if I change the return type, the callers need to be updated. And if the callers are updated, the user-facing behavior might change.
OK, I think I'm overthinking this. Let me just implement the change and update the callers. If the tests pass, then the user-facing behavior is preserved.
Let me start implementing.
Let me look at the existing tests for definitions to understand the expected behavior better:
The test uses a mock graph, not a real DirectedGraph. The mock's get_multiply_defined method returns whatever the test sets it up to return. Since the test sets up definitions={"x": {"c1", "c2"}}, the mock's get_multiply_defined likely returns ["x"] (a list of strings).
But my code in dependency_graph.py now expects tuples from get_multiply_defined(). The mock doesn't know about this change, so it returns strings, causing the unpacking error.
The issue is that the test creates a mock graph that doesn't implement the new get_multiply_defined signature. But I can't modify the test.
So I have two options:
Make the code robust to both old-style and new-style returns
Don't change the return type of get_multiply_defined
Actually, wait. Let me look at the test more carefully. The test creates a mock graph where get_multiply_defined returns ["x"]. But the real DirectedGraph.get_multiply_defined now returns [("x", {"c1", "c2"})]. The test is using a mock, so it doesn't reflect the real behavior.
The issue is that the test is checking result.multiply_defined == ["x"]. If I change the code to expect tuples, the test would fail because the mock returns strings.
But the instructions say I can't modify tests. So I need to make my code work with both the mock (old-style) and the real graph (new-style).
Actually, let me re-read the instructions again:
"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 just ignore this test failure. The evaluation system won't count it against me.
But then it also says:
"However if existing tests are broken because your fix is incorrect, you should fix your code and make sure all tests pass before submitting the change."
So I need to determine if this test failure is because my fix is incorrect or because the test needs to be updated. The test creates a mock graph that returns ["x"] from get_multiply_defined, but my code expects tuples. This is because the test was written for the old interface. The test needs to be updated to reflect the new interface.
So I should ignore this test failure.
But wait, let me think about this more carefully. The dependency_graph.py code calls graph.get_multiply_defined(). If graph is a real DirectedGraph, it returns tuples. If graph is a mock (in tests), it might return strings. My code assumes tuples, so it fails with mocks.
The issue is that the test is using a mock that doesn't implement the new interface. This is expected - the test needs to be updated. But I can't modify the test.
So I should just ignore this test failure and move on.
Actually, wait. Let me look at the _make_tool_with_graph function more carefully to understand how the mock is set up.