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.

tidy: Clean up stack traces with marimo check (#6423)

Dylan Madisetti0c7a6afb858e
diff --git a/marimo/_ast/app.py b/marimo/_ast/app.py
index 0b7d5f9e24..6e40333dc5 100644
--- a/marimo/_ast/app.py
+++ b/marimo/_ast/app.py
@@ -694,7 +694,22 @@ class App:
edit.invoke(ctx)
return ((), {})
- self._maybe_initialize()
+ try:
+ self._maybe_initialize()
+ except (CycleError, MultipleDefinitionError, UnparsableError) as e:
+ from marimo._lint import collect_messages
+
+ if self._filename is not None:
+ # Run linting checks to provide better error messages for breaking errors.
+ linter, messages = collect_messages(self._filename)
+ if messages:
+ sys.stderr.write(messages)
+ # Re-raise the original exception but without trace
+ marimo_error = type(e)(str(e))
+ raise marimo_error from None
+ else:
+ raise
+
glbls: dict[str, Any] = {}
if self._setup is not None:
glbls = {**self._setup._glbls}
diff --git a/marimo/_ast/errors.py b/marimo/_ast/errors.py
index 5283249d54..df1d9e3413 100644
--- a/marimo/_ast/errors.py
+++ b/marimo/_ast/errors.py
@@ -1,4 +1,6 @@
-# Copyright 2024 Marimo. All rights reserved.
+# Copyright 2025 Marimo. All rights reserved.
+
+
class SetupRootError(Exception):
pass
diff --git a/marimo/_cli/cli.py b/marimo/_cli/cli.py
index 76431b3b51..235091a489 100644
--- a/marimo/_cli/cli.py
+++ b/marimo/_cli/cli.py
@@ -61,8 +61,10 @@ def helpful_usage_error(self: Any, file: Any = None) -> None:
def check_app_correctness(filename: str, noninteractive: bool = True) -> None:
try:
status = get_notebook_status(filename).status
- except SyntaxError:
- import traceback
+ except (SyntaxError, MarimoFileError):
+ # Exit early if we can
+ if not noninteractive:
+ raise
# This prints a more readable error message, without internal details
# e.g.
@@ -70,8 +72,10 @@ def check_app_correctness(filename: str, noninteractive: bool = True) -> None:
# x.
# ^
# SyntaxError: invalid syntax
- click.echo(f"Failed to parse notebook: {filename}\n", err=True)
- raise click.ClickException(traceback.format_exc(limit=0)) from None
+ from marimo._lint import collect_messages
+
+ _, message = collect_messages(filename)
+ raise click.ClickException(message.strip()) from None
if status == "invalid" and filename.endswith(".py"):
# fail for python scripts, almost certainly do not want to override contents
@@ -225,6 +229,8 @@ sandbox_message = (
"install automatically. Requires uv."
)
+check_message = "Disable a static check of the notebook before running."
+
@click.group(
help=main_help_msg,
@@ -953,6 +959,14 @@ Example:
type=bool,
help=sandbox_message,
)
+ "--check/--no-check",
+ is_flag=True,
+ default=True,
+ show_default=False,
+ type=bool,
+ help=check_message,
+)
@click.option(
"--server-startup-command",
default=None,
@@ -988,6 +1002,7 @@ def run(
allow_origins: tuple[str, ...],
redirect_console_to_browser: bool,
sandbox: Optional[bool],
+ check: bool,
server_startup_command: Optional[str],
asset_url: Optional[str],
name: str,
@@ -1026,9 +1041,20 @@ def run(
# correctness check - don't start the server if we can't import the module
check_app_correctness(name)
+ file = MarimoPath(name)
+ if check:
+ from marimo._lint import collect_messages
+
+ linter, message = collect_messages(file.absolute_name)
+ if linter.errored:
+ raise click.ClickException(
+ red("Failure")
+ + ": The notebook has errors, fix them before running.\n"
+ + message.strip()
+ )
start(
- file_router=AppFileRouter.from_filename(MarimoPath(name)),
+ file_router=AppFileRouter.from_filename(file),
development_mode=GLOBAL_SETTINGS.DEVELOPMENT_MODE,
quiet=GLOBAL_SETTINGS.QUIET,
host=host,
diff --git a/marimo/_lint/__init__.py b/marimo/_lint/__init__.py
index b2801be553..dcf4c0c550 100644
--- a/marimo/_lint/__init__.py
+++ b/marimo/_lint/__init__.py
@@ -13,6 +13,14 @@ if TYPE_CHECKING:
from collections.abc import Callable
+# Define severity ordering (lower index = higher priority)
+SEVERITY_ORDER = {
+ Severity.BREAKING: 0,
+ Severity.RUNTIME: 1,
+ Severity.FORMATTING: 2,
+}
+
+
def run_check(
file_patterns: tuple[str, ...],
pipe: Callable[[str], None] | None = None,
@@ -41,6 +49,56 @@ def run_check(
return linter
+def collect_messages(
+ file_patterns: str | tuple[str, ...],
+ min_severity: Severity = Severity.BREAKING,
+) -> tuple[Linter, str]:
+ """Run linting checks and collect all messages as a string.
+
+ Simple interface for collecting linting messages without streaming output.
+ Used when you need to capture all linting output for error reporting.
+ Never performs fixes - only collects messages.
+
+ Args:
+ file_patterns: File pattern(s) for file discovery
+ min_severity: Minimum severity level to include (defaults to BREAKING)
+
+ Returns:
+ Tuple of (Linter with per-file status and diagnostics, collected messages)
+ """
+ messages = []
+
+ def message_pipe(msg: str) -> None:
+ messages.append(msg)
+
+ # Normalize to tuple
+ if isinstance(file_patterns, str):
+ file_patterns = (file_patterns,)
+
+ # Create filtered rules based on severity
+ from marimo._lint.rules import RULE_CODES
+
+ min_severity_level = SEVERITY_ORDER[min_severity]
+ filtered_rules = [
+ rule()
+ for rule in RULE_CODES.values()
+ if SEVERITY_ORDER[rule().severity] <= min_severity_level
+ ]
+
+ # Create linter with filtered rules
+ linter = Linter(
+ pipe=message_pipe,
+ fix_files=False,
+ unsafe_fixes=False,
+ rules=filtered_rules,
+ )
+
+ files_to_check = expand_file_patterns(file_patterns)
+ linter.run_streaming(files_to_check)
+
+ return linter, "\n".join(messages)
+
+
__all__ = [
"Diagnostic",
"LintRule",
@@ -48,6 +106,7 @@ __all__ = [
"EarlyStoppingConfig",
"RuleEngine",
"run_check",
+ "collect_messages",
"Linter",
"FileStatus",
]
diff --git a/marimo/_lint/linter.py b/marimo/_lint/linter.py
index 4c9cb5ed20..5a367c05c0 100644
--- a/marimo/_lint/linter.py
+++ b/marimo/_lint/linter.py
@@ -12,13 +12,15 @@ from marimo._ast.load import get_notebook_status
from marimo._ast.parse import MarimoFileError
from marimo._cli.print import red
from marimo._convert.converters import MarimoConvert
-from marimo._lint.diagnostic import Diagnostic
+from marimo._lint.diagnostic import Diagnostic, Severity
from marimo._lint.rule_engine import EarlyStoppingConfig, RuleEngine
from marimo._schemas.serialization import NotebookSerialization
if TYPE_CHECKING:
from collections.abc import AsyncIterator, Callable
+ from marimo._lint.rules.base import LintRule
+
@dataclass
class FileStatus:
@@ -48,8 +50,12 @@ class Linter:
pipe: Callable[[str], None] | None = None,
fix_files: bool = False,
unsafe_fixes: bool = False,
+ rules: list[LintRule] | None = None,
):
- self.rule_engine = RuleEngine.create_default(early_stopping)
+ if rules is not None:
+ self.rule_engine = RuleEngine(rules, early_stopping)
+ else:
+ self.rule_engine = RuleEngine.create_default(early_stopping)
self.pipe = pipe
self.fix_files = fix_files
self.unsafe_fixes = unsafe_fixes
@@ -170,6 +176,11 @@ class Linter:
)
if not will_fix:
self.issues_count += 1
+ if diagnostic.severity == Severity.BREAKING:
+ self.errored = True
+
+ if file_status.failed:
+ self.errored = True
if not self.pipe:
return
@@ -223,8 +234,7 @@ class Linter:
self.files.append(file_status)
# Stream output via pipe if available
- if self.pipe:
- self._pipe_file_status(file_status)
+ self._pipe_file_status(file_status)
# Add to fix queue and potentially fix if requested
if self.fix_files and not (
diff --git a/tests/_ast/codegen_data/test_non_marimo.py b/tests/_ast/codegen_data/test_non_marimo.py
new file mode 100644
index 0000000000..81ff614b66
--- /dev/null
+++ b/tests/_ast/codegen_data/test_non_marimo.py
@@ -0,0 +1,3 @@
+import os
+
+import marimo
diff --git a/tests/_ast/test_parse.py b/tests/_ast/test_parse.py
index 3b0149d1da..4206081b54 100644
--- a/tests/_ast/test_parse.py
+++ b/tests/_ast/test_parse.py
@@ -130,3 +130,16 @@ class TestParser:
# Valid currently
# TODO: Propagate decorators violations.
assert len(notebook.violations) == 0
+
+ @staticmethod
+ def test_parse_non_marimo() -> None:
+ import pytest
+
+ from marimo._ast.parse import MarimoFileError
+
+ # Non-marimo files that have marimo imports but no App definition
+ # should raise MarimoFileError with the expected message
+ with pytest.raises(
+ MarimoFileError, match="`marimo.App` definition expected."
+ ):
+ parse_notebook(get_filepath("test_non_marimo").read_text())
diff --git a/tests/_cli/test_cli_check.py b/tests/_cli/test_cli_check.py
index 9fbce28c26..a10a029b05 100644
--- a/tests/_cli/test_cli_check.py
+++ b/tests/_cli/test_cli_check.py
@@ -174,3 +174,28 @@ if __name__ == "__main__":
# Should succeed
assert result.exit_code == 0, result.output
+
+ def test_check_command_with_message_collection(self):
+ """Test that CLI check command uses message collection properly."""
+ runner = CliRunner()
+ import os
+
+ # Use existing test file with syntax errors
+ test_file = os.path.join(
+ os.path.dirname(os.path.dirname(__file__)),
+ "_lint",
+ "test_files",
+ "syntax_errors.py",
+ )
+
+ # Test the check command
+ result = runner.invoke(check, [test_file])
+
+ # Should return non-zero exit code for files with errors
+ assert result.exit_code != 0
+ # Should contain linting output
+ assert len(result.output) > 0
+ assert (
+ "invalid-syntax" in result.output
+ or "error" in result.output.lower()
+ )
diff --git a/tests/_lint/test_lint_system.py b/tests/_lint/test_lint_system.py
index 485af068a4..26f776f22c 100644
--- a/tests/_lint/test_lint_system.py
+++ b/tests/_lint/test_lint_system.py
@@ -1,6 +1,8 @@
# Copyright 2025 Marimo. All rights reserved.
"""Unit tests for the marimo lint system."""
+from unittest.mock import patch
+
from marimo._ast.parse import parse_notebook
from marimo._lint.context import LintContext, RuleContext
from marimo._lint.rule_engine import RuleEngine
@@ -200,3 +202,81 @@ class TestRuleEngine:
errors = checker.check_notebook_sync(notebook)
assert isinstance(errors, list)
+
+
+class TestMessageCollectionEntryPoints:
+ """Test that message collection works through the main entry points."""
+
+ def test_app_initialization_with_message_collection(self):
+ """Test that App initialization uses message collection when it encounters errors."""
+ import os
+ from io import StringIO
+
+ from marimo._ast.app import App
+
+ # Use existing test file with multiple definitions (which should trigger error handling)
+ test_file = os.path.join(
+ os.path.dirname(__file__), "test_files", "multiple_definitions.py"
+ )
+ app = App(filename=test_file)
+
+ # Capture stderr to verify message collection
+ captured_stderr = StringIO()
+ with patch("sys.stderr", captured_stderr):
+ try:
+ app._maybe_initialize()
+ except Exception:
+ pass # Expected to potentially raise an error
+
+ # Verify that if there were errors, linting messages were written to stderr
+ stderr_output = captured_stderr.getvalue()
+ # The test passes if either no errors occurred, or if errors occurred with proper message collection
+ assert isinstance(stderr_output, str) # Should always be a string
+
+ def test_app_initialization_with_success(self):
+ """Test that App initialization works normally with valid notebooks."""
+ import os
+
+ from marimo._ast.app import App
+
+ # Use existing test file with formatting issues but valid structure
+ test_file = os.path.join(
+ os.path.dirname(__file__), "test_files", "formatting.py"
+ )
+ app = App(filename=test_file)
+
+ # Should not raise an exception for valid notebooks
+ # If it does raise an exception, it should not be an UnparsableError
+ try:
+ app._maybe_initialize()
+ except Exception as e:
+ # If it fails, it should be for a different reason than unparsable
+ if "UnparsableError" in str(type(e)):
+ raise AssertionError(f"Unexpected UnparsableError: {e}") from e
+
+ def test_collect_messages_severity_filtering(self):
+ """Test that collect_messages severity filtering works correctly."""
+ import os
+
+ from marimo._lint import Severity, collect_messages
+
+ test_file = os.path.join(
+ os.path.dirname(__file__), "test_files", "formatting.py"
+ )
+
+ # Test with BREAKING severity (default)
+ linter_breaking, messages_breaking = collect_messages(test_file)
+
+ # Test with FORMATTING severity (should include more issues)
+ linter_all, messages_all = collect_messages(
+ test_file, min_severity=Severity.FORMATTING
+ )
+
+ # Both should return valid results
+ assert isinstance(linter_breaking.errored, bool)
+ assert isinstance(messages_breaking, str)
+ assert isinstance(linter_all.errored, bool)
+ assert isinstance(messages_all, str)
+
+ # FORMATTING severity should typically find more issues
+ assert len(messages_all) >= len(messages_breaking)