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
experimental: tracing panel (#3168)
Shahmir Varqhaf332b7064112
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 98cf8d4135..a4fecd8f4b 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -95,6 +95,7 @@ NODE_OPTIONS=--max_old_space_size=8192 NODE_ENV=development make fe -B| `py` | Setup | Editable python install; only need to run once || `install-all` | Setup | Install everything; takes a long time due to editable install || `fe` | Build | Package frontend into `marimo/` |+| `fe-codegen` | Build | Build [api specification](./development_docs/openapi.md) || `wheel` | Build | Build wheel || `check` | Test | Run all checks || `check-test` | Test | Run all checks and tests |diff --git a/development_docs/openapi.md b/development_docs/openapi.mdindex 63c1f4fae2..f576e0b566 100644--- a/development_docs/openapi.md+++ b/development_docs/openapi.md@@ -24,3 +24,10 @@ marimo development openapi | openapi-spec-validator -```bashmake fe-codegen```++You will then need to reinstall the package in `/frontend`:++```bash+cd frontend+pnpm update @marimo-team/marimo-api+```\ No newline at end of filediff --git a/frontend/src/components/buttons/clear-button.tsx b/frontend/src/components/buttons/clear-button.tsxnew file mode 100644index 0000000000..28e9bd1629--- /dev/null+++ b/frontend/src/components/buttons/clear-button.tsx@@ -0,0 +1,23 @@+/* Copyright 2024 Marimo. All rights reserved. */++import { cn } from "@/utils/cn";++interface ClearButtonProps {+ className?: string;+ dataTestId?: string;+ onClick: () => void;+}++export const ClearButton: React.FC<ClearButtonProps> = (props) => (+ <button+ type="button"+ data-testid={props.dataTestId}+ className={cn(+ "text-xs font-semibold text-accent-foreground",+ props.className,+ )}+ onClick={props.onClick}+ >+ Clear+ </button>+);diff --git a/frontend/src/components/editor/cell/CellStatus.tsx b/frontend/src/components/editor/cell/CellStatus.tsxindex ceeee2cb48..b748937d14 100644--- a/frontend/src/components/editor/cell/CellStatus.tsx+++ b/frontend/src/components/editor/cell/CellStatus.tsx@@ -321,7 +321,7 @@ export const CellStatusComponent: React.FC<CellStatusComponentProps> = ({return null;};-const ElapsedTime = (props: { elapsedTime: string }) => {+export const ElapsedTime = (props: { elapsedTime: string }) => {return (<span className="tracking-wide font-semibold">{props.elapsedTime}</span>);@@ -346,7 +346,7 @@ const LastRanTime = (props: { lastRanTime: number }) => {);};-function formatElapsedTime(elapsedTime: number | null) {+export function formatElapsedTime(elapsedTime: number | null) {if (elapsedTime === null) {return "";}diff --git a/frontend/src/components/editor/chrome/panels/logs-panel.tsx b/frontend/src/components/editor/chrome/panels/logs-panel.tsxindex dd100f838e..40be0b1bdf 100644--- a/frontend/src/components/editor/chrome/panels/logs-panel.tsx+++ b/frontend/src/components/editor/chrome/panels/logs-panel.tsx@@ -6,6 +6,7 @@ import React from "react";import { FileTextIcon } from "lucide-react";import { CellLink } from "../../links/cell-link";import { PanelEmptyState } from "./empty-state";+import { ClearButton } from "@/components/buttons/clear-button";interface Props {className?: string;@@ -35,13 +36,7 @@ export const LogsPanel: React.FC = () => {return (<><div className="flex flex-row justify-end px-2 py-1">- <button- data-testid="clear-logs-button"- className="text-xs font-semibold text-accent-foreground"- onClick={clearLogs}- >- Clear- </button>+ <ClearButton dataTestId="clear-logs-button" onClick={clearLogs} /></div><div className="overflow-auto flex-1"><LogViewer logs={logs} className="min-w-[300px]" />@@ -84,7 +79,9 @@ function formatLog(log: CellLog) {return (<>- <span className="flex-shrink-0 text-[var(--gray-10)]">[{timestamp}]</span>+ <span className="flex-shrink-0 text-[var(--gray-10)] dark:text-[var(--gray-11)]">+ [{timestamp}]+ </span><span className={cn("flex-shrink-0", color)}>{level}</span><span className="flex-shrink-0 text-[var(--gray-10)]">(<CellLink cellId={log.cellId} />)diff --git a/frontend/src/components/editor/chrome/panels/tracing-panel.tsx b/frontend/src/components/editor/chrome/panels/tracing-panel.tsxnew file mode 100644index 0000000000..a80d3284c9--- /dev/null+++ b/frontend/src/components/editor/chrome/panels/tracing-panel.tsx@@ -0,0 +1,7 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { Tracing } from "@/components/tracing/tracing";+import React from "react";++export const TracingPanel: React.FC = () => {+ return <Tracing />;+};diff --git a/frontend/src/components/editor/chrome/types.ts b/frontend/src/components/editor/chrome/types.tsindex 387e54edda..42760482b4 100644--- a/frontend/src/components/editor/chrome/types.ts+++ b/frontend/src/components/editor/chrome/types.ts@@ -14,6 +14,7 @@ import {NotebookPenIcon,BoxIcon,BotMessageSquareIcon,+ ActivityIcon,} from "lucide-react";export type PanelType =@@ -22,6 +23,7 @@ export type PanelType =| "variables"| "outline"| "dependencies"+ | "tracing"| "packages"| "documentation"| "snippets"@@ -94,6 +96,13 @@ export const PANELS: PanelDescriptor[] = [tooltip: "Notebook logs",position: "sidebar",},+ {+ type: "tracing",+ Icon: ActivityIcon,+ tooltip: "Tracing",+ position: "sidebar",+ hidden: !getFeatureFlag("tracing"),+ },{type: "snippets",Icon: SquareDashedBottomCodeIcon,diff --git a/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx b/frontend/src/components/editor/chrome/wrapper/app-chrome.tsxindex b931b14867..40d07bac76 100644--- a/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx+++ b/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx@@ -30,6 +30,7 @@ import { IfCapability } from "@/core/config/if-capability";import { PackagesPanel } from "../panels/packages-panel";import { ChatPanel } from "@/components/chat/chat-panel";import { TooltipProvider } from "@radix-ui/react-tooltip";+import { TracingPanel } from "../panels/tracing-panel";const LazyTerminal = React.lazy(() => import("@/components/terminal/terminal"));@@ -153,6 +154,7 @@ export const AppChrome: React.FC<PropsWithChildren> = ({ children }) => {{selectedPanel === "scratchpad" && <ScratchpadPanel />}{selectedPanel === "chat" && <ChatPanel />}{selectedPanel === "logs" && <LogsPanel />}+ {selectedPanel === "tracing" && <TracingPanel />}</TooltipProvider></div></Suspense>diff --git a/frontend/src/components/tracing/tracing-spec.ts b/frontend/src/components/tracing/tracing-spec.tsnew file mode 100644index 0000000000..6e23df7c5b--- /dev/null+++ b/frontend/src/components/tracing/tracing-spec.ts@@ -0,0 +1,106 @@+/* Copyright 2024 Marimo. All rights reserved. */+import type { CellId } from "@/core/cells/ids";+import type { CellRun } from "@/core/cells/runs";+import type { ResolvedTheme } from "@/theme/useTheme";+import type { TopLevelSpec } from "vega-lite";++export const REACT_HOVERED_CELLID = "hoveredCellId";+export const VEGA_HOVER_SIGNAL = "cellHover";++export type ChartPosition = "sideBySide" | "above";+export interface ChartValues {+ cell: CellId;+ cellNum: number;+ startTimestamp: string;+ endTimestamp: string;+ elapsedTime: string;+ status: CellRun["status"];+}++const cellNumField = "cellNum" satisfies keyof ChartValues;+const cellField = "cell" satisfies keyof ChartValues;+const startTimestampField = "startTimestamp" satisfies keyof ChartValues;+const endTimestampField = "endTimestamp" satisfies keyof ChartValues;+const statusField = "status" satisfies keyof ChartValues;++export function createGanttBaseSpec(+ chartValues: ChartValues[],+ hiddenInputElementId: string,+ chartPosition: ChartPosition,+ theme: ResolvedTheme,+): TopLevelSpec {+ return {+ $schema: "https://vega.github.io/schema/vega-lite/v5.json",+ background: theme === "dark" ? "black" : undefined,+ mark: {+ type: "bar",+ cornerRadius: 2,+ },+ params: [+ {+ name: REACT_HOVERED_CELLID,+ bind: { element: `#${hiddenInputElementId}` },+ },+ {+ name: VEGA_HOVER_SIGNAL,+ select: {+ type: "point",+ on: "mouseover",+ fields: [cellField],+ clear: "mouseout",+ },+ },+ ],+ height: { step: 23 },+ encoding: {+ y: {+ field: cellNumField,+ scale: { paddingInner: 0.2 },+ sort: { field: cellNumField },+ title: "cell",+ axis: chartPosition === "sideBySide" ? null : undefined,+ },+ x: {+ field: startTimestampField,+ type: "temporal",+ axis: { orient: "top", title: null },+ },+ x2: {+ field: endTimestampField,+ type: "temporal",+ },+ tooltip: [+ {+ field: startTimestampField,+ type: "temporal",+ timeUnit: "dayhoursminutesseconds",+ title: "Start",+ },+ {+ field: endTimestampField,+ type: "temporal",+ timeUnit: "dayhoursminutesseconds",+ title: "End",+ },+ ],+ size: {+ value: {+ expr: `${REACT_HOVERED_CELLID} == toString(datum.cell) ? 19.5 : 18`,+ },+ },+ color: {+ field: statusField,+ scale: { domain: ["success", "error"], range: ["#37BE5F", "red"] },+ legend: null,+ },+ },+ data: {+ values: chartValues,+ },+ config: {+ view: {+ stroke: "transparent",+ },+ },+ };+}diff --git a/frontend/src/components/tracing/tracing.test.tsx b/frontend/src/components/tracing/tracing.test.tsxnew file mode 100644index 0000000000..bb9e73828f--- /dev/null+++ b/frontend/src/components/tracing/tracing.test.tsx@@ -0,0 +1,66 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { describe, it, expect, beforeAll, afterAll, vi } from "vitest";+import { formatChartTime } from "./tracing";++describe("formatChartTime", () => {+ beforeAll(() => {+ // Mock Date to always use UTC+ vi.spyOn(global.Date.prototype, "getFullYear").mockImplementation(function (+ this: Date,+ ) {+ return this.getUTCFullYear();+ });+ vi.spyOn(global.Date.prototype, "getMonth").mockImplementation(function (+ this: Date,+ ) {+ return this.getUTCMonth();+ });+ vi.spyOn(global.Date.prototype, "getDate").mockImplementation(function (+ this: Date,+ ) {+ return this.getUTCDate();+ });+ vi.spyOn(global.Date.prototype, "getHours").mockImplementation(function (+ this: Date,+ ) {+ return this.getUTCHours();+ });+ vi.spyOn(global.Date.prototype, "getMinutes").mockImplementation(function (+ this: Date,+ ) {+ return this.getUTCMinutes();+ });+ vi.spyOn(global.Date.prototype, "getSeconds").mockImplementation(function (+ this: Date,+ ) {+ return this.getUTCSeconds();+ });+ vi.spyOn(global.Date.prototype, "getMilliseconds").mockImplementation(+ function (this: Date) {+ return this.getUTCMilliseconds();+ },+ );+ });++ afterAll(() => {+ vi.restoreAllMocks();+ });++ it("should handle a timestamp with milliseconds correctly", () => {+ const timestamp = 1_704_067_200.123;+ const formattedTime = formatChartTime(timestamp);+ expect(formattedTime).toBe("2024-01-01 00:00:00.123");+ });++ it("should handle a timestamp at the start of the year correctly", () => {+ const timestamp = 1_704_067_200;+ const formattedTime = formatChartTime(timestamp);+ expect(formattedTime).toBe("2024-01-01 00:00:00.000");+ });++ it("should handle a timestamp at the end of the year correctly", () => {+ const timestamp = 1_704_067_199;+ const formattedTime = formatChartTime(timestamp);+ expect(formattedTime).toBe("2023-12-31 23:59:59.000");+ });+});diff --git a/frontend/src/components/tracing/tracing.tsx b/frontend/src/components/tracing/tracing.tsxnew file mode 100644index 0000000000..5d36edbd5a--- /dev/null+++ b/frontend/src/components/tracing/tracing.tsx@@ -0,0 +1,349 @@+/* Copyright 2024 Marimo. All rights reserved. */+import React, { useRef, useState } from "react";+import type { CellId } from "@/core/cells/ids";+import { ElapsedTime, formatElapsedTime } from "../editor/cell/CellStatus";+import { Tooltip } from "@/components/ui/tooltip";+import { compile } from "vega-lite";+import {+ ChevronRight,+ ChevronDown,+ ActivityIcon,+ CirclePlayIcon,+ CircleCheck,+ CircleEllipsis,+ CircleX,+} from "lucide-react";+import type { SignalListeners, VisualizationSpec } from "react-vega";+import {+ type RunId,+ runsAtom,+ type CellRun,+ type Run,+ useRunsActions,+} from "@/core/cells/runs";+import { useAtomValue } from "jotai";+import { CellLink } from "../editor/links/cell-link";+import { formatLogTimestamp } from "@/core/cells/logs";+import { useCellIds } from "@/core/cells/cells";+import {+ type ChartPosition,+ type ChartValues,+ createGanttBaseSpec,+ VEGA_HOVER_SIGNAL,+} from "./tracing-spec";+import { ClearButton } from "../buttons/clear-button";+import { cn } from "@/utils/cn";+import { PanelEmptyState } from "../editor/chrome/panels/empty-state";+import { type ResolvedTheme, useTheme } from "@/theme/useTheme";++export const Tracing: React.FC = () => {+ const { runIds: newestToOldestRunIds, runMap } = useAtomValue(runsAtom);+ const { clearRuns } = useRunsActions();++ const { theme } = useTheme();+ const [chartPosition, setChartPosition] = useState<ChartPosition>("above");++ const toggleChartPosition = () => {+ if (chartPosition === "above") {+ setChartPosition("sideBySide");+ } else {+ setChartPosition("above");+ }+ };++ if (newestToOldestRunIds.length === 0) {+ return (+ <PanelEmptyState+ title="No traces"+ description={<span>Cells that have ran will appear here.</span>}+ icon={<ActivityIcon />}+ />+ );+ }++ return (+ <div className="py-1 px-2 overflow-y-scroll">+ <div className="flex flex-row justify-end gap-3">+ <div className="flex flex-row gap-1 items-center">+ <label htmlFor="chartPosition" className="text-xs">+ Inline chart+ </label>+ <input+ type="checkbox"+ name="chartPosition"+ id="chartPosition"+ onClick={toggleChartPosition}+ defaultChecked={chartPosition === "sideBySide"}+ className="h-3 cursor-pointer"+ />+ </div>++ <ClearButton dataTestId="clear-traces-button" onClick={clearRuns} />+ </div>++ <div className="flex flex-col gap-3">+ {newestToOldestRunIds.map((runId: RunId) => {+ const run = runMap.get(runId);+ if (run) {+ return (+ <TraceBlock+ key={run.runId}+ run={run}+ chartPosition={chartPosition}+ theme={theme}+ />+ );+ }+ })}+ </div>+ </div>+ );+};++const LazyVega = React.lazy(() =>+ import("react-vega").then((m) => ({ default: m.Vega })),+);+interface ChartProps {+ className?: string;+ width: number;+ height: number;+ vegaSpec: VisualizationSpec;+ signalListeners: SignalListeners;+ theme: ResolvedTheme;+}++const Chart: React.FC<ChartProps> = (props: ChartProps) => {+ return (+ <div className={props.className}>+ <LazyVega+ spec={props.vegaSpec}+ theme={props.theme === "dark" ? "dark" : undefined}+ width={props.width}+ height={props.height}+ signalListeners={props.signalListeners}+ actions={false}+ />+ </div>+ );+};++interface VegaHoverCellSignal {+ cell: string[];+ vlPoint: unknown;+}++const TraceBlock: React.FC<{+ run: Run;+ chartPosition: ChartPosition;+ theme: ResolvedTheme;+}> = ({ run, chartPosition, theme }) => {+ const [collapsed, setCollapsed] = useState(false);+ const [hoveredCellId, setHoveredCellId] = useState<CellId | null>();++ // To send signals to Vega from React, we bind a hidden input element+ const hiddenInputRef = useRef<HTMLInputElement>(null);+ const dispatchHoverEvent = (cellId: CellId | null) => {+ // dispatch input event to trigger vega's param to update+ if (hiddenInputRef.current) {+ hiddenInputRef.current.value = String(cellId);+ hiddenInputRef.current.dispatchEvent(+ new Event("input", { bubbles: true }),+ );+ }+ };++ const handleVegaSignal = {+ [VEGA_HOVER_SIGNAL]: (name: string, value: unknown) => {+ const signalValue = value as VegaHoverCellSignal;+ const hoveredCell = signalValue.cell?.[0] as CellId | undefined;+ setHoveredCellId(hoveredCell ?? null);+ },+ };++ const Icon = collapsed ? ChevronRight : ChevronDown;+ const chevron = <Icon height={16} className="inline" />;++ const TraceTitle = (+ <span+ className="text-sm cursor-pointer"+ onClick={() => setCollapsed(!collapsed)}+ >+ Run - {formatLogTimestamp(run.runStartTime)}+ {chevron}+ </span>+ );++ const cellIds = useCellIds();++ const chartValues: ChartValues[] = run.cellRuns.map((cellRun) => {+ const elapsedTime = cellRun.elapsedTime ?? 0;+ return {+ cell: cellRun.cellId,+ cellNum: cellIds.inOrderIds.indexOf(cellRun.cellId),+ startTimestamp: formatChartTime(cellRun.startTime),+ endTimestamp: formatChartTime(cellRun.startTime + elapsedTime),+ elapsedTime: formatElapsedTime(elapsedTime * 1000),+ status: cellRun.status,+ };+ });++ const hiddenInputElementId = `hiddenInputElement-${run.runId}`;+ const vegaSpec = compile(+ createGanttBaseSpec(+ chartValues,+ hiddenInputElementId,+ chartPosition,+ theme,+ ),+ ).spec;++ const TraceRows = (+ <div className="text-xs mt-0.5 ml-3 flex flex-col gap-0.5">+ <input+ type="text"+ id={hiddenInputElementId}+ defaultValue={hoveredCellId || ""}+ hidden={true}+ ref={hiddenInputRef}+ />+ {run.cellRuns.map((cellRun) => (+ <TraceRow+ key={cellRun.cellId}+ cellRun={cellRun}+ hovered={cellRun.cellId === hoveredCellId}+ dispatchHoverEvent={dispatchHoverEvent}+ />+ ))}+ </div>+ );++ if (chartPosition === "above") {+ return (+ <div key={run.runId} className="flex flex-col">+ <pre className="font-mono font-semibold">+ {TraceTitle}+ {!collapsed && (+ <Chart+ vegaSpec={vegaSpec}+ width={320}+ height={120}+ signalListeners={handleVegaSignal}+ theme={theme}+ />+ )}+ {!collapsed && TraceRows}+ </pre>+ </div>+ );+ }++ return (+ <div key={run.runId} className="flex flex-row">+ <pre className="font-mono font-semibold">+ {TraceTitle}+ {!collapsed && TraceRows}+ </pre>+ {!collapsed && (+ <Chart+ className="-mt-0.5"+ vegaSpec={vegaSpec}+ width={240}+ height={100}+ signalListeners={handleVegaSignal}+ theme={theme}+ />+ )}+ </div>+ );+};++const StatusIcons: Record<CellRun["status"], JSX.Element> = {+ success: <CircleCheck color="green" size={14} />,+ running: <CirclePlayIcon color="var(--blue-10)" size={14} />,+ error: <CircleX color="red" size={14} />,+ queued: <CircleEllipsis color="grey" size={14} />,+};++interface TraceRowProps {+ cellRun: CellRun;+ hovered: boolean;+ dispatchHoverEvent: (cellId: CellId | null) => void;+}++const TraceRow: React.FC<TraceRowProps> = ({+ cellRun,+ hovered,+ dispatchHoverEvent,+}: TraceRowProps) => {+ const elapsedTimeStr = cellRun.elapsedTime+ ? formatElapsedTime(cellRun.elapsedTime * 1000)+ : "-";++ const elapsedTimeTooltip = cellRun.elapsedTime ? (+ <span>+ This cell took <ElapsedTime elapsedTime={elapsedTimeStr} /> to run+ </span>+ ) : (+ <span>This cell has not been run</span>+ );++ const handleMouseEnter = () => {+ dispatchHoverEvent(cellRun.cellId);+ };++ const handleMouseLeave = () => {+ dispatchHoverEvent(null);+ };++ return (+ <div+ className={cn(+ "flex flex-row gap-2 py-1 px-1 opacity-70 hover:bg-[var(--gray-3)] hover:opacity-100",+ hovered && "bg-[var(--gray-3)] opacity-100",+ )}+ onMouseEnter={handleMouseEnter}+ onMouseLeave={handleMouseLeave}+ >+ <span className="text-[var(--gray-10)] dark:text-[var(--gray-11)]">+ [{formatLogTimestamp(cellRun.startTime)}]+ </span>+ <span className="text-[var(--gray-10)] w-16">+ (<CellLink cellId={cellRun.cellId} />)+ </span>+ <span className="w-40 truncate -ml-1">{cellRun.code}</span>++ <div className="flex flex-row gap-1 w-16 justify-end -ml-2">+ <Tooltip content={elapsedTimeTooltip}>+ <span className="text-[var(--gray-10)] dark:text-[var(--gray-11)]">+ {elapsedTimeStr}+ </span>+ </Tooltip>++ <Tooltip content={cellRun.status}>+ {StatusIcons[cellRun.status]}+ </Tooltip>+ </div>+ </div>+ );+};++export function formatChartTime(timestamp: number): string {+ try {+ // Multiply by 1000 to convert seconds to milliseconds+ const date = new Date(timestamp * 1000);++ const year = date.getFullYear();+ const month = String(date.getMonth() + 1).padStart(2, "0"); // getMonth() is 0-indexed+ const day = String(date.getDate()).padStart(2, "0");++ const hours = String(date.getHours()).padStart(2, "0");+ const minutes = String(date.getMinutes()).padStart(2, "0");+ const seconds = String(date.getSeconds()).padStart(2, "0");++ const milliseconds = String(date.getMilliseconds()).padStart(3, "0");++ return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}.${milliseconds}`;+ } catch {+ return "";+ }+}diff --git a/frontend/src/core/cells/__tests__/runs.test.ts b/frontend/src/core/cells/__tests__/runs.test.tsnew file mode 100644index 0000000000..01874ddf01--- /dev/null+++ b/frontend/src/core/cells/__tests__/runs.test.ts@@ -0,0 +1,321 @@+/* Copyright 2024 Marimo. All rights reserved. */++import { describe, expect, it, beforeEach } from "vitest";+import {+ exportedForTesting,+ MAX_CODE_LENGTH,+ MAX_RUNS,+ type RunId,+ type RunsState,+} from "../runs";+import type { CellMessage } from "@/core/kernel/messages";++describe("RunsState Reducer", () => {+ const { reducer, initialState } = exportedForTesting;++ let state: RunsState;++ const runId = "run1" as RunId;+ const cellId = "cell1";+ const timestamp = Date.now();+ const code = "print('Hello World')";++ const cellOperation: CellMessage = {+ run_id: runId,+ cell_id: cellId,+ timestamp,+ status: "queued",+ };++ function addQueuedCell(): RunsState {+ return reducer(state, {+ type: "addCellOperation",+ payload: {+ cellOperation: cellOperation,+ code: "print('Hello World')",+ },+ });+ }++ beforeEach(() => {+ state = initialState();+ });++ it("should initialize with an empty state", () => {+ expect(state.runIds).toEqual([]);+ expect(state.runMap.size).toBe(0);+ });++ it("should add a cell operation to a new run", () => {+ const nextState = addQueuedCell();++ expect(nextState.runIds).toEqual([runId]);+ expect(nextState.runMap.get(runId)).toEqual({+ runId,+ runStartTime: timestamp,+ cellRuns: [+ {+ cellId,+ code: code.slice(0, MAX_CODE_LENGTH),+ elapsedTime: 0,+ startTime: timestamp,+ status: "queued",+ },+ ],+ });+ });++ it("should clear all runs", () => {+ const intermediateState = addQueuedCell();++ const clearedState = reducer(intermediateState, {+ type: "clearRuns",+ payload: undefined,+ });++ expect(clearedState.runIds).toEqual([]);+ expect(clearedState.runMap.size).toBe(0);+ });++ it("should remove a specific run by ID", () => {+ const runId1 = "run1" as RunId;+ const runId2 = "run2" as RunId;+ const timestamp = Date.now();++ let intermediateState = addQueuedCell();++ intermediateState = reducer(intermediateState, {+ type: "addCellOperation",+ payload: {+ cellOperation: {+ run_id: runId2,+ cell_id: "cell2",+ timestamp,+ status: "queued",+ },+ code: "console.log('Run 2');",+ },+ });++ const nextState = reducer(intermediateState, {+ type: "removeRun",+ payload: runId1,+ });++ expect(nextState.runIds).toEqual([runId2]);+ expect(nextState.runMap.has(runId1)).toBe(false);+ });++ it("should update an existing run with a new cell operation", () => {+ const state = addQueuedCell();++ const runStartTimestamp = timestamp + 1000;+ const updatedState = reducer(state, {+ type: "addCellOperation",+ payload: {+ cellOperation: {+ run_id: runId,+ cell_id: cellId,+ timestamp: timestamp + 1000,+ status: "running",+ },+ code: "console.log('Hello World');",+ },+ });++ expect(updatedState.runIds).toEqual([runId]);+ expect(updatedState.runMap.get(runId)?.cellRuns[0].status).toBe("running");+ expect(updatedState.runMap.get(runId)?.cellRuns[0].startTime).toBe(+ runStartTimestamp,+ );++ const successState = reducer(state, {+ type: "addCellOperation",+ payload: {+ cellOperation: {+ run_id: runId,+ cell_id: cellId,+ timestamp: runStartTimestamp + 5000,+ status: "success",+ },+ code: "console.log('Hello World');",+ },+ });++ expect(successState.runIds).toEqual([runId]);+ expect(successState.runMap.get(runId)?.cellRuns[0].status).toBe("success");+ expect(successState.runMap.get(runId)?.cellRuns[0].startTime).toBe(+ runStartTimestamp,+ );+ expect(successState.runMap.get(runId)?.cellRuns[0].elapsedTime).toBe(5000);+ });++ it("should limit the number of runs to MAX_RUNS", () => {+ for (let i = 1; i <= MAX_RUNS + 1; i++) {+ state = reducer(state, {+ type: "addCellOperation",+ payload: {+ cellOperation: {+ run_id: `run${i}`,+ cell_id: `cell${i}`,+ timestamp: timestamp,+ status: "queued",+ },+ code: "console.log('Hello World');",+ },+ });+ }++ expect(state.runIds.length).toBe(MAX_RUNS);+ expect(state.runMap.size).toBe(MAX_RUNS);++ // Oldest run should be removed+ expect(state.runIds).not.toContain("run1");+ expect(state.runMap.has("run1" as RunId)).toBe(false);+ });++ it("should truncate code to MAX_CODE_LENGTH", () => {+ const longCode = "a".repeat(MAX_CODE_LENGTH + 10);+ const truncatedCode = longCode.slice(0, MAX_CODE_LENGTH);++ const nextState = reducer(state, {+ type: "addCellOperation",+ payload: {+ cellOperation: {+ run_id: runId,+ cell_id: cellId,+ timestamp,+ status: "queued",+ },+ code: longCode,+ },+ });++ expect(nextState.runMap.get(runId)?.cellRuns[0].code).toBe(truncatedCode);+ });++ it("should update the run status to error when stderr occurs", () => {+ const state = addQueuedCell();++ const errorTimestamp = timestamp + 2000;+ const errorState = reducer(state, {+ type: "addCellOperation",+ payload: {+ cellOperation: {+ run_id: runId,+ cell_id: cellId,+ timestamp: errorTimestamp,+ status: "running",+ output: {+ channel: "stderr",+ text: "Error occurred",+ },+ },+ code: "console.log('Hello World');",+ },+ });++ expect(errorState.runIds).toEqual([runId]);+ expect(errorState.runMap.get(runId)?.cellRuns[0].status).toBe("error");+ expect(errorState.runMap.get(runId)?.cellRuns[0].elapsedTime).toBe(+ errorTimestamp - timestamp,+ );+ });++ it("should update the run status to error when marimo-error occurs", () => {+ const state = addQueuedCell();++ const errorTimestamp = timestamp + 2000;+ const errorState = reducer(state, {+ type: "addCellOperation",+ payload: {+ cellOperation: {+ run_id: runId,+ cell_id: cellId,+ timestamp: errorTimestamp,+ status: "running",+ output: {+ channel: "marimo-error",+ text: "Error occurred",+ },+ },+ code: "console.log('Hello World');",+ },+ });++ expect(errorState.runIds).toEqual([runId]);+ expect(errorState.runMap.get(runId)?.cellRuns[0].status).toBe("error");+ expect(errorState.runMap.get(runId)?.cellRuns[0].elapsedTime).toBe(+ errorTimestamp - timestamp,+ );+ });++ it("should maintain status as error when there was a previous error", () => {+ const erroredState = reducer(state, {+ type: "addCellOperation",+ payload: {+ cellOperation: {+ run_id: runId,+ cell_id: cellId,+ timestamp,+ output: {+ channel: "marimo-error",+ },+ },+ code: "console.log('Hello World');",+ },+ });++ const finalState = reducer(erroredState, {+ type: "addCellOperation",+ payload: {+ cellOperation: {+ run_id: runId,+ cell_id: cellId,+ timestamp: timestamp + 2000,+ status: "running", // shouldn't happen+ },+ code: "console.log('Hello World');",+ },+ });++ expect(finalState.runIds).toEqual([runId]);+ expect(finalState.runMap.get(runId)?.cellRuns[0].status).toBe("error");+ });++ it("should order runs from newest to oldest", () => {+ const runId2 = "run2" as RunId;+ const runId3 = "run3" as RunId;+ const timestamp = Date.now();++ let intermediateState = addQueuedCell();++ intermediateState = reducer(intermediateState, {+ type: "addCellOperation",+ payload: {+ cellOperation: {+ run_id: runId2,+ cell_id: "cell2",+ timestamp: timestamp + 1000,+ status: "queued",+ },+ code: "console.log('Run 2');",+ },+ });++ const finalState = reducer(intermediateState, {+ type: "addCellOperation",+ payload: {+ cellOperation: {+ run_id: runId3,+ cell_id: "cell3",+ timestamp: timestamp + 2000,+ status: "queued",+ },+ code: "console.log('Run 3');",+ },+ });++ expect(finalState.runIds).toEqual([runId3, runId2, runId]);+ });+});diff --git a/frontend/src/core/cells/runs.ts b/frontend/src/core/cells/runs.tsnew file mode 100644index 0000000000..861b37a3d0--- /dev/null+++ b/frontend/src/core/cells/runs.ts@@ -0,0 +1,170 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { createReducerAndAtoms } from "@/utils/createReducer";+import type { CellMessage } from "../kernel/messages";+import type { TypedString } from "@/utils/typed";+import type { CellId } from "./ids";+export type RunId = TypedString<"RunId">;++export interface CellRun {+ cellId: CellId;+ code: string;+ elapsedTime?: number;+ startTime: number;+ status: "success" | "error" | "queued" | "running";+}++export interface Run {+ runId: RunId;+ cellRuns: CellRun[];+ runStartTime: number;+}++export interface RunsState {+ runIds: RunId[];+ runMap: Map<RunId, Run>;+}++function initialState(): RunsState {+ return {+ runIds: [],+ runMap: new Map(),+ };+}++export const MAX_RUNS = 20;+export const MAX_CODE_LENGTH = 200;++const {+ reducer,+ createActions,+ valueAtom: runsAtom,+ useActions: useRunsActions,+} = createReducerAndAtoms(initialState, {+ addCellOperation: (+ state: RunsState,+ opts: { cellOperation: CellMessage; code: string },+ ): RunsState => {+ const { cellOperation, code } = opts;+ const runId = cellOperation.run_id as RunId | undefined;+ if (!runId) {+ return state;+ }+ let runIds: RunId[];++ let run = state.runMap.get(runId);+ if (run) {+ runIds = state.runIds;+ } else {+ run = {+ runId: runId,+ cellRuns: [],+ runStartTime: cellOperation.timestamp,+ };++ runIds = [runId, ...state.runIds];+ if (runIds.length > MAX_RUNS) {+ const oldestRunId = runIds.pop();+ if (oldestRunId) {+ state.runMap.delete(oldestRunId);+ }+ }+ }++ // We determine if the cell operation errored by looking at the output+ const erroredOutput =+ cellOperation.output &&+ (cellOperation.output.channel === "marimo-error" ||+ cellOperation.output.channel === "stderr");++ const nextRuns: CellRun[] = [];+ let found = false;+ for (const existingCellRun of run.cellRuns) {+ if (existingCellRun.cellId === cellOperation.cell_id) {+ const hasErroredPreviously = existingCellRun.status === "error";+ let status: CellRun["status"];+ let startTime = existingCellRun.startTime;++ if (hasErroredPreviously || erroredOutput) {+ status = "error";+ } else if (cellOperation.status === "queued") {+ status = "queued";+ } else if (cellOperation.status === "running") {+ status = "running";+ startTime = cellOperation.timestamp;+ } else {+ status = "success";+ }++ let elapsedTime: number | undefined = undefined;+ if (status === "success" || status === "error") {+ elapsedTime = cellOperation.timestamp - existingCellRun.startTime;+ }++ nextRuns.push({+ ...existingCellRun,+ startTime: startTime,+ elapsedTime: elapsedTime,+ status: status,+ });+ found = true;+ } else {+ nextRuns.push(existingCellRun);+ }+ }+ if (!found) {+ let status: CellRun["status"];++ if (erroredOutput) {+ status = "error";+ } else if (cellOperation.status === "queued") {+ status = "queued";+ } else if (cellOperation.status === "running") {+ status = "running";+ } else {+ status = "success";+ }++ nextRuns.push({+ cellId: cellOperation.cell_id as CellId,+ code: code.slice(0, MAX_CODE_LENGTH),+ elapsedTime: 0,+ status: status,+ startTime: cellOperation.timestamp,+ });+ }++ run.cellRuns = nextRuns;++ const nextRunMap = new Map(state.runMap);+ nextRunMap.set(runId, run);++ return {+ ...state,+ runIds: runIds,+ runMap: nextRunMap,+ };+ },+ clearRuns: (state: RunsState): RunsState => ({+ ...state,+ runIds: [],+ runMap: new Map(),+ }),+ removeRun: (state: RunsState, runId: RunId): RunsState => {+ const nextRunIds = state.runIds.filter((id) => id !== runId);+ const nextRunMap = new Map(state.runMap);+ nextRunMap.delete(runId);+ return {+ ...state,+ runIds: nextRunIds,+ runMap: nextRunMap,+ };+ },+});++export { runsAtom, useRunsActions };++export const exportedForTesting = {+ reducer,+ createActions,+ initialState,+};diff --git a/frontend/src/core/config/feature-flag.tsx b/frontend/src/core/config/feature-flag.tsxindex c2823640c9..c8f3866435 100644--- a/frontend/src/core/config/feature-flag.tsx+++ b/frontend/src/core/config/feature-flag.tsx@@ -12,6 +12,7 @@ export interface ExperimentalFeatures {scratchpad: boolean;multi_column: boolean;chat_sidebar: boolean;+ tracing: boolean;// Add new feature flags here}@@ -21,6 +22,7 @@ const defaultValues: ExperimentalFeatures = {scratchpad: true,multi_column: import.meta.env.DEV,chat_sidebar: import.meta.env.DEV,+ tracing: import.meta.env.DEV,};export function getFeatureFlag<T extends keyof ExperimentalFeatures>(diff --git a/frontend/src/core/websocket/useMarimoWebSocket.tsx b/frontend/src/core/websocket/useMarimoWebSocket.tsxindex 7af3d4f47f..6136221e92 100644--- a/frontend/src/core/websocket/useMarimoWebSocket.tsx+++ b/frontend/src/core/websocket/useMarimoWebSocket.tsx@@ -4,7 +4,7 @@ import { useAtom, useSetAtom } from "jotai";import { connectionAtom } from "../network/connection";import { useWebSocket } from "@/core/websocket/useWebSocket";import { logNever } from "@/utils/assertNever";-import { useCellActions } from "@/core/cells/cells";+import { getNotebook, useCellActions } from "@/core/cells/cells";import { AUTOCOMPLETER } from "@/core/codemirror/completion/Autocompleter";import type { OperationMessage } from "@/core/kernel/messages";import type { CellData } from "../cells/types";@@ -40,6 +40,7 @@ import { focusAndScrollCellOutputIntoView } from "../cells/scrollCellIntoView";import { capabilitiesAtom } from "../config/capabilities";import { UI_ELEMENT_REGISTRY } from "../dom/uiregistry";import { reloadSafe } from "@/utils/reload-safe";+import { useRunsActions } from "../cells/runs";/*** WebSocket that connects to the Marimo kernel and handles incoming messages.@@ -55,6 +56,7 @@ export function useMarimoWebSocket(opts: {const { showBoundary } = useErrorBoundary();const { handleCellMessage, setCellCodes, setCellIds } = useCellActions();+ const { addCellOperation } = useRunsActions();const setAppConfig = useSetAppConfig();const { setVariables, setMetadata } = useVariablesActions();const { addColumnPreview } = useDatasetsActions();@@ -110,9 +112,12 @@ export function useMarimoWebSocket(opts: {msg.data,);return;- case "cell-op":+ case "cell-op": {handleCellOperation(msg.data, handleCellMessage);+ const cellData = getNotebook().cellData[msg.data.cell_id as CellId];+ addCellOperation({ cellOperation: msg.data, code: cellData.code });return;+ }case "variables":setVariables(diff --git a/marimo/_messaging/context.py b/marimo/_messaging/context.pynew file mode 100644index 0000000000..af7a8edab9--- /dev/null+++ b/marimo/_messaging/context.py@@ -0,0 +1,23 @@+import uuid+from contextvars import ContextVar+from dataclasses import dataclass+from typing import Any, Optional++RunId_t = str+RUN_ID_CTX = ContextVar[Optional[RunId_t]]("run_id")+++@dataclass+class run_id_context:+ """Context manager for setting and unsetting the run ID."""++ run_id: RunId_t++ def __init__(self) -> None:+ self.run_id = str(uuid.uuid4())++ def __enter__(self) -> None:+ self.token = RUN_ID_CTX.set(self.run_id)++ def __exit__(self, *_: Any) -> None:+ RUN_ID_CTX.reset(self.token)diff --git a/marimo/_messaging/ops.py b/marimo/_messaging/ops.pyindex 7d84e623f5..2086b236ce 100644--- a/marimo/_messaging/ops.py+++ b/marimo/_messaging/ops.py@@ -32,6 +32,7 @@ from marimo._data.models import ColumnSummary, DataTable, DataTableSourcefrom marimo._dependencies.dependencies import DependencyManagerfrom marimo._messaging.cell_output import CellChannel, CellOutputfrom marimo._messaging.completion_option import CompletionOption+from marimo._messaging.context import RUN_ID_CTX, RunId_tfrom marimo._messaging.errors import (Error,MarimoInternalError,@@ -106,13 +107,14 @@ class Op:class CellOp(Op):"""Op to transition a cell.- A CellOp's data has three optional fields:+ A CellOp's data has some optional fields:output - a CellOutputconsole - a CellOutput (console msg to append), or a list ofCellOutputsstatus - execution statusstale_inputs - whether the cell has stale inputs (variables, modules, ...)+ run_id - the run associated with this cell.Omitting a field means that its value should be unchanged!@@ -127,8 +129,28 @@ class CellOp(Op):console: Optional[Union[CellOutput, List[CellOutput]]] = Nonestatus: Optional[RuntimeStateType] = Nonestale_inputs: Optional[bool] = None+ run_id: Optional[RunId_t] = Nonetimestamp: float = field(default_factory=lambda: time.time())+ def __post_init__(self) -> None:+ if self.run_id is not None:+ return++ # We currently don't support tracing for replayed cell ops (previous session runs)+ if self.status == "idle":+ self.run_id = None+ return++ try:+ self.run_id = RUN_ID_CTX.get()+ except LookupError:+ # Be specific about the exception we're catching+ # The context variable hasn't been set yet+ self.run_id = None+ except Exception as e:+ LOGGER.error("Error getting run id: %s", str(e))+ self.run_id = None+@staticmethoddef maybe_truncate_output(mimetype: KnownMimeType, data: strdiff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.pyindex a94138e0f1..4b241ae664 100644--- a/marimo/_runtime/runtime.py+++ b/marimo/_runtime/runtime.py@@ -31,6 +31,7 @@ from marimo._data.preview_column import ()from marimo._dependencies.dependencies import DependencyManagerfrom marimo._messaging.cell_output import CellChannel+from marimo._messaging.context import run_id_contextfrom marimo._messaging.errors import (Error,MarimoInterruptionError,@@ -1129,18 +1130,19 @@ class Kernel:async def _run_cells(self, cell_ids: set[CellId_t]) -> None:"""Run cells and any state updates they trigger"""- # This patch is an attempt to mitigate problems caused by the fact- # that in run mode, kernels run in threads and share the same- # sys.modules. Races can still happen, but this should help in most- # common cases. We could also be more aggressive and run this before- # every cell, or even before pickle.dump/pickle.dumps()- with patches.patch_main_module_context(self._module):- while cell_ids := await self._run_cells_internal(cell_ids):- LOGGER.debug("Running state updates ...")- if self.lazy() and cell_ids:- self.graph.set_stale(cell_ids, prune_imports=True)- break- LOGGER.debug("Finished run.")+ with run_id_context():+ # This patch is an attempt to mitigate problems caused by the fact+ # that in run mode, kernels run in threads and share the same+ # sys.modules. Races can still happen, but this should help in most+ # common cases. We could also be more aggressive and run this before+ # every cell, or even before pickle.dump/pickle.dumps()+ with patches.patch_main_module_context(self._module):+ while cell_ids := await self._run_cells_internal(cell_ids):+ LOGGER.debug("Running state updates ...")+ if self.lazy() and cell_ids:+ self.graph.set_stale(cell_ids, prune_imports=True)+ break+ LOGGER.debug("Finished run.")async def _if_autorun_then_run_cells(self, cell_ids: set[CellId_t]diff --git a/openapi/.gitignore b/openapi/.gitignorenew file mode 100644index 0000000000..a7554c2fcc--- /dev/null+++ b/openapi/.gitignore@@ -0,0 +1,2 @@+# dependencies+/node_modules\ No newline at end of filediff --git a/openapi/api.yaml b/openapi/api.yamlindex 1de7bc3146..5f8eb53db5 100644--- a/openapi/api.yaml+++ b/openapi/api.yaml@@ -184,6 +184,9 @@ components:output:$ref: '#/components/schemas/CellOutput'nullable: true+ run_id:+ nullable: true+ type: stringstale_inputs:nullable: truetype: booleandiff --git a/openapi/src/api.ts b/openapi/src/api.tsindex d097f59267..9e181116af 100644--- a/openapi/src/api.ts+++ b/openapi/src/api.ts@@ -2158,6 +2158,7 @@ export interface components {/** @enum {string} */name: "cell-op";output?: components["schemas"]["CellOutput"];+ run_id?: string | null;stale_inputs?: boolean | null;status?: components["schemas"]["RuntimeState"];timestamp: number;diff --git a/tests/_messaging/test_run_id_context.py b/tests/_messaging/test_run_id_context.pynew file mode 100644index 0000000000..348727e9aa--- /dev/null+++ b/tests/_messaging/test_run_id_context.py@@ -0,0 +1,16 @@+import pytest++from marimo._messaging.context import RUN_ID_CTX, run_id_context+++class TestRunIDContext:+ def test_run_id_context(self):+ with run_id_context():+ run_id = RUN_ID_CTX.get()+ assert (+ run_id is not None+ ), "within run_id context but unable to obtain run_id"++ # out of context manager+ with pytest.raises(LookupError):+ RUN_ID_CTX.get()diff --git a/tests/_runtime/test_runtime.py b/tests/_runtime/test_runtime.pyindex 0f89ea8e87..c301489eb0 100644--- a/tests/_runtime/test_runtime.py+++ b/tests/_runtime/test_runtime.py@@ -1227,6 +1227,25 @@ class TestExecution:await k.run([ExecutionRequest(er.cell_id, "None")])assert f"_cell_{er.cell_id}_x" not in k.globals+ async def test_has_run_id(+ self, mocked_kernel: MockedKernel, exec_req: ExecReqProvider+ ) -> None:+ k = mocked_kernel.k+ await k.run([exec_req.get("print(2)")])++ cell_ops = [+ parse_raw(op_data, CellOp)+ for op_name, op_data in mocked_kernel.stream.messages+ if op_name == "cell-op"+ ]++ assert len(cell_ops) == 4 # queued -> running -> output -> idle+ for cell_op in cell_ops:+ if cell_op.status == "idle":+ assert cell_op.run_id is None+ else:+ assert cell_op.run_id is not None+class TestStrictExecution:@staticmethod