Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

Add variable type information to 'get_cell_dependency_graph' (#8663)

Titi Ala'ilimae95880d38e83
diff --git a/docs/guides/editor_features/tools.md b/docs/guides/editor_features/tools.md
index f3358a82bb..0ea388ea38 100644
--- a/docs/guides/editor_features/tools.md
+++ b/docs/guides/editor_features/tools.md
@@ -19,7 +19,7 @@ These tools are available when using the [chat panel in ask mode](ai_completion.
| **get_lightweight_cell_map** | Get an overview of notebook structure showing a preview of each cell. Takes a `session_id` and optional `preview_lines` parameter. Returns cell IDs, preview text, line counts, cell types (code, markdown, SQL), runtime state (`idle`, `running`, `queued`, etc.), and `has_output`/`has_console_output` flags. |
| **get_cell_runtime_data** | Get detailed runtime information for one or more cells. Takes `session_id` and `cell_ids` (list) parameters. Returns full cell code, error details, runtime metadata (execution time, runtime state), and variables defined by each cell. |
| **get_cell_outputs** | Get execution output from one or more cells. Takes `session_id` and `cell_ids` (list) parameters. Returns visual output (HTML, charts, tables, etc.) with mimetype, stdout messages, and stderr messages for each cell. |
-| **get_cell_dependency_graph** | Get the cell dependency graph showing variable ownership and cell relationships. Takes `session_id` and optional `cell_id` and `depth` parameters. Returns cell dependency info (defined variables with kind, referenced variables, parent/child cells), a variable ownership map, multiply-defined variables, and cycle information. Use `cell_id` to center on a specific cell and `depth` to limit traversal hops. |
+| **get_cell_dependency_graph** | Get the cell dependency graph showing variable ownership and cell relationships. Takes `session_id` and optional `cell_id` and `depth` parameters. Returns cell dependency info (defined variables with kind and runtime type, referenced variables, parent/child cells), a variable ownership map, multiply-defined variables, and cycle information. Use `cell_id` to center on a specific cell and `depth` to limit traversal hops. |
### Data
diff --git a/marimo/_ai/_tools/tools/dependency_graph.py b/marimo/_ai/_tools/tools/dependency_graph.py
index 04714099da..b11a3459a0 100644
--- a/marimo/_ai/_tools/tools/dependency_graph.py
+++ b/marimo/_ai/_tools/tools/dependency_graph.py
@@ -3,7 +3,6 @@ from __future__ import annotations
from collections import deque
from dataclasses import dataclass, field
-from typing import Optional
from marimo._ai._tools.base import ToolBase
from marimo._ai._tools.types import SuccessResult, ToolGuidelines
@@ -20,14 +19,15 @@ from marimo._types.ids import CellId_t, SessionId
@dataclass
class GetCellDependencyGraphArgs:
session_id: SessionId
- cell_id: Optional[CellId_t] = None
- depth: Optional[int] = None
+ cell_id: CellId_t | None = None
+ depth: int | None = None
@dataclass
class VariableInfo:
name: str
kind: str
+ datatype: str | None = None
@dataclass
@@ -98,6 +98,7 @@ class GetCellDependencyGraph(
self, args: GetCellDependencyGraphArgs
) -> GetCellDependencyGraphOutput:
session = self.context.get_session(args.session_id)
+ variable_values = session.session_view.variable_values
app = session.app_file_manager.app
cell_manager = app.cell_manager
# app.graph calls _maybe_initialize() which raises on cycles or
@@ -165,7 +166,11 @@ class GetCellDependencyGraph(
vd_list = cell_impl.variable_data[var_name]
if vd_list:
kind = vd_list[-1].kind
- defs.append(VariableInfo(name=var_name, kind=kind))
+ vv = variable_values.get(var_name)
+ datatype = vv.datatype if vv is not None else None
+ defs.append(
+ VariableInfo(name=var_name, kind=kind, datatype=datatype)
+ )
cells.append(
CellDependencyInfo(
@@ -218,7 +223,7 @@ class GetCellDependencyGraph(
def _get_cells_within_depth(
graph: DirectedGraph,
center_cell_id: CellId_t,
- depth: Optional[int],
+ depth: int | None,
) -> set[CellId_t]:
if depth is None:
all_related = graph.ancestors(center_cell_id) | graph.descendants(
@@ -248,7 +253,7 @@ def _get_cells_within_depth(
def _build_next_steps(
multiply_defined: list[str],
cycles: list[CycleInfo],
- cell_id: Optional[CellId_t],
+ cell_id: CellId_t | None,
) -> list[str]:
next_steps: list[str] = []
if multiply_defined:
diff --git a/marimo/_utils/dataclass_to_openapi.py b/marimo/_utils/dataclass_to_openapi.py
index 24c01bf9b1..8b4a0bfda7 100644
--- a/marimo/_utils/dataclass_to_openapi.py
+++ b/marimo/_utils/dataclass_to_openapi.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import dataclasses
import datetime
import sys
+import types
from collections.abc import Mapping, Sequence as CollectionSequence
from decimal import Decimal
from enum import Enum
@@ -31,6 +32,8 @@ from typing import Sequence # noqa: UP035
import msgspec
import msgspec.json
+_UNION_ORIGINS = (Union, types.UnionType)
+
class PythonTypeToOpenAPI:
def __init__(self, *, name_overrides: dict[Any, str], camel_case: bool):
@@ -64,7 +67,7 @@ class PythonTypeToOpenAPI:
if hasattr(py_type, "__supertype__"): # NewType check
return self.convert(py_type.__supertype__, processed_classes)
- if origin is Union:
+ if origin in _UNION_ORIGINS:
args = get_args(py_type)
if py_type in processed_classes:
ref = processed_classes[py_type]
@@ -324,9 +327,9 @@ def _is_optional(field: dataclasses.Field[Any]) -> bool:
"""
Check if a field is Optional
"""
- return (get_origin(field) is Union and type(None) in get_args(field)) or (
- get_origin(field) is NotRequired
- )
+ return (
+ get_origin(field) in _UNION_ORIGINS and type(None) in get_args(field)
+ ) or (get_origin(field) is NotRequired)
def is_typeddict_subclass(cls: Any) -> bool:
diff --git a/marimo/_utils/parse_dataclass.py b/marimo/_utils/parse_dataclass.py
index 3c96e1fb8c..3cbc64788c 100644
--- a/marimo/_utils/parse_dataclass.py
+++ b/marimo/_utils/parse_dataclass.py
@@ -5,6 +5,7 @@ import dataclasses
import datetime
import json
import sys
+import types
from enum import Enum
from typing import (
Any,
@@ -29,6 +30,8 @@ else:
T = TypeVar("T")
+_UNION_ORIGINS = (Union, types.UnionType)
+
def to_snake(string: str) -> str:
# basic conversion of javascript camel case to snake
@@ -120,7 +123,7 @@ class _DataclassParser:
for k, v in value.items()
}
)
- elif origin_cls == Union:
+ elif origin_cls in _UNION_ORIGINS:
arg_types = get_args(cls)
for arg_type in arg_types:
try:
diff --git a/tests/_ai/tools/tools/test_dependency_graph.py b/tests/_ai/tools/tools/test_dependency_graph.py
index ee96a3bba7..33c6e5cf18 100644
--- a/tests/_ai/tools/tools/test_dependency_graph.py
+++ b/tests/_ai/tools/tools/test_dependency_graph.py
@@ -45,6 +45,7 @@ def _make_tool_with_graph(
cycles: set | None = None,
ancestors_map: dict[str, set[str]] | None = None,
descendants_map: dict[str, set[str]] | None = None,
+ variable_values: dict | None = None,
) -> GetCellDependencyGraph:
graph = Mock()
graph.cells = {CellId_t(k): v for k, v in cell_impls.items()}
@@ -85,6 +86,7 @@ def _make_tool_with_graph(
mock_session = Mock()
mock_session.app_file_manager.app = mock_app
+ mock_session.session_view.variable_values = variable_values or {}
context = Mock(spec=ToolContext)
context.get_session.return_value = mock_session
@@ -344,3 +346,42 @@ def test_empty_graph():
assert result.variable_owners == {}
assert result.multiply_defined == []
assert result.cycles == []
+
+
+def test_variable_datatype_from_runtime():
+ """datatype should be populated from session_view.variable_values."""
+ from marimo._messaging.notification import VariableValue
+
+ tool = _make_tool_with_graph(
+ cell_impls={"c1": _make_cell_impl(defs={"df", "n"}, refs=set())},
+ parents={"c1": set()},
+ children={"c1": set()},
+ definitions={"df": {"c1"}, "n": {"c1"}},
+ cell_data_list=[_make_cell_data("c1")],
+ variable_values={
+ "df": VariableValue(name="df", value=None, datatype="DataFrame"),
+ "n": VariableValue(name="n", value="42", datatype="int"),
+ },
+ )
+ result = tool.handle(
+ GetCellDependencyGraphArgs(session_id=SessionId("s1"))
+ )
+ defs = {vi.name: vi for vi in result.cells[0].defs}
+ assert defs["df"].datatype == "DataFrame"
+ assert defs["n"].datatype == "int"
+
+
+def test_variable_datatype_none_when_not_executed():
+ """datatype is None when variable has no runtime value."""
+ tool = _make_tool_with_graph(
+ cell_impls={"c1": _make_cell_impl(defs={"x"}, refs=set())},
+ parents={"c1": set()},
+ children={"c1": set()},
+ definitions={"x": {"c1"}},
+ cell_data_list=[_make_cell_data("c1")],
+ variable_values={}, # nothing executed
+ )
+ result = tool.handle(
+ GetCellDependencyGraphArgs(session_id=SessionId("s1"))
+ )
+ assert result.cells[0].defs[0].datatype is None
diff --git a/tests/_utils/test_dataclass_to_openapi.py b/tests/_utils/test_dataclass_to_openapi.py
index 058cbc5c95..d6987ec710 100644
--- a/tests/_utils/test_dataclass_to_openapi.py
+++ b/tests/_utils/test_dataclass_to_openapi.py
@@ -2,6 +2,7 @@ from __future__ import annotations
import dataclasses
import sys
+import types
from typing import Any, ClassVar, Literal, Optional, TypedDict, Union
import pytest
@@ -157,6 +158,66 @@ def test_optional() -> None:
}
+def test_pipe_union_nullable() -> None:
+ """types.UnionType (X | None) should be handled like Optional[X]."""
+ pipe_type = str | None
+ assert type(pipe_type) is types.UnionType
+ openapi_spec = PythonTypeToOpenAPI(
+ name_overrides={},
+ camel_case=False,
+ ).convert(pipe_type, {})
+ assert openapi_spec == {
+ "type": "string",
+ "nullable": True,
+ }
+
+
+def test_pipe_union_multi() -> None:
+ """types.UnionType with multiple non-None args produces oneOf."""
+ pipe_type = int | str
+ assert type(pipe_type) is types.UnionType
+ openapi_spec = PythonTypeToOpenAPI(
+ name_overrides={},
+ camel_case=False,
+ ).convert(pipe_type, {})
+ assert openapi_spec == {
+ "oneOf": [
+ {"type": "integer"},
+ {"type": "string"},
+ ],
+ }
+
+
+def test_pipe_union_in_dataclass() -> None:
+ """Dataclass fields using X | None should produce nullable schema."""
+
+ @dataclasses.dataclass
+ class PipeOptional:
+ required: str
+ optional_int: int | None = None
+
+ openapi_spec = PythonTypeToOpenAPI(
+ name_overrides={},
+ camel_case=False,
+ ).convert(PipeOptional, {})
+ assert openapi_spec == {
+ "type": "object",
+ "properties": {
+ "required": {"type": "string"},
+ "optional_int": {"type": "integer", "nullable": True},
+ },
+ "required": ["required"],
+ }
+
+
+def test_is_optional_with_pipe_union() -> None:
+ """_is_optional should recognise types.UnionType containing None."""
+ from marimo._utils.dataclass_to_openapi import _is_optional
+
+ assert _is_optional(str | None) is True
+ assert _is_optional(str | int) is False
+
+
if sys.version_info >= (3, 11):
from typing import NotRequired
diff --git a/tests/_utils/test_parse_dataclass.py b/tests/_utils/test_parse_dataclass.py
index 5222b0fc88..2aad6c154f 100644
--- a/tests/_utils/test_parse_dataclass.py
+++ b/tests/_utils/test_parse_dataclass.py
@@ -902,6 +902,35 @@ def test_date_and_datetime_types() -> None:
)
+def test_pipe_union_optional() -> None:
+ """Dataclass fields using X | None should round-trip through parse_raw."""
+
+ @dataclass
+ class PipeOptional:
+ name: str
+ age: int | None = None
+
+ parsed = parse_raw({"name": "Alice"}, PipeOptional)
+ assert parsed == PipeOptional(name="Alice", age=None)
+
+ parsed = parse_raw({"name": "Bob", "age": 30}, PipeOptional)
+ assert parsed == PipeOptional(name="Bob", age=30)
+
+
+def test_pipe_union_multi_types() -> None:
+ """Dataclass fields using X | Y (no None) should parse correctly."""
+
+ @dataclass
+ class PipeUnion:
+ value: int | str
+
+ parsed = parse_raw({"value": 42}, PipeUnion)
+ assert parsed == PipeUnion(value=42)
+
+ parsed = parse_raw({"value": "hello"}, PipeUnion)
+ assert parsed == PipeUnion(value="hello")
+
+
class StructClass(msgspec.Struct):
limit: int