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.

improvement: tracing perf, hide charts and skip markdown (#3282)

Myles Scolnick0555fa22fda4
diff --git a/frontend/src/components/app-config/user-config-form.tsx b/frontend/src/components/app-config/user-config-form.tsx
index 3d2e7c69e9..888e61eeca 100644
--- a/frontend/src/components/app-config/user-config-form.tsx
+++ b/frontend/src/components/app-config/user-config-form.tsx
@@ -1096,7 +1096,7 @@ export const UserConfigForm: React.FC = () => {
render={({ field }) => (
<div className="flex flex-col gap-y-1">
<FormItem className={formItemClasses}>
- <FormLabel className="font-normal">Chat Sidebar</FormLabel>
+ <FormLabel className="font-normal">Chat sidebar</FormLabel>
<FormControl>
<Checkbox
data-testid="chat-sidebar-checkbox"
@@ -1112,6 +1112,30 @@ export const UserConfigForm: React.FC = () => {
</div>
)}
/>
+ <FormField
+ control={form.control}
+ name="experimental.tracing"
+ render={({ field }) => (
+ <div className="flex flex-col gap-y-1">
+ <FormItem className={formItemClasses}>
+ <FormLabel className="font-normal">
+ Tracing sidebar
+ </FormLabel>
+ <FormControl>
+ <Checkbox
+ data-testid="tracing-sidebar-checkbox"
+ checked={field.value === true}
+ onCheckedChange={field.onChange}
+ />
+ </FormControl>
+ </FormItem>
+ <FormDescription>
+ Enable experimental tracing sidebar to debug cell execution
+ times and dependencies.
+ </FormDescription>
+ </div>
+ )}
+ />
</SettingGroup>
);
}
diff --git a/frontend/src/components/tracing/tracing.tsx b/frontend/src/components/tracing/tracing.tsx
index 5d36edbd5a..4a9761309a 100644
--- a/frontend/src/components/tracing/tracing.tsx
+++ b/frontend/src/components/tracing/tracing.tsx
@@ -21,7 +21,7 @@ import {
type Run,
useRunsActions,
} from "@/core/cells/runs";
-import { useAtomValue } from "jotai";
+import { atom, useAtomValue, useSetAtom } from "jotai";
import { CellLink } from "../editor/links/cell-link";
import { formatLogTimestamp } from "@/core/cells/logs";
import { useCellIds } from "@/core/cells/cells";
@@ -35,9 +35,13 @@ 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";
+import useResizeObserver from "use-resize-observer";
+
+const expandedRunsAtom = atom<Map<RunId, boolean>>(new Map<RunId, boolean>());
export const Tracing: React.FC = () => {
const { runIds: newestToOldestRunIds, runMap } = useAtomValue(runsAtom);
+ const expandedRuns = useAtomValue(expandedRunsAtom);
const { clearRuns } = useRunsActions();
const { theme } = useTheme();
@@ -82,13 +86,15 @@ export const Tracing: React.FC = () => {
</div>
<div className="flex flex-col gap-3">
- {newestToOldestRunIds.map((runId: RunId) => {
+ {newestToOldestRunIds.map((runId: RunId, index: number) => {
const run = runMap.get(runId);
if (run) {
return (
<TraceBlock
key={run.runId}
run={run}
+ isExpanded={expandedRuns.get(run.runId)}
+ isMostRecentRun={index === 0}
chartPosition={chartPosition}
theme={theme}
/>
@@ -101,11 +107,10 @@ export const Tracing: React.FC = () => {
};
const LazyVega = React.lazy(() =>
- import("react-vega").then((m) => ({ default: m.Vega })),
+ import("react-vega").then((m) => ({ default: m.VegaLite })),
);
interface ChartProps {
className?: string;
- width: number;
height: number;
vegaSpec: VisualizationSpec;
signalListeners: SignalListeners;
@@ -113,12 +118,13 @@ interface ChartProps {
}
const Chart: React.FC<ChartProps> = (props: ChartProps) => {
+ const { ref, width = 300 } = useResizeObserver<HTMLDivElement>();
return (
- <div className={props.className}>
+ <div className={props.className} ref={ref}>
<LazyVega
spec={props.vegaSpec}
theme={props.theme === "dark" ? "dark" : undefined}
- width={props.width}
+ width={width - 50}
height={props.height}
signalListeners={props.signalListeners}
actions={false}
@@ -134,24 +140,64 @@ interface VegaHoverCellSignal {
const TraceBlock: React.FC<{
run: Run;
+ /**
+ * undefined means the user hasn't clicked on this run yet
+ */
+ isExpanded: boolean | undefined;
+ isMostRecentRun: boolean;
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 }),
- );
- }
+}> = ({ run, isMostRecentRun, chartPosition, isExpanded, theme }) => {
+ const setExpandedRuns = useSetAtom(expandedRunsAtom);
+ // We prefer the user's last click, but if they haven't clicked on this run,
+ // we expand the most recent run by default, otherwise we collapse it.
+ isExpanded = isExpanded ?? isMostRecentRun;
+
+ const onToggleExpanded = () => {
+ setExpandedRuns((prev) => {
+ const newMap = new Map(prev);
+ newMap.set(run.runId, !isExpanded);
+ return newMap;
+ });
};
+ const Icon = isExpanded ? ChevronDown : ChevronRight;
+ const chevron = <Icon height={16} className="inline" />;
+
+ const traceTitle = (
+ <span className="text-sm cursor-pointer" onClick={onToggleExpanded}>
+ Run - {formatLogTimestamp(run.runStartTime)}
+ {chevron}
+ </span>
+ );
+
+ if (!isExpanded) {
+ return (
+ <div key={run.runId} className="flex flex-col">
+ <pre className="font-mono font-semibold">{traceTitle}</pre>
+ </div>
+ );
+ }
+
+ return (
+ <TraceBlockBody
+ key={run.runId}
+ run={run}
+ chartPosition={chartPosition}
+ theme={theme}
+ title={traceTitle}
+ />
+ );
+};
+
+const TraceBlockBody: React.FC<{
+ run: Run;
+ chartPosition: ChartPosition;
+ theme: ResolvedTheme;
+ title: React.ReactNode;
+}> = ({ run, chartPosition, theme, title }) => {
+ const [hoveredCellId, setHoveredCellId] = useState<CellId | null>();
+
const handleVegaSignal = {
[VEGA_HOVER_SIGNAL]: (name: string, value: unknown) => {
const signalValue = value as VegaHoverCellSignal;
@@ -160,19 +206,6 @@ const TraceBlock: React.FC<{
},
};
- 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) => {
@@ -197,41 +230,26 @@ const TraceBlock: React.FC<{
),
).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>
+ const traceRows = (
+ <TraceRows
+ run={run}
+ hoveredCellId={hoveredCellId}
+ hiddenInputElementId={hiddenInputElementId}
+ />
);
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}
+ {title}
+ <Chart
+ vegaSpec={vegaSpec}
+ height={120}
+ signalListeners={handleVegaSignal}
+ theme={theme}
+ />
+ {traceRows}
</pre>
</div>
);
@@ -240,19 +258,56 @@ const TraceBlock: React.FC<{
return (
<div key={run.runId} className="flex flex-row">
<pre className="font-mono font-semibold">
- {TraceTitle}
- {!collapsed && TraceRows}
+ {title}
+ {traceRows}
</pre>
- {!collapsed && (
- <Chart
- className="-mt-0.5"
- vegaSpec={vegaSpec}
- width={240}
- height={100}
- signalListeners={handleVegaSignal}
- theme={theme}
+ <Chart
+ className="-mt-0.5 flex-1"
+ vegaSpec={vegaSpec}
+ height={100}
+ signalListeners={handleVegaSignal}
+ theme={theme}
+ />
+ </div>
+ );
+};
+
+const TraceRows = (props: {
+ run: Run;
+ hoveredCellId: CellId | null | undefined;
+ hiddenInputElementId: string;
+}) => {
+ const { run, hoveredCellId, hiddenInputElementId } = props;
+
+ // 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 }),
+ );
+ }
+ };
+
+ return (
+ <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>
);
};
diff --git a/frontend/src/core/cells/__tests__/runs.test.ts b/frontend/src/core/cells/__tests__/runs.test.ts
index 01874ddf01..937d7fd61e 100644
--- a/frontend/src/core/cells/__tests__/runs.test.ts
+++ b/frontend/src/core/cells/__tests__/runs.test.ts
@@ -10,9 +10,9 @@ import {
} from "../runs";
import type { CellMessage } from "@/core/kernel/messages";
-describe("RunsState Reducer", () => {
- const { reducer, initialState } = exportedForTesting;
+const { reducer, initialState, isPureMarkdown } = exportedForTesting;
+describe("RunsState Reducer", () => {
let state: RunsState;
const runId = "run1" as RunId;
@@ -129,7 +129,7 @@ describe("RunsState Reducer", () => {
runStartTimestamp,
);
- const successState = reducer(state, {
+ const successState = reducer(updatedState, {
type: "addCellOperation",
payload: {
cellOperation: {
@@ -318,4 +318,119 @@ describe("RunsState Reducer", () => {
expect(finalState.runIds).toEqual([runId3, runId2, runId]);
});
+
+ it("should create a new run object when adding a cell operation", () => {
+ const state1 = addQueuedCell();
+ const run1 = state1.runMap.get(runId);
+
+ const state2 = reducer(state1, {
+ type: "addCellOperation",
+ payload: {
+ cellOperation: {
+ run_id: runId,
+ cell_id: "cell2",
+ timestamp: timestamp + 1000,
+ status: "queued",
+ },
+ code: "print('Another cell')",
+ },
+ });
+
+ const run2 = state2.runMap.get(runId);
+ expect(run2).not.toBe(run1);
+ expect(run2?.cellRuns).not.toBe(run1?.cellRuns);
+ });
+
+ it("should create new run object when updating cell status", () => {
+ const state1 = addQueuedCell();
+ const run1 = state1.runMap.get(runId);
+
+ const state2 = reducer(state1, {
+ type: "addCellOperation",
+ payload: {
+ cellOperation: {
+ run_id: runId,
+ cell_id: cellId,
+ timestamp: timestamp + 1000,
+ status: "running",
+ },
+ code: code,
+ },
+ });
+
+ const run2 = state2.runMap.get(runId);
+ expect(run2).not.toBe(run1);
+ expect(run2?.cellRuns).not.toBe(run1?.cellRuns);
+ });
+
+ it("should skip markdown for first run", () => {
+ const markdownState = reducer(state, {
+ type: "addCellOperation",
+ payload: {
+ cellOperation: {
+ run_id: runId,
+ cell_id: cellId,
+ timestamp,
+ status: "queued",
+ },
+ code: 'mo.md("""# Hello""")',
+ },
+ });
+
+ expect(markdownState.runIds).toEqual([]);
+ expect(markdownState.runMap.size).toBe(0);
+ });
+
+ it("should not skip markdown if first run was not markdown", () => {
+ // Add non-markdown run first
+ let nextState = reducer(state, {
+ type: "addCellOperation",
+ payload: {
+ cellOperation: {
+ run_id: runId,
+ cell_id: cellId,
+ timestamp,
+ status: "queued",
+ },
+ code: "print('hello')",
+ },
+ });
+
+ // Add markdown run second
+ nextState = reducer(nextState, {
+ type: "addCellOperation",
+ payload: {
+ cellOperation: {
+ run_id: runId,
+ cell_id: "cell2",
+ timestamp: timestamp + 1000,
+ status: "queued",
+ },
+ code: 'mo.md("""# Hello""")',
+ },
+ });
+
+ expect(nextState.runIds).toEqual([runId]);
+ expect(nextState.runMap.size).toBe(1);
+ expect(nextState.runMap.get(runId)?.cellRuns.length).toBe(2);
+ });
+});
+
+describe("isPureMarkdown", () => {
+ it("should return true for pure markdown", () => {
+ expect(isPureMarkdown("mo.md(r'''")).toBe(true);
+ expect(isPureMarkdown('mo.md(r"""')).toBe(true);
+ expect(isPureMarkdown("mo.md('''")).toBe(true);
+ expect(isPureMarkdown('mo.md("""')).toBe(true);
+
+ expect(isPureMarkdown("mo.md(\nr'''")).toBe(true);
+ expect(isPureMarkdown('mo.md(\nr"""')).toBe(true);
+ expect(isPureMarkdown("mo.md(\n'''")).toBe(true);
+ expect(isPureMarkdown('mo.md(\n"""')).toBe(true);
+ });
+
+ it("should return false for non-markdown", () => {
+ expect(isPureMarkdown("mo.md(f'''")).toBe(false);
+ expect(isPureMarkdown('mo.md(f"""')).toBe(false);
+ });
});
diff --git a/frontend/src/core/cells/runs.ts b/frontend/src/core/cells/runs.ts
index 861b37a3d0..537b5d26ae 100644
--- a/frontend/src/core/cells/runs.ts
+++ b/frontend/src/core/cells/runs.ts
@@ -31,7 +31,7 @@ function initialState(): RunsState {
};
}
-export const MAX_RUNS = 20;
+export const MAX_RUNS = 50;
export const MAX_CODE_LENGTH = 200;
const {
@@ -54,7 +54,16 @@ const {
let run = state.runMap.get(runId);
if (run) {
runIds = state.runIds;
+ // Shallow copy the run to avoid mutating the existing run
+ run = { ...run };
} else {
+ // If it is a brand new run and the cell code is "pure markdown",
+ // we don't want to show the trace since it's not helpful.
+ // This spams the tracing because we re-render pure markdown on keystrokes.
+ if (isPureMarkdown(code)) {
+ return state;
+ }
+
run = {
runId: runId,
cellRuns: [],
@@ -161,10 +170,16 @@ const {
},
});
+const MARKDOWN_REGEX = /mo\.md\(\s*r?('''|""")/;
+function isPureMarkdown(code: string): boolean {
+ return code.startsWith("mo.md(") && MARKDOWN_REGEX.test(code);
+}
+
export { runsAtom, useRunsActions };
export const exportedForTesting = {
reducer,
createActions,
initialState,
+ isPureMarkdown,
};