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.

fix: safe annotation quotes (#7028)

Dylan Madisetti8fbef8bce67b
diff --git a/marimo/_ast/codegen.py b/marimo/_ast/codegen.py
index 4af45b450e..aa2ed0d545 100644
--- a/marimo/_ast/codegen.py
+++ b/marimo/_ast/codegen.py
@@ -246,7 +246,9 @@ def to_annotated_string(
annotation = variable.annotation_data
if annotation:
if annotation.refs - allowed_refs:
- response[name] = f'"{annotation.repr}"'
+ # replace unescaped quotes with escaped quotes
+ safe_repr = re.sub(r'(?<!\\)"', r'\\"', annotation.repr)
+ response[name] = f'"{safe_repr}"'
else:
response[name] = annotation.repr
return response
@@ -419,6 +421,25 @@ def serialize_cell(
raise ValueError("Unknown cell status, please report this issue.")
+def safe_serialize_cell(
+ extraction: TopLevelExtraction, status: TopLevelStatus
+) -> str:
+ """Additional defensive layer- we should _never_ generate invalid code."""
+ code = serialize_cell(extraction, status)
+ try:
+ ast_parse(code)
+ except SyntaxError as e:
+ LOGGER.warning(
+ f"Generated code for cell {status.name} is invalid, "
+ "falling back to unparsable cell. Please report this error. "
+ f"Error: {e}"
+ )
+ return generate_unparsable_cell(
+ code=status.code, config=status.cell_config, name=status.name
+ )
+ return code
+
+
def generate_app_constructor(config: Optional[_AppConfig]) -> str:
updates = {}
# only include a config setting if it's not a default setting, to
@@ -461,7 +482,9 @@ def generate_filecontents(
if setup_cell:
toplevel_defs = set(setup_cell.defs)
extraction = TopLevelExtraction(codes, names, cell_configs, toplevel_defs)
- cell_blocks = [serialize_cell(extraction, status) for status in extraction]
+ cell_blocks = [
+ safe_serialize_cell(extraction, status) for status in extraction
+ ]
filecontents = []
if header_comments is not None:
diff --git a/tests/_ast/test_codegen.py b/tests/_ast/test_codegen.py
index 604ed7bdae..39953cfd1b 100644
--- a/tests/_ast/test_codegen.py
+++ b/tests/_ast/test_codegen.py
@@ -8,6 +8,7 @@ from inspect import cleandoc
from pathlib import Path
from textwrap import dedent
from typing import Any, Optional
+from unittest.mock import patch
import codegen_data.test_main as mod
import pytest
@@ -449,6 +450,85 @@ class TestGeneration:
)
assert fndef == expected
+ def test_quote_nested_edge_cases(self) -> None:
+ """Test edge cases for quote standardization in type annotations."""
+ # Test mixed quotes where double quotes are preserved
+ referring = 'x: tuple[tuple[Literal["foo", \'bar\']]] = "((foo,),)"'
+ ref_vars = compile_cell(referring).init_variable_data
+
+ code = "z = x"
+ cell = compile_cell(code)
+ fndef = codegen.to_functiondef(
+ cell, "foo", allowed_refs={"tuple"}, variable_data=ref_vars
+ )
+ expected = "\n".join(
+ [
+ "@app.cell",
+ 'def foo(x: "tuple[tuple[Literal[\\"foo\\", \\"bar\\"]]]"):',
+ " z = x",
+ " return (z,)",
+ ]
+ )
+ assert fndef == expected
+
+ def test_quote_nested_esscaped_edge_cases(self) -> None:
+ referring = "x: Literal['say \"hello\"'] = 'say \"hello\"'"
+ ref_vars = compile_cell(referring).init_variable_data
+
+ code = "z = x"
+ cell = compile_cell(code)
+ fndef = codegen.to_functiondef(
+ cell, "foo", allowed_refs=set(), variable_data=ref_vars
+ )
+ expected = "\n".join(
+ [
+ "@app.cell",
+ 'def foo(x: "Literal[\'say \\"hello\\"\']"):',
+ " z = x",
+ " return (z,)",
+ ]
+ )
+ assert fndef == expected
+
+ def test_safe_serialize_cell_handles_syntax_error(self) -> None:
+ """Test that safe_serialize_cell falls back when ast_parse fails.
+
+ This test mocks ast_parse to fail, exercising the except block in
+ safe_serialize_cell that falls back to generate_unparsable_cell.
+ Goes through the full codegen path via generate_filecontents.
+ """
+ # Create a simple cell that would normally serialize fine
+ code = "x = 1"
+ name = "test_cell"
+
+ # Mock ast_parse to raise SyntaxError and mock the logger
+ with (
+ patch("marimo._ast.codegen.ast_parse") as mock_ast_parse,
+ patch("marimo._ast.codegen.LOGGER.warning") as mock_warning,
+ ):
+ mock_ast_parse.side_effect = SyntaxError("Mock syntax error")
+
+ # Go through the full codegen path
+ result = wrap_generate_filecontents([code], [name])
+
+ # Verify ast_parse was called
+ assert mock_ast_parse.called
+
+ # Verify the result contains an unparsable cell format
+ # (it should contain the original code)
+ assert "x = 1" in result
+ # Unparsable cells use app._unparsable_cell wrapper
+ assert "app._unparsable_cell" in result
+ # Verify it has the cell name
+ assert name in result
+
+ # Verify warning was logged with the correct message
+ assert mock_warning.called
+ warning_message = mock_warning.call_args[0][0]
+ assert "falling back to unparsable cell" in warning_message
+ assert name in warning_message
+ assert "Mock syntax error" in warning_message
+
@staticmethod
def test_generate_app_constructor_with_auto_download() -> None:
config = _AppConfig(