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.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
feat: Add line highlighting for syntax errors (#7047)
SamarJyoti496345a4197314e
diff --git a/frontend/src/__mocks__/notebook.ts b/frontend/src/__mocks__/notebook.tsindex 64f7c1752f..42219a7535 100644--- a/frontend/src/__mocks__/notebook.ts+++ b/frontend/src/__mocks__/notebook.ts@@ -4,7 +4,11 @@ import { createRef } from "react";import { vi } from "vitest";import type { CellActions, NotebookState } from "@/core/cells/cells";import { CellId } from "@/core/cells/ids";-import { type CellData, createCellRuntimeState } from "@/core/cells/types";+import {+ type CellData,+ type CellRuntimeState,+ createCellRuntimeState,+} from "@/core/cells/types";import type { MarimoError } from "@/core/kernel/messages";import { MultiColumn } from "@/utils/id-tree";import { Objects } from "@/utils/objects";@@ -19,8 +23,10 @@ export const MockNotebook = {notebookState: (opts?: {cellData: Record<string, Partial<CellData>>;+ cellRuntime?: Record<string, Partial<CellRuntimeState>>;}): NotebookState => {const cellData = opts?.cellData || {};+ const cellRuntime = opts?.cellRuntime || {};return {cellData: Objects.mapValues(cellData, (data, cellId) => ({id: cellId as CellId,@@ -39,8 +45,8 @@ export const MockNotebook = {...data,})),cellIds: MultiColumn.from([Object.keys(cellData) as CellId[]]),- cellRuntime: Objects.mapValues(cellData, (_data) =>- createCellRuntimeState({}),+ cellRuntime: Objects.mapValues(cellData, (_data, cellId) =>+ createCellRuntimeState({ ...(cellRuntime[cellId] || {}) }),),cellHandles: Objects.mapValues(cellData, (_data) => createRef()),cellLogs: [],diff --git a/frontend/src/core/cells/__tests__/cells.test.ts b/frontend/src/core/cells/__tests__/cells.test.tsindex 0e624e8690..94f43d029e 100644--- a/frontend/src/core/cells/__tests__/cells.test.ts+++ b/frontend/src/core/cells/__tests__/cells.test.ts@@ -3,6 +3,7 @@import { python } from "@codemirror/lang-python";import { EditorState } from "@codemirror/state";import { EditorView } from "@codemirror/view";+import { createStore } from "jotai";import {afterAll,beforeAll,@@ -12,6 +13,7 @@ import {it,vi,} from "vitest";+import { MockNotebook } from "@/__mocks__/notebook";import type { CellHandle } from "@/components/editor/notebook-cell";import { CellId, SETUP_CELL_ID } from "@/core/cells/ids";import { foldAllBulk, unfoldAllBulk } from "@/core/codemirror/editing/commands";@@ -24,6 +26,7 @@ import {exportedForTesting,flattenTopLevelNotebookCells,type NotebookState,+ notebookAtom,} from "../cells";import {focusAndScrollCellIntoView,@@ -2679,3 +2682,205 @@ describe("isCellCodeHidden", () => {);});});++describe("createTracebackInfoAtom", () => {+ const store = createStore();++ it("returns undefined when cell has no errors", async () => {+ store.set(+ notebookAtom,+ MockNotebook.notebookState({+ cellData: {+ cell1: {+ id: "cell1" as CellId,+ name: "cell1",+ code: "",+ },+ },+ }),+ );++ const tracebackAtom = exportedForTesting.createTracebackInfoAtom(+ "cell1" as CellId,+ );+ const traceback = store.get(tracebackAtom);++ expect(traceback).toBeUndefined();+ });++ it("extracts lineno from syntax errors", async () => {+ store.set(+ notebookAtom,+ MockNotebook.notebookState({+ cellData: {+ cell1: { id: "cell1" as CellId, name: "cell1", code: "x = 1" },+ },+ cellRuntime: {+ cell1: {+ output: {+ channel: "marimo-error",+ data: [{ type: "syntax", msg: "Syntax error", lineno: 5 }],+ mimetype: "application/vnd.marimo+error",+ },+ },+ },+ }),+ );++ const tracebackAtom = exportedForTesting.createTracebackInfoAtom(+ "cell1" as CellId,+ );+ const traceback = store.get(tracebackAtom);++ expect(traceback).toBeDefined();+ expect(traceback).toHaveLength(1);+ expect(traceback![0]).toEqual({+ kind: "cell",+ cellId: "cell1",+ lineNumber: 5,+ });+ });++ it("handles syntax errors with lineno = 0", async () => {+ store.set(+ notebookAtom,+ MockNotebook.notebookState({+ cellData: {+ cell1: { id: "cell1" as CellId, name: "cell1", code: "x = 1" },+ },+ cellRuntime: {+ cell1: {+ output: {+ channel: "marimo-error",+ data: [{ type: "syntax", msg: "Syntax error", lineno: 0 }],+ mimetype: "application/vnd.marimo+error",+ },+ },+ },+ }),+ );++ const tracebackAtom = exportedForTesting.createTracebackInfoAtom(+ "cell1" as CellId,+ );+ const traceback = store.get(tracebackAtom);+ expect(traceback).toBeDefined();+ expect(traceback).toHaveLength(1);+ expect(traceback![0].lineNumber).toBe(0);+ });++ it("ignores syntax errors with lineno = null", () => {+ store.set(+ notebookAtom,+ MockNotebook.notebookState({+ cellData: {+ cell1: { id: "cell1" as CellId, name: "cell1", code: "x = 1" },+ },+ cellRuntime: {+ cell1: {+ output: {+ channel: "marimo-error",+ data: [{ type: "syntax", msg: "Syntax error", lineno: null }],+ mimetype: "application/vnd.marimo+error",+ },+ },+ },+ }),+ );++ const tracebackAtom = exportedForTesting.createTracebackInfoAtom(+ "cell1" as CellId,+ );+ const traceback = store.get(tracebackAtom);++ expect(traceback).toBeUndefined();+ });++ it("handles multiple syntax errors", () => {+ store.set(+ notebookAtom,+ MockNotebook.notebookState({+ cellData: {+ cell1: { id: "cell1" as CellId, name: "cell1", code: "x = 1" },+ },+ cellRuntime: {+ cell1: {+ output: {+ channel: "marimo-error",+ data: [+ { type: "syntax", msg: "Syntax error", lineno: 3 },+ { type: "syntax", msg: "Syntax error", lineno: 7 },+ ],+ mimetype: "application/vnd.marimo+error",+ },+ },+ },+ }),+ );++ const tracebackAtom = exportedForTesting.createTracebackInfoAtom(+ "cell1" as CellId,+ );+ const traceback = store.get(tracebackAtom);+ expect(traceback).toBeDefined();+ expect(traceback).toHaveLength(2);+ expect(traceback![0].lineNumber).toBe(3);+ expect(traceback![1].lineNumber).toBe(7);+ });++ it("returns undefined when cell is queued", async () => {+ store.set(+ notebookAtom,+ MockNotebook.notebookState({+ cellData: {+ cell1: { id: "cell1" as CellId, name: "cell1", code: "x = 1" },+ },+ cellRuntime: {+ cell1: {+ output: {+ channel: "marimo-error",+ data: [{ type: "syntax", msg: "Syntax error", lineno: 1 }],+ mimetype: "application/vnd.marimo+error",+ },+ status: "queued",+ },+ },+ }),+ );++ const tracebackAtom = exportedForTesting.createTracebackInfoAtom(+ "cell1" as CellId,+ );+ const traceback = store.get(tracebackAtom);++ expect(traceback).toBeUndefined();+ });++ it("returns undefined when cell is running", () => {+ store.set(+ notebookAtom,+ MockNotebook.notebookState({+ cellData: {+ cell1: { id: "cell1" as CellId, name: "cell1", code: "x = 1" },+ },+ cellRuntime: {+ cell1: {+ output: {+ channel: "marimo-error",+ data: [{ type: "syntax", msg: "Syntax error", lineno: 1 }],+ mimetype: "application/vnd.marimo+error",+ },+ status: "running",+ },+ },+ }),+ );++ const tracebackAtom = exportedForTesting.createTracebackInfoAtom(+ "cell1" as CellId,+ );+ const traceback = store.get(tracebackAtom);++ expect(traceback).toBeUndefined();+ });+});diff --git a/frontend/src/core/cells/cells.ts b/frontend/src/core/cells/cells.tsindex 8efb02e2f5..556b0ca071 100644--- a/frontend/src/core/cells/cells.ts+++ b/frontend/src/core/cells/cells.ts@@ -1681,40 +1681,59 @@ export function createUntouchedCellAtom(cellId: CellId): Atom<boolean> {export function createTracebackInfoAtom(cellId: CellId,): Atom<TracebackInfo[] | undefined> {- // We create an intermediate atom that just computes the string- // so it prevents downstream recomputations.- const tracebackStringAtom = atom<string | undefined>((get) => {- const notebook = get(notebookAtom);- const data = notebook.cellRuntime[cellId];+ //use existing cellRuntimeAtom for intermediate computation+ const cellRuntime = cellRuntimeAtom(cellId);++ return atom((get) => {+ const data = get(cellRuntime);+if (!data) {return undefined;}- // Must be errored and idle- if (data.status !== "idle") {++ if (data.status === "queued" || data.status === "running") {return undefined;}++ const tracebackInfo: TracebackInfo[] = [];++ // Runtime errors (ZeroDivisionError, etc.)const outputs = data.consoleOutputs;- // console.warn(notebook);- if (!outputs || outputs.length === 0) {- return undefined;+ if (outputs && outputs.length > 0) {+ const firstTraceback = outputs.find(+ (output) => output.mimetype === "application/vnd.marimo+traceback",+ );+ if (firstTraceback) {+ const traceback = firstTraceback.data as string;+ tracebackInfo.push(...extractAllTracebackInfo(traceback));+ }}- const firstTraceback = outputs.find(- (output) => output.mimetype === "application/vnd.marimo+traceback",- );- if (!firstTraceback) {- return undefined;+ // Syntax errors+ const output = data.output;+ if (output?.mimetype === "application/vnd.marimo+error") {+ const errors = output.data;+ if (Array.isArray(errors)) {+ for (const error of errors) {+ if (error.type === "syntax" && error.lineno != null) {+ tracebackInfo.push({+ kind: "cell",+ cellId: cellId,+ lineNumber: error.lineno,+ });+ }+ if (error.type === "import-star" && error.lineno != null) {+ tracebackInfo.push({+ kind: "cell",+ cellId: cellId,+ lineNumber: error.lineno,+ });+ }+ }+ }}- const traceback = firstTraceback.data;- return traceback as string;- });- return atom((get) => {- const traceback = get(tracebackStringAtom);- if (!traceback) {- return undefined;- }- return extractAllTracebackInfo(traceback);+ return tracebackInfo.length > 0 ? tracebackInfo : undefined;});}@@ -1743,4 +1762,5 @@ export const exportedForTesting = {cellDataAtom,cellRuntimeAtom,cellHandleAtom,+ createTracebackInfoAtom,};diff --git a/marimo/_messaging/errors.py b/marimo/_messaging/errors.pyindex f8f44b5fa1..7d2904170c 100644--- a/marimo/_messaging/errors.py+++ b/marimo/_messaging/errors.py@@ -33,6 +33,7 @@ class MultipleDefinitionError(msgspec.Struct, tag="multiple-defs"):class ImportStarError(msgspec.Struct, tag="import-star"):msg: str+ lineno: Optional[int] = Nonedef describe(self) -> str:return self.msg@@ -72,6 +73,7 @@ class MarimoExceptionRaisedError(msgspec.Struct, tag="exception"):class MarimoSyntaxError(msgspec.Struct, tag="syntax"):msg: str+ lineno: Optional[int] = Nonedef describe(self) -> str:return self.msgdiff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.pyindex 09fd1f3cc4..c2537fde86 100644--- a/marimo/_runtime/runtime.py+++ b/marimo/_runtime/runtime.py@@ -876,10 +876,14 @@ class Kernel:syntax_error[0] = syntax_error[0][syntax_error[0].find("line") :]++ lineno = getattr(e, "lineno", None)if isinstance(e, ImportStarError):- error = MarimoImportStarError(msg=str(e))+ error = MarimoImportStarError(msg=str(e), lineno=lineno)else:- error = MarimoSyntaxError(msg="\n".join(syntax_error))+ error = MarimoSyntaxError(+ msg="\n".join(syntax_error), lineno=lineno+ )else:tmpio = io.StringIO()traceback.print_exc(file=tmpio)diff --git a/packages/openapi/api.yaml b/packages/openapi/api.yamlindex 545cee42b6..1e765aabe0 100644--- a/packages/openapi/api.yaml+++ b/packages/openapi/api.yaml@@ -1708,6 +1708,11 @@ components:type: objectImportStarError:properties:+ lineno:+ anyOf:+ - type: integer+ - type: 'null'+ default: nullmsg:type: stringtype:@@ -2383,6 +2388,11 @@ components:type: objectMarimoSyntaxError:properties:+ lineno:+ anyOf:+ - type: integer+ - type: 'null'+ default: nullmsg:type: stringtype:diff --git a/packages/openapi/src/api.ts b/packages/openapi/src/api.tsindex a6889753ae..ae91fd7b91 100644--- a/packages/openapi/src/api.ts+++ b/packages/openapi/src/api.ts@@ -3718,6 +3718,8 @@ export interface components {};/** ImportStarError */ImportStarError: {+ /** @default null */+ lineno?: number | null;msg: string;/** @enum {unknown} */type: "import-star";@@ -4057,6 +4059,8 @@ export interface components {};/** MarimoSyntaxError */MarimoSyntaxError: {+ /** @default null */+ lineno?: number | null;msg: string;/** @enum {unknown} */type: "syntax";diff --git a/tests/_messaging/test_cell_output.py b/tests/_messaging/test_cell_output.pyindex dffddb30f3..f304760ac4 100644--- a/tests/_messaging/test_cell_output.py+++ b/tests/_messaging/test_cell_output.py@@ -66,6 +66,7 @@ def test_serialize_cell_output():{"msg": "Syntax Error!","type": "syntax",+ "lineno": None,}],"timestamp": 0,diff --git a/tests/_messaging/test_messaging_errors.py b/tests/_messaging/test_messaging_errors.pyindex ca3633339a..8818a4ae46 100644--- a/tests/_messaging/test_messaging_errors.py+++ b/tests/_messaging/test_messaging_errors.py@@ -54,6 +54,17 @@ class TestErrorClasses:assert serialized["type"] == "import-star"assert error.describe() == "Cannot use import * in this context"+ def test_import_star_error_with_lineno(self) -> None:+ error = ImportStarError(+ msg="Cannot use import * in this context", lineno=3+ )++ # Test properties+ serialized = msgspec.to_builtins(error)+ assert serialized["type"] == "import-star"+ assert error.describe() == "Cannot use import * in this context"+ assert error.lineno == 3+def test_marimo_interruption_error(self) -> None:error = MarimoInterruptionError()@@ -104,12 +115,42 @@ class TestErrorClasses:assert error.exception_type == "ValueError"def test_marimo_syntax_error(self) -> None:+ error = MarimoSyntaxError(msg="Invalid syntax", lineno=5)++ # Test properties+ serialized = msgspec.to_builtins(error)+ assert serialized["type"] == "syntax"+ assert error.describe() == "Invalid syntax"+ assert error.lineno == 5++ def test_marimo_syntax_error_without_lineno(self) -> None:error = MarimoSyntaxError(msg="Invalid syntax")# Test propertiesserialized = msgspec.to_builtins(error)assert serialized["type"] == "syntax"assert error.describe() == "Invalid syntax"+ assert error.lineno is None++ def test_marimo_syntax_error_with_line_zero(self) -> None:+ # Edge case: line 0 should be treated as valid+ error = MarimoSyntaxError(msg="Invalid syntax", lineno=0)++ # Test properties+ serialized = msgspec.to_builtins(error)+ assert serialized["type"] == "syntax"+ assert error.describe() == "Invalid syntax"+ assert error.lineno == 0++ def test_marimo_syntax_error_with_large_lineno(self) -> None:+ # Test with larger line numbers+ error = MarimoSyntaxError(msg="Invalid syntax", lineno=100)++ # Test properties+ serialized = msgspec.to_builtins(error)+ assert serialized["type"] == "syntax"+ assert error.describe() == "Invalid syntax"+ assert error.lineno == 100def test_unknown_error(self) -> None:error = UnknownError(msg="Something went wrong")diff --git a/tests/_runtime/test_runtime.py b/tests/_runtime/test_runtime.pyindex 576fc3ef16..f3b61c1884 100644--- a/tests/_runtime/test_runtime.py+++ b/tests/_runtime/test_runtime.py@@ -865,8 +865,45 @@ except NameError:)assert set(k.errors.keys()) == {"1"}assert isinstance(k.errors["1"][0], MarimoSyntaxError)+ assert k.errors["1"][0].lineno is not None+ assert k.errors["1"][0].lineno == 1assert not cell.stale+ async def test_syntax_error_multiline_code(+ self, lazy_kernel: Kernel+ ) -> None:+ """Test that syntax errors on different lines report correct line numbers"""+ k = lazy_kernel++ # Syntax error on line 3 of multiline code+ await k.run(+ [+ ExecutionRequest(+ cell_id="0", code="x = 1\ny = 2\nz ^ !\nw = 4"+ ),+ ]+ )+ assert set(k.errors.keys()) == {"0"}+ assert isinstance(k.errors["0"][0], MarimoSyntaxError)+ assert k.errors["0"][0].lineno is not None+ assert k.errors["0"][0].lineno == 3++ async def test_syntax_error_line_zero(self, lazy_kernel: Kernel) -> None:+ """Test edge case where syntax error might be on line 0"""+ k = lazy_kernel++ # Single line syntax error (should be line 1)+ await k.run(+ [+ ExecutionRequest(cell_id="0", code="!"),+ ]+ )+ assert set(k.errors.keys()) == {"0"}+ assert isinstance(k.errors["0"][0], MarimoSyntaxError)+ assert k.errors["0"][0].lineno is not None+ # Python reports line numbers starting from 1+ assert k.errors["0"][0].lineno >= 1+async def test_child_of_errored_cell_with_error_not_stale(self,any_kernel: Kernel,