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(editor): add code lens linking datasources, buckets, and caches to panels (#10161)
Myles Scolnick254ee018cc80
diff --git a/frontend/src/components/editor/chrome/__tests__/state.test.ts b/frontend/src/components/editor/chrome/__tests__/state.test.tsindex 73ae56e409..08763e4283 100644--- a/frontend/src/components/editor/chrome/__tests__/state.test.ts+++ b/frontend/src/components/editor/chrome/__tests__/state.test.ts@@ -1,9 +1,15 @@/* Copyright 2026 Marimo. All rights reserved. */-import { describe, expect, it } from "vitest";+import { describe, expect, it, vi } from "vitest";import { adaptForLocalStorage } from "@/utils/storage/jotai";import type { PanelLayout } from "../state";import { exportedForTesting } from "../state";+// Panel visibility (and thus the default layout) depends on feature flags,+// some of which default on in dev builds; pin them off for stable layouts.+vi.mock("@/core/config/feature-flag", () => ({+ getFeatureFlag: () => false,+}));+const { mergePanelLayout } = exportedForTesting;describe("mergePanelLayout", () => {diff --git a/frontend/src/components/editor/chrome/panels/__tests__/panel-accordion-state.test.ts b/frontend/src/components/editor/chrome/panels/__tests__/panel-accordion-state.test.tsnew file mode 100644index 0000000000..fbdee3e7f4--- /dev/null+++ b/frontend/src/components/editor/chrome/panels/__tests__/panel-accordion-state.test.ts@@ -0,0 +1,42 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { afterAll, expect, it } from "vitest";+import { store } from "@/core/state/jotai";+import { availableStorage } from "@/utils/storage/storage";++const SESSION_PANEL_KEY = "marimo:session-panel:state";+const FILE_EXPLORER_PANEL_KEY = "marimo:file-explorer-panel:state";++afterAll(() => {+ availableStorage.removeItem(SESSION_PANEL_KEY);+ availableStorage.removeItem(FILE_EXPLORER_PANEL_KEY);+});++it("preserves stored panel state when expanding an unmounted panel", async () => {+ const persistedState = {+ openSections: [],+ hasUserInteracted: true,+ };+ availableStorage.setItem(SESSION_PANEL_KEY, JSON.stringify(persistedState));+ availableStorage.setItem(+ FILE_EXPLORER_PANEL_KEY,+ JSON.stringify(persistedState),+ );++ // Import after seeding storage to exercise atom initialization before a+ // lazily mounted panel subscribes to it.+ const { expandAccordionSection, fileExplorerPanelAtom, sessionPanelAtom } =+ await import("../panel-accordion-state");++ expandAccordionSection(sessionPanelAtom, "datasources");+ expandAccordionSection(fileExplorerPanelAtom, "remote-storage");++ expect(store.get(sessionPanelAtom)).toEqual({+ openSections: ["datasources"],+ hasUserInteracted: true,+ });+ expect(store.get(fileExplorerPanelAtom)).toEqual({+ openSections: ["remote-storage"],+ hasUserInteracted: true,+ });+});diff --git a/frontend/src/components/editor/chrome/panels/file-explorer-panel.tsx b/frontend/src/components/editor/chrome/panels/file-explorer-panel.tsxindex 5b55fa39e2..96a974edd2 100644--- a/frontend/src/components/editor/chrome/panels/file-explorer-panel.tsx+++ b/frontend/src/components/editor/chrome/panels/file-explorer-panel.tsx@@ -1,7 +1,6 @@/* Copyright 2026 Marimo. All rights reserved. */import { useAtom, useAtomValue } from "jotai";-import { atomWithStorage } from "jotai/utils";import { FileIcon, HardDrive } from "lucide-react";import React, { useCallback, useMemo } from "react";import useResizeObserver from "use-resize-observer";@@ -9,7 +8,6 @@ import { StorageInspector } from "@/components/storage/storage-inspector";import { Accordion } from "@/components/ui/accordion";import { storageNamespacesAtom } from "@/core/storage/state";import { cn } from "@/utils/cn";-import { jotaiJsonStorage } from "@/utils/storage/jotai";import { TreeDndProvider } from "../../file-tree/dnd-wrapper";import { FileExplorer } from "../../file-tree/file-explorer";import { useFileExplorerUpload } from "../../file-tree/upload";@@ -19,19 +17,10 @@ import {PanelAccordionTrigger,PanelBadge,} from "./components";--type OpenSections = "files" | "remote-storage";--interface FileExplorerPanelState {- openSections: OpenSections[];- hasUserInteracted: boolean;-}--const fileExplorerPanelAtom = atomWithStorage<FileExplorerPanelState>(- "marimo:file-explorer-panel:state",- { openSections: ["files"], hasUserInteracted: false },- jotaiJsonStorage,-);+import {+ fileExplorerPanelAtom,+ type FileExplorerPanelSection,+} from "./panel-accordion-state";const FileExplorerComponent: React.FC<{ height: number }> = ({ height }) => {const { getRootProps, getInputProps, isDragActive } = useFileExplorerUpload({@@ -70,7 +59,7 @@ const FileExplorerPanel: React.FC = () => {const storageNamespaces = useAtomValue(storageNamespacesAtom);const remoteStorageConnections = storageNamespaces.length;- const openSections = useMemo<OpenSections[]>(() => {+ const openSections = useMemo<FileExplorerPanelSection[]>(() => {if (!state.hasUserInteracted && remoteStorageConnections > 0) {if (state.openSections.includes("remote-storage")) {return state.openSections;@@ -81,7 +70,7 @@ const FileExplorerPanel: React.FC = () => {}, [state.hasUserInteracted, state.openSections, remoteStorageConnections]);const handleValueChange = useCallback(- (value: OpenSections[]) => {+ (value: FileExplorerPanelSection[]) => {setState({openSections: value,hasUserInteracted: true,diff --git a/frontend/src/components/editor/chrome/panels/panel-accordion-state.ts b/frontend/src/components/editor/chrome/panels/panel-accordion-state.tsnew file mode 100644index 0000000000..ae884a1a74--- /dev/null+++ b/frontend/src/components/editor/chrome/panels/panel-accordion-state.ts@@ -0,0 +1,51 @@+/* Copyright 2026 Marimo. All rights reserved. */++import type { WritableAtom } from "jotai";+import { atomWithStorage } from "jotai/utils";+import { store } from "@/core/state/jotai";+import { jotaiJsonStorage } from "@/utils/storage/jotai";++export type SessionPanelSection = "variables" | "datasources";+export type FileExplorerPanelSection = "files" | "remote-storage";++export interface PanelAccordionState<Section extends string> {+ openSections: Section[];+ hasUserInteracted: boolean;+}++export const sessionPanelAtom = atomWithStorage<+ PanelAccordionState<SessionPanelSection>+>(+ "marimo:session-panel:state",+ { openSections: ["variables"], hasUserInteracted: false },+ jotaiJsonStorage,+ { getOnInit: true },+);++export const fileExplorerPanelAtom = atomWithStorage<+ PanelAccordionState<FileExplorerPanelSection>+>(+ "marimo:file-explorer-panel:state",+ { openSections: ["files"], hasUserInteracted: false },+ jotaiJsonStorage,+ { getOnInit: true },+);++/**+ * Expand an accordion section without collapsing others. Leaves+ * `hasUserInteracted` untouched so auto-open heuristics are unaffected.+ */+export function expandAccordionSection<Section extends string>(+ panelAtom: WritableAtom<+ PanelAccordionState<Section>,+ [(prev: PanelAccordionState<Section>) => PanelAccordionState<Section>],+ void+ >,+ section: Section,+): void {+ store.set(panelAtom, (prev) =>+ prev.openSections.includes(section)+ ? prev+ : { ...prev, openSections: [...prev.openSections, section] },+ );+}diff --git a/frontend/src/components/editor/chrome/panels/session-panel.tsx b/frontend/src/components/editor/chrome/panels/session-panel.tsxindex 8f02e137dd..c42d5a4a6a 100644--- a/frontend/src/components/editor/chrome/panels/session-panel.tsx+++ b/frontend/src/components/editor/chrome/panels/session-panel.tsx@@ -1,7 +1,6 @@/* Copyright 2026 Marimo. All rights reserved. */import { useAtom, useAtomValue } from "jotai";-import { atomWithStorage } from "jotai/utils";import { DatabaseIcon, VariableIcon } from "lucide-react";import React, { useCallback } from "react";import {@@ -13,26 +12,16 @@ import { VariableTable } from "@/components/variables/variables-table";import { useCellIds } from "@/core/cells/cells";import { datasetTablesAtom } from "@/core/datasets/state";import { useVariables } from "@/core/variables/state";-import { jotaiJsonStorage } from "@/utils/storage/jotai";import {PanelAccordionContent,PanelAccordionItem,PanelAccordionTrigger,PanelBadge,} from "./components";--type OpenSections = "variables" | "datasources";--interface SessionPanelState {- openSections: OpenSections[];- hasUserInteracted: boolean;-}--const sessionPanelAtom = atomWithStorage<SessionPanelState>(- "marimo:session-panel:state",- { openSections: ["variables"], hasUserInteracted: false },- jotaiJsonStorage,-);+import {+ sessionPanelAtom,+ type SessionPanelSection,+} from "./panel-accordion-state";const SessionPanel: React.FC = () => {const variables = useVariables();@@ -50,7 +39,7 @@ const SessionPanel: React.FC = () => {: state.openSections;const handleValueChange = useCallback(- (value: OpenSections[]) => {+ (value: SessionPanelSection[]) => {setState({openSections: value,hasUserInteracted: true,diff --git a/frontend/src/components/editor/chrome/state.ts b/frontend/src/components/editor/chrome/state.tsindex dfd04bd634..112ccf5569 100644--- a/frontend/src/components/editor/chrome/state.ts+++ b/frontend/src/components/editor/chrome/state.ts@@ -196,6 +196,16 @@ export function useChromeActions() {return useActions();}+/**+ * Open a panel imperatively from non-React code (e.g. CodeMirror extensions).+ * No-ops if the panel is hidden (not in the layout).+ */+export function openPanel(panelType: PanelType): void {+ store.set(chromeAtom, (prev) =>+ reducer(prev, { type: "openApplication", payload: panelType }),+ );+}+export { chromeAtom };/**diff --git a/frontend/src/core/codemirror/cm.ts b/frontend/src/core/codemirror/cm.tsindex 2630e9abe5..a1f24867be 100644--- a/frontend/src/core/codemirror/cm.ts+++ b/frontend/src/core/codemirror/cm.ts@@ -50,6 +50,7 @@ import type { HotkeyProvider } from "../hotkeys/hotkeys";import { requestEditCompletion } from "./ai/request";import { cellBundle } from "./cells/extensions";import type { CodemirrorCellActions } from "./cells/state";+import { codeLensBundle } from "./code-lens/extension";import { jupyterHelpExtension } from "./compat/jupyter";import { hintTooltip } from "./completion/hints";import { completionKeymap } from "./completion/keymap";@@ -198,6 +199,8 @@ export const setupCodeMirror = (opts: CodeMirrorSetupOpts): Extension[] => {cellId,displayConfig.reference_highlighting ?? true,),+ // Inline icons linking datasources/buckets/caches to their panels+ codeLensBundle(cellId),];};diff --git a/frontend/src/core/codemirror/code-lens/__tests__/actions.test.ts b/frontend/src/core/codemirror/code-lens/__tests__/actions.test.tsnew file mode 100644index 0000000000..a0864f99f3--- /dev/null+++ b/frontend/src/core/codemirror/code-lens/__tests__/actions.test.ts@@ -0,0 +1,68 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { beforeEach, describe, expect, it, vi } from "vitest";+import {+ fileExplorerPanelAtom,+ sessionPanelAtom,+} from "@/components/editor/chrome/panels/panel-accordion-state";+import { openPanel } from "@/components/editor/chrome/state";+import { store } from "@/core/state/jotai";+import { openLensTarget } from "../actions";++vi.mock("@/components/editor/chrome/state", () => ({+ openPanel: vi.fn(),+}));++describe("openLensTarget", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ store.set(sessionPanelAtom, {+ openSections: ["variables"],+ hasUserInteracted: false,+ });+ store.set(fileExplorerPanelAtom, {+ openSections: ["files"],+ hasUserInteracted: true,+ });+ });++ it.each(["table", "connection"] as const)(+ "opens the variables panel and expands datasources for a %s",+ (kind) => {+ openLensTarget(kind);++ expect(openPanel).toHaveBeenCalledWith("variables");+ expect(store.get(sessionPanelAtom).openSections).toEqual([+ "variables",+ "datasources",+ ]);+ },+ );++ it("opens the files panel and expands remote storage for a bucket", () => {+ openLensTarget("bucket");++ expect(openPanel).toHaveBeenCalledWith("files");+ expect(store.get(fileExplorerPanelAtom).openSections).toEqual([+ "files",+ "remote-storage",+ ]);+ });++ it("opens the cache panel for a cache", () => {+ openLensTarget("cache");++ expect(openPanel).toHaveBeenCalledWith("cache");+ expect(store.get(sessionPanelAtom).openSections).toEqual(["variables"]);+ expect(store.get(fileExplorerPanelAtom).openSections).toEqual(["files"]);+ });++ it("does not duplicate an already-open section or mark interaction", () => {+ openLensTarget("table");+ openLensTarget("table");++ const state = store.get(sessionPanelAtom);+ expect(state.openSections).toEqual(["variables", "datasources"]);+ expect(state.hasUserInteracted).toBe(false);+ });+});diff --git a/frontend/src/core/codemirror/code-lens/__tests__/analyzer.test.ts b/frontend/src/core/codemirror/code-lens/__tests__/analyzer.test.tsnew file mode 100644index 0000000000..b0dd6ebc62--- /dev/null+++ b/frontend/src/core/codemirror/code-lens/__tests__/analyzer.test.ts@@ -0,0 +1,224 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { python } from "@codemirror/lang-python";+import { EditorState } from "@codemirror/state";+import { describe, expect, it } from "vitest";+import { findCacheSites, findDeclarationSites } from "../analyzer";++function pythonState(code: string) {+ return EditorState.create({ doc: code, extensions: [python()] });+}++function run(names: string[], code: string) {+ return findDeclarationSites({+ state: pythonState(code),+ names: new Set(names),+ });+}++describe("findDeclarationSites", () => {+ it("finds a simple assignment", () => {+ const code = 'df = pd.read_csv("a.csv")';+ const targets = run(["df"], code);+ expect(targets).toEqual([{ from: 0, to: 2, name: "df" }]);+ expect(code.slice(targets[0].from, targets[0].to)).toBe("df");+ });++ it("only matches the given names", () => {+ const targets = run(["df"], "df = 1\nother = 2");+ expect(targets.map((t) => t.name)).toEqual(["df"]);+ });++ it("handles annotated assignments", () => {+ const targets = run(["df", "DataFrame"], "df: DataFrame = load()");+ expect(targets.map((t) => t.name)).toEqual(["df"]);+ });++ it("handles chained assignments", () => {+ const targets = run(["a", "b"], "a = b = load()");+ expect(targets.map((t) => t.name).toSorted()).toEqual(["a", "b"]);+ });++ it("handles tuple and list unpacking", () => {+ expect(run(["x", "y"], "x, y = f()").map((t) => t.name)).toEqual([+ "x",+ "y",+ ]);+ expect(run(["a", "b"], "(a, b) = f()").map((t) => t.name)).toEqual([+ "a",+ "b",+ ]);+ expect(run(["a", "b"], "[a, b] = f()").map((t) => t.name)).toEqual([+ "a",+ "b",+ ]);+ });++ it("handles a parenthesized single target", () => {+ expect(run(["df"], "(df) = load()").map((t) => t.name)).toEqual(["df"]);+ });++ it("returns only the first assignment site per name", () => {+ const targets = run(["df"], "df = 1\ndf = 2");+ expect(targets).toEqual([{ from: 0, to: 2, name: "df" }]);+ });++ it("ignores attribute and subscript targets", () => {+ expect(run(["df"], "obj.df = 1")).toEqual([]);+ expect(run(["df"], "data[df] = 1")).toEqual([]);+ });++ it("ignores augmented assignments", () => {+ expect(run(["df"], "df += 1")).toEqual([]);+ });++ it("ignores assignments in function, lambda, and class scopes", () => {+ expect(run(["df"], "def f():\n df = 1")).toEqual([]);+ expect(run(["df"], "class A:\n df = 1")).toEqual([]);+ });++ it("finds assignments in top-level control flow", () => {+ const targets = run(["df"], "if cond:\n df = load()");+ expect(targets.map((t) => t.name)).toEqual(["df"]);+ });++ it("ignores usages that are not assignments", () => {+ expect(run(["df"], "print(df)")).toEqual([]);+ });++ it("returns nothing for syntax errors", () => {+ expect(run(["df"], "df = (")).toEqual([]);+ });++ it("returns nothing for an empty name set", () => {+ expect(run([], "df = 1")).toEqual([]);+ });+});++describe("findCacheSites", () => {+ function runCache(code: string) {+ return findCacheSites(pythonState(code)).map((site) =>+ code.slice(site.from, site.to),+ );+ }++ it("matches decorator usage", () => {+ expect(runCache("@mo.cache\ndef f():\n return 1")).toEqual(["mo.cache"]);+ });++ it("extends past decorator arguments", () => {+ expect(+ runCache("@mo.cache(pin_modules=True)\ndef f():\n return 1"),+ ).toEqual(["mo.cache(pin_modules=True)"]);+ });++ it("extends past call arguments", () => {+ expect(runCache("g = mo.cache(f)")).toEqual(["mo.cache(f)"]);+ expect(runCache("g = mo.cache(f, pin_modules=True)")).toEqual([+ "mo.cache(f, pin_modules=True)",+ ]);+ });++ it("does not extend a bare reference or an enclosing call", () => {+ expect(runCache("g = mo.cache")).toEqual(["mo.cache"]);+ expect(runCache("print(mo.cache, 1)")).toEqual(["mo.cache"]);+ });++ it("matches persistent_cache context manager usage", () => {+ expect(runCache('with mo.persistent_cache("k"):\n pass')).toEqual([+ 'mo.persistent_cache("k")',+ ]);+ });++ it("matches multiple occurrences", () => {+ expect(runCache("mo.cache(f)\nmo.persistent_cache(g)")).toHaveLength(2);+ });++ it("does not match similar names", () => {+ expect(runCache("memo.cache(f)")).toEqual([]);+ expect(runCache("mo.cached(f)")).toEqual([]);+ expect(runCache("mo.cache_info()")).toEqual([]);+ });++ it("does not match attribute chains like obj.mo.cache", () => {+ expect(runCache("obj.mo.cache(f)")).toEqual([]);+ expect(runCache("self.mo.persistent_cache(g)")).toEqual([]);+ });++ it("does not match mentions in comments or strings", () => {+ expect(runCache("# uses mo.cache internally")).toEqual([]);+ expect(runCache('x = "mo.cache"')).toEqual([]);+ expect(runCache("mo.cache(f) # not mo.persistent_cache")).toEqual([+ "mo.cache(f)",+ ]);+ });++ it("returns nothing for syntax errors", () => {+ expect(runCache("mo.cache(f)\ndf = (")).toEqual([]);+ });++ describe("bound name and cache name extraction", () => {+ function sites(code: string) {+ return findCacheSites(pythonState(code)).map(+ ({ boundName, cacheName }) => ({ boundName, cacheName }),+ );+ }++ it("extracts the decorated function name", () => {+ expect(sites("@mo.cache\ndef add(a, b):\n return a + b")).toEqual([+ { boundName: "add", cacheName: null },+ ]);+ expect(+ sites("@mo.cache(pin_modules=True)\ndef add(a, b):\n return a + b"),+ ).toEqual([{ boundName: "add", cacheName: null }]);+ });++ it("extracts the assignment target", () => {+ expect(sites("g = mo.cache(f)")).toEqual([+ { boundName: "g", cacheName: null },+ ]);+ });++ it("extracts the with-statement binding and cache name", () => {+ expect(sites('with mo.persistent_cache("k") as c:\n pass')).toEqual([+ { boundName: "c", cacheName: "k" },+ ]);+ expect(sites('with mo.persistent_cache("k"):\n pass')).toEqual([+ { boundName: null, cacheName: "k" },+ ]);+ expect(sites('with mo.persistent_cache(name="k"):\n pass')).toEqual([+ { boundName: null, cacheName: "k" },+ ]);+ });++ it("ignores string-valued options that are not cache names", () => {+ expect(+ sites(+ '@mo.cache(hash_type="content")\ndef add(a, b):\n return a + b',+ ),+ ).toEqual([{ boundName: "add", cacheName: null }]);+ expect(+ sites(+ '@mo.persistent_cache(save_path="cache")\ndef add(a, b):\n return a + b',+ ),+ ).toEqual([{ boundName: "add", cacheName: null }]);+ expect(+ sites('with mo.persistent_cache(prefix, save_path="cache"):\n pass'),+ ).toEqual([{ boundName: null, cacheName: null }]);+ });++ it("extracts an explicit name after other keyword arguments", () => {+ expect(+ sites(+ 'with mo.persistent_cache(save_path="cache", name="k"):\n pass',+ ),+ ).toEqual([{ boundName: null, cacheName: "k" }]);+ });++ it("extracts nothing for bare expressions", () => {+ expect(sites("mo.cache(f)")).toEqual([+ { boundName: null, cacheName: null },+ ]);+ });+ });+});diff --git a/frontend/src/core/codemirror/code-lens/__tests__/entities.test.ts b/frontend/src/core/codemirror/code-lens/__tests__/entities.test.tsnew file mode 100644index 0000000000..d100e07980--- /dev/null+++ b/frontend/src/core/codemirror/code-lens/__tests__/entities.test.ts@@ -0,0 +1,175 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { beforeEach, describe, expect, it, vi } from "vitest";+import { cellId, variableName } from "@/__tests__/branded";+import {+ type DataSourceConnection,+ dataSourceConnectionsAtom,+} from "@/core/datasets/data-source-connections";+import { type ConnectionName, DUCKDB_ENGINE } from "@/core/datasets/engines";+import { datasetsAtom } from "@/core/datasets/state";+import type { QualifiedColumn } from "@/core/datasets/types";+import type { DataTable } from "@/core/kernel/messages";+import { store } from "@/core/state/jotai";+import { storageAtom } from "@/core/storage/state";+import type { StorageNamespace } from "@/core/storage/types";+import { variablesAtom } from "@/core/variables/state";+import type { Variables } from "@/core/variables/types";+import { Logger } from "@/utils/Logger";+import { getLensEntities } from "../entities";++const CELL = cellId("cell1");+const OTHER_CELL = cellId("other-cell");++const table = (name: string): DataTable => ({+ name,+ source: "memory",+ source_type: "local",+ num_rows: 1,+ num_columns: 1,+ columns: [],+ variable_name: variableName(name),+});++const namespace = (name: string): StorageNamespace => ({+ name: variableName(name),+ displayName: name,+ protocol: "s3",+ rootPath: `s3://${name}`,+ backendType: "obstore",+ storageEntries: [],+});++const connection = (name: string): DataSourceConnection => ({+ name: name as ConnectionName,+ source: "postgres",+ dialect: "postgresql",+ display_name: name,+ databases: [],+});++function seedStore(opts: {+ tables?: DataTable[];+ namespaces?: StorageNamespace[];+ connections?: DataSourceConnection[];+ variables?: Variables;+}) {+ store.set(datasetsAtom, {+ tables: opts.tables ?? [],+ expandedTables: new Set<string>(),+ expandedColumns: new Set<QualifiedColumn>(),+ columnsPreviews: new Map(),+ });+ store.set(storageAtom, {+ namespaces: opts.namespaces ?? [],+ entriesByPath: new Map(),+ pageMetadataByPath: new Map(),+ });+ store.set(dataSourceConnectionsAtom, {+ latestEngineSelected: DUCKDB_ENGINE,+ connectionsMap: new Map((opts.connections ?? []).map((c) => [c.name, c])),+ });+ store.set(variablesAtom, opts.variables ?? {});+}++describe("getLensEntities", () => {+ beforeEach(() => {+ seedStore({});+ vi.restoreAllMocks();+ });++ it("returns an empty map when there are no entities", () => {+ expect(getLensEntities(CELL)).toEqual(new Map());+ });++ it("includes tables, connections, and buckets declared in the cell", () => {+ seedStore({+ tables: [table("df")],+ connections: [connection("engine")],+ namespaces: [namespace("bucket")],+ });++ const entities = getLensEntities(CELL);+ expect(entities).toEqual(+ new Map([+ ["df", "table"],+ ["engine", "connection"],+ ["bucket", "bucket"],+ ]),+ );+ });++ it("excludes the internal DuckDB engine from connections", () => {+ seedStore({ connections: [connection(DUCKDB_ENGINE)] });+ expect(getLensEntities(CELL)).toEqual(new Map());+ });++ it("excludes entities declared by a different cell", () => {+ seedStore({+ tables: [table("df")],+ variables: {+ [variableName("df")]: {+ name: variableName("df"),+ declaredBy: [OTHER_CELL],+ usedBy: [],+ },+ },+ });++ expect(getLensEntities(CELL)).toEqual(new Map());+ });++ it("is permissive when the kernel hasn't reported the variable yet", () => {+ // No entry in `variablesAtom` for "df" at all.+ seedStore({ tables: [table("df")] });+ expect(getLensEntities(CELL)).toEqual(new Map([["df", "table"]]));+ });++ it("last-write-wins and logs an error when a name is claimed by more than one kind", () => {+ const errorSpy = vi+ .spyOn(Logger, "error")+ .mockImplementation(() => undefined);+ seedStore({+ tables: [table("shared")],+ connections: [connection("shared")],+ });++ const entities = getLensEntities(CELL);++ expect(entities.get("shared")).toBe("connection");+ expect(errorSpy).toHaveBeenCalledExactlyOnceWith(+ expect.stringContaining("shared"),+ );+ });++ it("does not log when the same name repeats with the same kind", () => {+ const errorSpy = vi+ .spyOn(Logger, "error")+ .mockImplementation(() => undefined);+ seedStore({ tables: [table("df"), table("df")] });++ const entities = getLensEntities(CELL);++ expect(entities.get("df")).toBe("table");+ expect(errorSpy).not.toHaveBeenCalled();+ });++ it("shares the underlying entity map across cells instead of rebuilding it per call", () => {+ // Regression test: the table/connection/namespace scan (and its+ // collision logging) must run once and be reused by every cell, not+ // once per `getLensEntities` call.+ const errorSpy = vi+ .spyOn(Logger, "error")+ .mockImplementation(() => undefined);+ seedStore({+ tables: [table("shared")],+ connections: [connection("shared")],+ });++ getLensEntities(CELL);+ getLensEntities(OTHER_CELL);+ getLensEntities(CELL);++ expect(errorSpy).toHaveBeenCalledTimes(1);+ });+});diff --git a/frontend/src/core/codemirror/code-lens/__tests__/extension.test.ts b/frontend/src/core/codemirror/code-lens/__tests__/extension.test.tsnew file mode 100644index 0000000000..ddedb0d996--- /dev/null+++ b/frontend/src/core/codemirror/code-lens/__tests__/extension.test.ts@@ -0,0 +1,325 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { python } from "@codemirror/lang-python";+import { EditorState } from "@codemirror/state";+import { EditorView } from "@codemirror/view";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { cellId, variableName } from "@/__tests__/branded";+import { languageAdapterState } from "@/core/codemirror/language/extension";+import { LanguageAdapters } from "@/core/codemirror/language/LanguageAdapters";+import type { ExperimentalFeatures } from "@/core/config/feature-flag";+import { getFeatureFlag } from "@/core/config/feature-flag";+import {+ type DataSourceConnection,+ dataSourceConnectionsAtom,+} from "@/core/datasets/data-source-connections";+import { type ConnectionName, DUCKDB_ENGINE } from "@/core/datasets/engines";+import { datasetsAtom } from "@/core/datasets/state";+import type { QualifiedColumn } from "@/core/datasets/types";+import type { DataTable } from "@/core/kernel/messages";+import { store } from "@/core/state/jotai";+import { storageAtom } from "@/core/storage/state";+import type { StorageNamespace } from "@/core/storage/types";+import { variablesAtom } from "@/core/variables/state";+import type { Variables } from "@/core/variables/types";+import { openLensTarget } from "../actions";+import { CODE_LENS_HOVER_DELAY_MS, codeLensBundle } from "../extension";+import { mountLensPopover } from "../popover";++vi.mock("@/core/config/feature-flag", () => ({+ getFeatureFlag: vi.fn(),+}));++vi.mock("../actions", () => ({+ openLensTarget: vi.fn(),+}));++vi.mock("../popover", () => ({+ mountLensPopover: vi.fn(() => vi.fn()),+}));++function mockFlags(flags: Partial<ExperimentalFeatures>) {+ vi.mocked(getFeatureFlag).mockImplementation((flag) => flags[flag] ?? false);+}++const DF_TABLE: DataTable = {+ name: "df",+ source: "memory",+ source_type: "local",+ num_rows: 1,+ num_columns: 1,+ columns: [],+ variable_name: variableName("df"),+};++const BUCKET_NAMESPACE: StorageNamespace = {+ name: variableName("bucket"),+ displayName: "bucket",+ protocol: "s3",+ rootPath: "s3://bucket",+ backendType: "obstore",+ storageEntries: [],+};++const ENGINE_CONNECTION: DataSourceConnection = {+ name: "engine" as ConnectionName,+ source: "postgres",+ dialect: "postgresql",+ display_name: "engine (postgres)",+ databases: [],+};++function seedStore(opts: {+ tables?: DataTable[];+ namespaces?: StorageNamespace[];+ connections?: DataSourceConnection[];+ variables?: Variables;+}) {+ store.set(datasetsAtom, {+ tables: opts.tables ?? [],+ expandedTables: new Set<string>(),+ expandedColumns: new Set<QualifiedColumn>(),+ columnsPreviews: new Map(),+ });+ store.set(storageAtom, {+ namespaces: opts.namespaces ?? [],+ entriesByPath: new Map(),+ pageMetadataByPath: new Map(),+ });+ store.set(dataSourceConnectionsAtom, {+ latestEngineSelected: DUCKDB_ENGINE,+ connectionsMap: new Map(+ (opts.connections ?? []).map((connection) => [+ connection.name,+ connection,+ ]),+ ),+ });+ store.set(variablesAtom, opts.variables ?? {});+}++describe("codeLensBundle", () => {+ let view: EditorView | null = null;++ beforeEach(() => {+ vi.useFakeTimers();+ mockFlags({ editor_code_lens: true, cache_panel: true });+ seedStore({});+ });++ afterEach(() => {+ if (view) {+ view.destroy();+ view = null;+ }+ document.body.innerHTML = "";+ vi.useRealTimers();+ vi.clearAllMocks();+ });++ async function mount(+ code: string,+ language: "python" | "sql" | "markdown" = "python",+ ): Promise<EditorView> {+ const state = EditorState.create({+ doc: code,+ extensions: [+ python(),+ languageAdapterState.init(() => LanguageAdapters[language]),+ codeLensBundle(cellId("cell1")),+ ],+ });+ view = new EditorView({ state, parent: document.body });+ // Fire the debounced analysis, then flush the deferred dispatch+ vi.advanceTimersByTime(300);+ await Promise.resolve();+ view.dispatch({});+ return view;+ }++ function lenses(v: EditorView): HTMLElement[] {+ return [...v.dom.querySelectorAll<HTMLElement>(".mo-code-lens")];+ }++ it("returns an empty extension when the flag is off", () => {+ mockFlags({ editor_code_lens: false });+ expect(codeLensBundle(cellId("cell1"))).toEqual([]);+ });++ it("renders a lens at a dataframe declaration", async () => {+ seedStore({ tables: [DF_TABLE] });+ const v = await mount("df = load()\nx = 1");++ const found = lenses(v);+ expect(found).toHaveLength(1);+ expect(found[0].getAttribute("aria-label")).toBe("Open in data sources");+ // The native tooltip is replaced by the hover popover+ expect(found[0].getAttribute("title")).toBeNull();+ });++ it("opens the datasources panel on click", async () => {+ seedStore({ tables: [DF_TABLE] });+ const v = await mount("df = load()");++ lenses(v)[0].dispatchEvent(new MouseEvent("click", { bubbles: true }));++ expect(openLensTarget).toHaveBeenCalledWith("table");+ });++ it("is keyboard focusable and activatable", async () => {+ seedStore({ tables: [DF_TABLE] });+ const v = await mount("df = load()");+ const lens = lenses(v)[0];++ expect(lens.getAttribute("role")).toBe("button");+ expect(lens.tabIndex).toBe(0);++ lens.dispatchEvent(+ new KeyboardEvent("keydown", { key: "Enter", bubbles: true }),+ );+ expect(openLensTarget).toHaveBeenCalledWith("table");++ lens.dispatchEvent(+ new KeyboardEvent("keydown", { key: " ", bubbles: true }),+ );+ expect(openLensTarget).toHaveBeenCalledTimes(2);+ });++ it("renders a lens at a bucket declaration", async () => {+ seedStore({ namespaces: [BUCKET_NAMESPACE] });+ const v = await mount("bucket = get_bucket()");++ const found = lenses(v);+ expect(found).toHaveLength(1);+ expect(found[0].getAttribute("aria-label")).toBe("Open in remote storage");++ found[0].dispatchEvent(new MouseEvent("click", { bubbles: true }));+ expect(openLensTarget).toHaveBeenCalledWith("bucket");+ });++ it("renders a lens at a connection declaration", async () => {+ seedStore({ connections: [ENGINE_CONNECTION] });+ const v = await mount("engine = create_engine()");++ const found = lenses(v);+ expect(found).toHaveLength(1);+ expect(found[0].getAttribute("aria-label")).toBe("Open in data sources");++ found[0].dispatchEvent(new MouseEvent("click", { bubbles: true }));+ expect(openLensTarget).toHaveBeenCalledWith("connection");+ });++ it("renders a lens at mo.cache and mo.persistent_cache sites", async () => {+ const v = await mount(+ '@mo.cache\ndef f():\n return 1\n\nwith mo.persistent_cache("k"):\n pass',+ );++ const found = lenses(v);+ expect(found).toHaveLength(2);+ expect(found[0].getAttribute("aria-label")).toBe("Open cache panel");++ found[0].dispatchEvent(new MouseEvent("click", { bubbles: true }));+ expect(openLensTarget).toHaveBeenCalledWith("cache");+ });++ it("shows a popover on hover and hides it on leave", async () => {+ seedStore({ tables: [DF_TABLE] });+ const v = await mount("df = load()");+ const lens = lenses(v)[0];++ lens.dispatchEvent(new MouseEvent("mouseenter"));+ vi.advanceTimersByTime(CODE_LENS_HOVER_DELAY_MS);++ expect(v.dom.querySelector(".mo-cm-tooltip")).not.toBeNull();+ expect(mountLensPopover).toHaveBeenCalledWith(+ expect.any(HTMLElement),+ expect.objectContaining({ kind: "table", name: "df" }),+ );++ lens.dispatchEvent(new MouseEvent("mouseleave"));+ expect(v.dom.querySelector(".mo-cm-tooltip")).toBeNull();+ });++ it("does not show a popover before the hover delay", async () => {+ seedStore({ tables: [DF_TABLE] });+ const v = await mount("df = load()");+ const lens = lenses(v)[0];++ lens.dispatchEvent(new MouseEvent("mouseenter"));+ vi.advanceTimersByTime(CODE_LENS_HOVER_DELAY_MS - 100);+ lens.dispatchEvent(new MouseEvent("mouseleave"));+ vi.advanceTimersByTime(CODE_LENS_HOVER_DELAY_MS);++ expect(v.dom.querySelector(".mo-cm-tooltip")).toBeNull();+ });++ it("passes cache context to the popover", async () => {+ const v = await mount(+ '@mo.cache\ndef add(a, b):\n return a + b\n\nwith mo.persistent_cache("k"):\n pass',+ );+ const [decoratorLens, withLens] = lenses(v);++ decoratorLens.dispatchEvent(new MouseEvent("mouseenter"));+ vi.advanceTimersByTime(CODE_LENS_HOVER_DELAY_MS);+ expect(mountLensPopover).toHaveBeenCalledWith(+ expect.any(HTMLElement),+ expect.objectContaining({+ kind: "cache",+ cache: { boundName: "add", cacheName: null },+ }),+ );++ decoratorLens.dispatchEvent(new MouseEvent("mouseleave"));+ withLens.dispatchEvent(new MouseEvent("mouseenter"));+ vi.advanceTimersByTime(CODE_LENS_HOVER_DELAY_MS);+ expect(mountLensPopover).toHaveBeenCalledWith(+ expect.any(HTMLElement),+ expect.objectContaining({+ kind: "cache",+ cache: { boundName: null, cacheName: "k" },+ }),+ );+ });++ it.each(["sql", "markdown"] as const)(+ "does not render lenses in %s cells",+ async (language) => {+ // A `mo.cache` inside a SQL string (or markdown) must not get an icon.+ seedStore({ tables: [DF_TABLE] });+ const v = await mount("df = load()\nmo.cache(f)", language);++ expect(lenses(v)).toHaveLength(0);+ },+ );++ it("does not render cache lenses when the cache panel is disabled", async () => {+ mockFlags({ editor_code_lens: true, cache_panel: false });+ const v = await mount("@mo.cache\ndef f():\n return 1");++ expect(lenses(v)).toHaveLength(0);+ });++ it("only decorates the declaring cell", async () => {+ const dfName = variableName("df");+ seedStore({+ tables: [DF_TABLE],+ variables: {+ [dfName]: {+ name: dfName,+ declaredBy: [cellId("other-cell")],+ usedBy: [cellId("cell1")],+ },+ },+ });+ const v = await mount("df = load()");++ expect(lenses(v)).toHaveLength(0);+ });++ it("decorates only the declaration site, not later references", async () => {+ seedStore({ tables: [DF_TABLE] });+ const v = await mount("df = load()\ndf.head()");++ expect(lenses(v)).toHaveLength(1);+ });+});diff --git a/frontend/src/core/codemirror/code-lens/__tests__/perf.test.ts b/frontend/src/core/codemirror/code-lens/__tests__/perf.test.tsnew file mode 100644index 0000000000..e627a22d3b--- /dev/null+++ b/frontend/src/core/codemirror/code-lens/__tests__/perf.test.ts@@ -0,0 +1,121 @@+/* Copyright 2026 Marimo. All rights reserved. */++/**+ * Regression guards for code-lens hot paths: assert wall time stays within a+ * generous budget for a large, synthetic notebook.+ */++import { python } from "@codemirror/lang-python";+import { EditorState } from "@codemirror/state";+import { describe, expect, it } from "vitest";+import { cellId, variableName } from "@/__tests__/branded";+import type { CellId } from "@/core/cells/ids";+import { dataSourceConnectionsAtom } from "@/core/datasets/data-source-connections";+import { DUCKDB_ENGINE } from "@/core/datasets/engines";+import { datasetsAtom } from "@/core/datasets/state";+import type { QualifiedColumn } from "@/core/datasets/types";+import type { DataTable } from "@/core/kernel/messages";+import { store } from "@/core/state/jotai";+import { storageAtom } from "@/core/storage/state";+import { variablesAtom } from "@/core/variables/state";+import type { Variables } from "@/core/variables/types";+import { findCacheSites, findDeclarationSites } from "../analyzer";+import { getLensEntities } from "../entities";++function pythonState(code: string): EditorState {+ return EditorState.create({ doc: code, extensions: [python()] });+}++describe("code-lens performance", () => {+ it("getLensEntities stays fast across many cells in a large notebook", () => {+ const DATASOURCE_COUNT = 2000;+ const CELL_COUNT = 1000;++ const tables: DataTable[] = [];+ const variables: Variables = {};+ for (let i = 0; i < DATASOURCE_COUNT; i++) {+ const name = variableName(`table_${i}`);+ tables.push({+ name,+ source: "memory",+ source_type: "local",+ num_rows: 1,+ num_columns: 1,+ columns: [],+ variable_name: name,+ });+ // Every datasource is owned by a distinct cell, like a real notebook.+ variables[name] = {+ name,+ declaredBy: [cellId(`owner-${i}`)],+ usedBy: [],+ };+ }+ store.set(datasetsAtom, {+ tables,+ expandedTables: new Set<string>(),+ expandedColumns: new Set<QualifiedColumn>(),+ columnsPreviews: new Map(),+ });+ store.set(storageAtom, {+ namespaces: [],+ entriesByPath: new Map(),+ pageMetadataByPath: new Map(),+ });+ store.set(dataSourceConnectionsAtom, {+ latestEngineSelected: DUCKDB_ENGINE,+ connectionsMap: new Map(),+ });+ store.set(variablesAtom, variables);++ const cellIds: CellId[] = Array.from({ length: CELL_COUNT }, (_, i) =>+ cellId(`cell-${i}`),+ );++ const start = performance.now();+ for (const id of cellIds) {+ getLensEntities(id);+ }+ const elapsed = performance.now() - start;++ // Rescanning all 2000 datasources per cell (instead of an O(1) lookup+ // into a precomputed per-cell index) would take on the order of seconds+ // here; 200ms leaves generous headroom for slow CI while still catching+ // that kind of regression.+ expect(elapsed).toBeLessThan(200);+ });++ it("findCacheSites stays fast for a large cell, valid or not", () => {+ const lines: string[] = [];+ for (let i = 0; i < 500; i++) {+ lines.push(`@mo.cache`, `def fn_${i}(x):`, ` return x + ${i}`, "");+ }+ const validCode = lines.join("\n");+ // Trailing unclosed paren makes the whole tree unparsable, mimicking a+ // cell mid-edit — this must bail out quickly rather than scanning anyway.+ const brokenCode = `${validCode}\ndf = (`;++ const start = performance.now();+ findCacheSites(pythonState(validCode));+ findCacheSites(pythonState(brokenCode));+ const elapsed = performance.now() - start;++ expect(elapsed).toBeLessThan(200);+ });++ it("findDeclarationSites stays fast for a large cell", () => {+ const lines: string[] = [];+ const names = new Set<string>();+ for (let i = 0; i < 2000; i++) {+ lines.push(`var_${i} = compute_${i}()`);+ names.add(`var_${i}`);+ }+ const state = pythonState(lines.join("\n"));++ const start = performance.now();+ findDeclarationSites({ state, names });+ const elapsed = performance.now() - start;++ expect(elapsed).toBeLessThan(200);+ });+});diff --git a/frontend/src/core/codemirror/code-lens/__tests__/popover.test.ts b/frontend/src/core/codemirror/code-lens/__tests__/popover.test.tsnew file mode 100644index 0000000000..f7f67a369d--- /dev/null+++ b/frontend/src/core/codemirror/code-lens/__tests__/popover.test.ts@@ -0,0 +1,93 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { act } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { CodeLensSpec } from "../entities";++// Stable mock reference so every (re)import of popover.tsx after+// vi.resetModules() sees the same spy — the module-level fetch-throttle+// state in popover.tsx (`lastCacheInfoFetchAt`) needs to start fresh per+// test, which requires resetting the whole module, not just the mock.+const { getCacheInfoMock } = vi.hoisted(() => ({+ getCacheInfoMock: vi.fn().mockResolvedValue(null),+}));++vi.mock("@/core/network/requests", () => ({+ getRequestClient: () => ({ getCacheInfo: getCacheInfoMock }),+}));++const CACHE_SPEC: CodeLensSpec = {+ pos: 0,+ kind: "cache",+ name: "my_cache",+ // `boundName: null` means the popover has no per-cache stats to fall back+ // on, so it always attempts the notebook-wide `getCacheInfo` fetch.+ cache: { boundName: null, cacheName: "my_cache" },+};++describe("CachePopover getCacheInfo throttling", () => {+ let mountLensPopover: typeof import("../popover").mountLensPopover;+ let now: number;++ beforeEach(async () => {+ vi.resetModules();+ getCacheInfoMock.mockClear();+ getCacheInfoMock.mockResolvedValue(null);+ ({ mountLensPopover } = await import("../popover"));+ // Control `Date.now()` directly (rather than `vi.useFakeTimers()`)+ // so React's own scheduler — which effect-flushing inside `act()`+ // depends on — keeps using real timers.+ now = 0;+ vi.spyOn(Date, "now").mockImplementation(() => now);+ });++ afterEach(() => {+ document.body.innerHTML = "";+ vi.restoreAllMocks();+ });++ function mount() {+ const dom = document.createElement("div");+ document.body.append(dom);+ let dispose: () => void;+ act(() => {+ dispose = mountLensPopover(dom, CACHE_SPEC);+ });+ return () => act(() => dispose());+ }++ it("does not refetch on every hover, only after the throttle interval elapses", () => {+ const disposeFirst = mount();+ expect(getCacheInfoMock).toHaveBeenCalledTimes(1);+ disposeFirst();++ // Hovering again shortly after should reuse whatever is already in+ // flight/cached rather than firing a second request.+ const disposeSecond = mount();+ expect(getCacheInfoMock).toHaveBeenCalledTimes(1);+ disposeSecond();++ now += 5001;++ const disposeThird = mount();+ expect(getCacheInfoMock).toHaveBeenCalledTimes(2);+ disposeThird();+ });++ it("allows an immediate retry after a failed fetch instead of waiting out the interval", async () => {+ getCacheInfoMock.mockRejectedValueOnce(new Error("kernel not ready"));++ const disposeFirst = mount();+ expect(getCacheInfoMock).toHaveBeenCalledTimes(1);+ // Flush the microtask queue so the effect's `.catch()` runs and resets+ // the throttle before the next hover.+ await act(async () => {+ await Promise.resolve();+ });+ disposeFirst();++ const disposeSecond = mount();+ expect(getCacheInfoMock).toHaveBeenCalledTimes(2);+ disposeSecond();+ });+});diff --git a/frontend/src/core/codemirror/code-lens/actions.ts b/frontend/src/core/codemirror/code-lens/actions.tsnew file mode 100644index 0000000000..59d5befbef--- /dev/null+++ b/frontend/src/core/codemirror/code-lens/actions.ts@@ -0,0 +1,33 @@+/* Copyright 2026 Marimo. All rights reserved. */++import {+ expandAccordionSection,+ fileExplorerPanelAtom,+ sessionPanelAtom,+} from "@/components/editor/chrome/panels/panel-accordion-state";+import { openPanel } from "@/components/editor/chrome/state";+import { assertNever } from "@/utils/assertNever";+import type { CodeLensKind } from "./entities";++/**+ * Opens the panel associated with a code lens target, expanding the accordion+ * section that holds it.+ */+export function openLensTarget(kind: CodeLensKind): void {+ switch (kind) {+ case "table":+ case "connection":+ openPanel("variables");+ expandAccordionSection(sessionPanelAtom, "datasources");+ return;+ case "bucket":+ openPanel("files");+ expandAccordionSection(fileExplorerPanelAtom, "remote-storage");+ return;+ case "cache":+ openPanel("cache");+ return;+ default:+ assertNever(kind);+ }+}diff --git a/frontend/src/core/codemirror/code-lens/analyzer.ts b/frontend/src/core/codemirror/code-lens/analyzer.tsnew file mode 100644index 0000000000..254d6518ec--- /dev/null+++ b/frontend/src/core/codemirror/code-lens/analyzer.ts@@ -0,0 +1,284 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { syntaxTree } from "@codemirror/language";+import type { EditorState } from "@codemirror/state";+import type { SyntaxNode, Tree } from "@lezer/common";+import {+ NON_CODE_NODES,+ PyKeyword,+ PyNode,+ SCOPE_CREATING_NODES,+} from "../python-node-names";+import { hasSyntaxErrors } from "../reactive-references/analyzer";++export interface CodeLensTarget {+ from: number;+ to: number;+ name: string;+}++/**+ * Finds the first module-scope assignment site for each name in `names`.+ */+export function findDeclarationSites(options: {+ state: EditorState;+ names: ReadonlySet<string>;+}): CodeLensTarget[] {+ const { state, names } = options;+ if (names.size === 0) {+ return [];+ }+ const tree = syntaxTree(state);+ if (!tree || hasSyntaxErrors(tree)) {+ return [];+ }++ const firstSites = new Map<string, CodeLensTarget>();++ const collectTargetNames = (node: SyntaxNode) => {+ if (node.name === PyNode.VariableName) {+ const name = state.doc.sliceString(node.from, node.to);+ if (names.has(name) && !firstSites.has(name)) {+ firstSites.set(name, { from: node.from, to: node.to, name });+ }+ return;+ }+ // Recurse into tuple/list unpacking, e.g. `(a, b) = ...` or `[a, b] = ...`,+ // and parenthesized targets, e.g. `(df) = ...`.+ // Member/subscript targets (`obj.attr = ...`) are not declarations.+ if (+ node.name === PyNode.TupleExpression ||+ node.name === PyNode.ArrayExpression ||+ node.name === PyNode.ParenthesizedExpression+ ) {+ for (let child = node.firstChild; child; child = child.nextSibling) {+ collectTargetNames(child);+ }+ }+ };++ const collectAssignmentTargets = (assign: SyntaxNode) => {+ // Targets are everything before the last AssignOp (handles `a = b = ...`).+ // A bare annotation (`x: int`) has no AssignOp and is skipped.+ let lastAssignOp = -1;+ for (let child = assign.firstChild; child; child = child.nextSibling) {+ if (child.name === PyNode.AssignOp) {+ lastAssignOp = child.from;+ }+ }+ if (lastAssignOp === -1) {+ return;+ }+ for (+ let child = assign.firstChild;+ child && child.from < lastAssignOp;+ child = child.nextSibling+ ) {+ collectTargetNames(child);+ }+ };++ const visit = (node: SyntaxNode) => {+ // Only module-scope assignments count as creation sites; top-level+ // `if`/`for`/`try` bodies are still module scope.+ if (SCOPE_CREATING_NODES.has(node.name)) {+ return;+ }+ if (node.name === PyNode.AssignStatement) {+ collectAssignmentTargets(node);+ return;+ }+ for (let child = node.firstChild; child; child = child.nextSibling) {+ visit(child);+ }+ };+ visit(tree.topNode);++ return [...firstSites.values()];+}++// Note that the cache pattern assumes users `import marimo as mo`.+// This is a common convention for marimo notebooks.+const CACHE_PATTERN = /\bmo\.(?:persistent_cache|cache)\b/g;++export interface CacheSite {+ from: number;+ to: number;+ /**+ * Variable the cache is bound to: the decorated function name+ * (`@mo.cache def f`), the assignment target (`g = mo.cache(f)`), or the+ * `as` binding (`with mo.persistent_cache("k") as c`).+ */+ boundName: string | null;+ /** First string argument, e.g. the persistent_cache name. */+ cacheName: string | null;+}++function stripStringQuotes(text: string): string {+ const match = text.match(/^[A-Za-z]*("""|'''|"|')([\s\S]*)\1$/);+ return match ? match[2] : text;+}++/**+ * Extracts a static cache name from the first positional argument or an+ * explicit `name=` argument. Other string-valued options, such as+ * `hash_type="content"` and `save_path="cache"`, are not cache names.+ */+function findStaticCacheName(+ argList: SyntaxNode | null,+ text: (node: SyntaxNode) => string,+): string | null {+ if (!argList) {+ return null;+ }++ const isArgumentBoundary = (node: SyntaxNode | null) =>+ node?.name === "," || node?.name === ")";++ let firstArgument: SyntaxNode | null = null;+ for (let child = argList.firstChild; child; child = child.nextSibling) {+ if (child.name === "(" || child.name === ")" || child.name === ",") {+ continue;+ }+ firstArgument ??= child;++ if (+ child.name === PyNode.VariableName &&+ text(child) === "name" &&+ child.nextSibling?.name === PyNode.AssignOp+ ) {+ const value = child.nextSibling.nextSibling;+ if (+ value?.name === PyNode.String &&+ isArgumentBoundary(value.nextSibling)+ ) {+ return stripStringQuotes(text(value));+ }+ }+ }++ if (!firstArgument) {+ return null;+ }+ if (+ firstArgument.name === PyNode.String &&+ isArgumentBoundary(firstArgument.nextSibling)+ ) {+ return stripStringQuotes(text(firstArgument));+ }+ return null;+}++/**+ * Resolves a `mo.cache` / `mo.persistent_cache` match into a CacheSite:+ * extends `to` past call arguments (`mo.cache(pin_modules=True)`), so an+ * icon placed at `to` lands after the closing paren, and extracts the bound+ * variable name and the cache-name string argument.+ */+function analyzeCacheSite(+ state: EditorState,+ tree: Tree,+ from: number,+ to: number,+): CacheSite {+ const text = (node: SyntaxNode) => state.doc.sliceString(node.from, node.to);+ const node = tree.resolveInner(from, 1);+ let boundName: string | null = null;+ let argList: SyntaxNode | null = null;+ let end = to;++ // `mo.cache(...)` as an expression wraps in a CallExpression that starts+ // at the match+ let call: SyntaxNode | null = null;+ for (+ let ancestor: SyntaxNode | null = node.parent;+ ancestor && ancestor.from === from;+ ancestor = ancestor.parent+ ) {+ if (ancestor.name === PyNode.CallExpression) {+ call = ancestor;+ break;+ }+ }++ if (call) {+ end = call.to;+ argList = call.getChild(PyNode.ArgList);+ const parent = call.parent;+ if (parent?.name === PyNode.AssignStatement) {+ // `g = mo.cache(f)` — the direct VariableName child is the target+ const target = parent.getChild(PyNode.VariableName);+ boundName = target && target.from < call.from ? text(target) : null;+ } else if (parent?.name === PyNode.WithStatement) {+ // `with mo.persistent_cache("k") as c:` — `as c` follows the call+ let child = parent.firstChild;+ while (child) {+ if (child.from < call.to || child.name === PyKeyword.As) {+ child = child.nextSibling;+ continue;+ }+ if (child.name === PyNode.VariableName) {+ boundName = text(child);+ }+ break;+ }+ }+ } else if (node.parent?.name === PyNode.Decorator) {+ // `@mo.cache(...)` decorators are flat: the ArgList is a direct sibling+ const decorator = node.parent;+ const decoratorArgs = decorator.getChild(PyNode.ArgList);+ if (decoratorArgs?.from === to) {+ argList = decoratorArgs;+ end = decoratorArgs.to;+ }+ // The decorated function's name+ const fn = decorator.parent?.getChild(PyNode.FunctionDefinition);+ const fnName = fn?.getChild(PyNode.VariableName);+ boundName = fnName ? text(fnName) : null;+ }++ const cacheName = findStaticCacheName(argList, text);+ return { from, to: end, boundName, cacheName };+}++/**+ * True when the `mo` at `from` is a standalone module reference (the object of+ * `mo.cache`), not an attribute of something else. This filters out chains+ * like `obj.mo.cache(f)` — where `mo` is a `PropertyName` rather than a+ * `VariableName` — and mentions inside comments or strings.+ */+function isStandaloneMoReference(+ state: EditorState,+ tree: Tree,+ from: number,+): boolean {+ const node = tree.resolveInner(from, 1);+ if (NON_CODE_NODES.has(node.name)) {+ return false;+ }+ // In `obj.mo.cache`, `mo` parses as a `PropertyName`; a standalone `mo`+ // (including whitespace-separated `mo . cache`) parses as a `VariableName`.+ return (+ node.name === PyNode.VariableName &&+ state.doc.sliceString(node.from, node.to) === "mo"+ );+}++/**+ * Finds occurrences of `mo.cache` / `mo.persistent_cache` (as a decorator,+ * call, or context manager) with a simple text match, skipping mentions in+ * comments, strings, and attribute chains (`obj.mo.cache`). `to` extends past+ * call arguments when present.+ */+export function findCacheSites(state: EditorState): CacheSite[] {+ const tree = syntaxTree(state);+ if (!tree || hasSyntaxErrors(tree)) {+ return [];+ }+ return [...state.doc.toString().matchAll(CACHE_PATTERN)]+ .filter((match) => isStandaloneMoReference(state, tree, match.index ?? 0))+ .map((match) => {+ const from = match.index ?? 0;+ return analyzeCacheSite(state, tree, from, from + match[0].length);+ });+}diff --git a/frontend/src/core/codemirror/code-lens/entities.ts b/frontend/src/core/codemirror/code-lens/entities.tsnew file mode 100644index 0000000000..996cdec752--- /dev/null+++ b/frontend/src/core/codemirror/code-lens/entities.ts@@ -0,0 +1,123 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { atom } from "jotai";+import type { CellId } from "@/core/cells/ids";+import { dataConnectionsMapAtom } from "@/core/datasets/data-source-connections";+import { INTERNAL_SQL_ENGINES } from "@/core/datasets/engines";+import { datasetTablesAtom } from "@/core/datasets/state";+import { store } from "@/core/state/jotai";+import { storageNamespacesAtom } from "@/core/storage/state";+import { variablesAtom } from "@/core/variables/state";+import type { VariableName } from "@/core/variables/types";+import { Logger } from "@/utils/Logger";++export type CodeLensKind = "table" | "connection" | "bucket" | "cache";++export interface CodeLensSpec {+ /** Document position the icon is anchored at */+ pos: number;+ kind: CodeLensKind;+ /** Variable name for entities; a stable identity key for cache sites */+ name: string;+ /** Extra context for cache sites */+ cache?: {+ boundName: string | null;+ cacheName: string | null;+ };+}++/**+ * Sets `name` to `kind`, logging (and overwriting) if the name was already+ * claimed by a different kind. This should be rare.+ */+function setEntity(+ entities: Map<string, CodeLensKind>,+ name: string,+ kind: CodeLensKind,+): void {+ const existing = entities.get(name);+ if (existing !== undefined && existing !== kind) {+ Logger.error(+ `[code-lens] "${name}" is claimed by both a ${existing} and a ${kind} entity; keeping ${kind}`,+ );+ }+ entities.set(name, kind);+}++/**+ * All datasource (dataframe/SQL engine) and storage bucket names in the+ * notebook, keyed by name, independent of any particular cell.+ */+const lensEntityKindsAtom = atom((get) => {+ const entities = new Map<string, CodeLensKind>();+ for (const table of get(datasetTablesAtom)) {+ if (table.variable_name) {+ setEntity(entities, table.variable_name, "table");+ }+ }+ for (const name of get(dataConnectionsMapAtom).keys()) {+ if (!INTERNAL_SQL_ENGINES.has(name)) {+ setEntity(entities, name, "connection");+ }+ }+ for (const namespace of get(storageNamespacesAtom)) {+ setEntity(entities, namespace.name, "bucket");+ }+ return entities;+});++interface LensEntitiesByCell {+ byCell: Map<CellId, Map<string, CodeLensKind>>;+ /**+ * Entities the kernel hasn't reported a variable for yet (still executing,+ * or just typed), so they can't be attributed to a declaring cell.+ */+ pending: Map<string, CodeLensKind>;+}++/**+ * Groups `lensEntityKindsAtom` by declaring cell, once per store update.+ * With C cells and T datasource/bucket entities, this turns+ * an O(C x T) per-round cost (every cell re-scanning every entity) into O(T) here.+ */+const lensEntitiesByCellAtom = atom((get): LensEntitiesByCell => {+ const kinds = get(lensEntityKindsAtom);+ const variables = get(variablesAtom);+ const byCell = new Map<CellId, Map<string, CodeLensKind>>();+ const pending = new Map<string, CodeLensKind>();++ for (const [name, kind] of kinds) {+ const variable = variables[name as VariableName];+ if (variable == null) {+ pending.set(name, kind);+ continue;+ }+ for (const declaringCell of variable.declaredBy) {+ let forCell = byCell.get(declaringCell);+ if (!forCell) {+ forCell = new Map();+ byCell.set(declaringCell, forCell);+ }+ forCell.set(name, kind);+ }+ }++ return { byCell, pending };+});++/**+ * Variables declared in `cellId` that are datasources (dataframes and SQL+ * engines) or storage buckets, keyed by variable name.+ */+export function getLensEntities(cellId: CellId): Map<string, CodeLensKind> {+ const { byCell, pending } = store.get(lensEntitiesByCellAtom);+ const entities = new Map(byCell.get(cellId));+ // Be permissive when the kernel hasn't reported a variable yet: any cell+ // could turn out to be the declaring one.+ for (const [name, kind] of pending) {+ if (!entities.has(name)) {+ entities.set(name, kind);+ }+ }+ return entities;+}diff --git a/frontend/src/core/codemirror/code-lens/extension.ts b/frontend/src/core/codemirror/code-lens/extension.tsnew file mode 100644index 0000000000..fec717acbf--- /dev/null+++ b/frontend/src/core/codemirror/code-lens/extension.ts@@ -0,0 +1,298 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { type Extension, StateEffect, StateField } from "@codemirror/state";+import {+ Decoration,+ type DecorationSet,+ EditorView,+ showTooltip,+ type Tooltip,+ ViewPlugin,+ type ViewUpdate,+ WidgetType,+} from "@codemirror/view";+import { type DebouncedFunc, debounce } from "lodash-es";+import type { CellId } from "@/core/cells/ids";+import { getFeatureFlag } from "@/core/config/feature-flag";+import { dataConnectionsMapAtom } from "@/core/datasets/data-source-connections";+import { datasetTablesAtom } from "@/core/datasets/state";+import { store } from "@/core/state/jotai";+import { storageNamespacesAtom } from "@/core/storage/state";+import { variablesAtom } from "@/core/variables/state";+import { languageAdapterState } from "../language/extension";+import { openLensTarget } from "./actions";+import { findCacheSites, findDeclarationSites } from "./analyzer";+import { type CodeLensSpec, getLensEntities } from "./entities";+import { LENS_ICONS, LENS_TOOLTIPS } from "./icons";+import { mountLensPopover } from "./popover";++// Delay (in ms) before showing the hover popover, matching the app's+// tooltip delay+export const CODE_LENS_HOVER_DELAY_MS = 400;++const setCodeLenses = StateEffect.define<CodeLensSpec[]>();+const setHoveredLens = StateEffect.define<CodeLensSpec | null>();++// Pending hover timers, keyed by widget element so `destroy` can cancel them+const HOVER_TIMERS = new WeakMap<HTMLElement, number>();++class CodeLensWidget extends WidgetType {+ private readonly spec: CodeLensSpec;++ constructor(spec: CodeLensSpec) {+ super();+ this.spec = spec;+ }++ override eq(other: CodeLensWidget): boolean {+ return (+ // `pos` is captured by the DOM hover/click handlers, so a reused widget+ // whose anchor moved must not be treated as equal+ this.spec.pos === other.spec.pos &&+ this.spec.kind === other.spec.kind &&+ this.spec.name === other.spec.name &&+ this.spec.cache?.boundName === other.spec.cache?.boundName &&+ this.spec.cache?.cacheName === other.spec.cache?.cacheName+ );+ }++ override toDOM(view: EditorView): HTMLElement {+ const { spec } = this;+ const element = document.createElement("span");+ element.className = "mo-code-lens";+ element.setAttribute("role", "button");+ // Focusable so the action is reachable and activatable by keyboard+ element.tabIndex = 0;+ // No `title`: the native tooltip is replaced by the hover popover+ element.setAttribute("aria-label", LENS_TOOLTIPS[spec.kind]);+ // Static, trusted markup (see icons.ts)+ element.innerHTML = LENS_ICONS[spec.kind];+ const hidePopover = () => {+ window.clearTimeout(HOVER_TIMERS.get(element));+ HOVER_TIMERS.delete(element);+ if (view.state.field(codeLensHoverField, false)) {+ view.dispatch({ effects: setHoveredLens.of(null) });+ }+ };+ element.onmouseenter = () => {+ const timer = window.setTimeout(() => {+ view.dispatch({ effects: setHoveredLens.of(spec) });+ }, CODE_LENS_HOVER_DELAY_MS);+ HOVER_TIMERS.set(element, timer);+ };+ element.onmouseleave = hidePopover;+ element.onmousemove = (event) => {+ // Keep the editor's built-in hover documentation tooltip from also+ // triggering over the icon+ event.stopPropagation();+ };+ element.onmousedown = (event) => {+ // Don't move the cursor or steal focus from the editor+ event.preventDefault();+ event.stopPropagation();+ };+ element.onclick = (event) => {+ event.preventDefault();+ event.stopPropagation();+ hidePopover();+ openLensTarget(spec.kind);+ };+ element.onkeydown = (event) => {+ if (event.key === "Enter" || event.key === " ") {+ event.preventDefault();+ event.stopPropagation();+ hidePopover();+ openLensTarget(spec.kind);+ }+ };+ return element;+ }++ override destroy(dom: HTMLElement): void {+ window.clearTimeout(HOVER_TIMERS.get(dom));+ HOVER_TIMERS.delete(dom);+ }++ override ignoreEvent(): boolean {+ // The widget handles its own events+ return true;+ }+}++function createLensTooltip(spec: CodeLensSpec): Tooltip {+ return {+ pos: spec.pos,+ above: true,+ create: () => {+ const dom = document.createElement("div");+ // Same chrome as the SQL completion/hover popovers+ dom.classList.add("mo-cm-tooltip", "docs-documentation");+ const unmount = mountLensPopover(dom, spec);+ return { dom, resize: false, destroy: unmount };+ },+ };+}++const codeLensHoverField = StateField.define<Tooltip | null>({+ create() {+ return null;+ },+ update(tooltip, tr) {+ for (const effect of tr.effects) {+ if (effect.is(setHoveredLens)) {+ return effect.value ? createLensTooltip(effect.value) : null;+ }+ if (effect.is(setCodeLenses)) {+ // Lenses were rebuilt; the hovered widget may be gone+ return null;+ }+ }+ return tr.docChanged ? null : tooltip;+ },+ provide: (field) => showTooltip.from(field),+});++const codeLensField = StateField.define<DecorationSet>({+ create() {+ return Decoration.none;+ },+ update(decorations, tr) {+ decorations = decorations.map(tr.changes);+ for (const effect of tr.effects) {+ if (effect.is(setCodeLenses)) {+ decorations = Decoration.set(+ effect.value.map((spec) =>+ Decoration.widget({+ widget: new CodeLensWidget(spec),+ side: 1,+ }).range(spec.pos),+ ),+ // Variable and cache lenses are collected separately, so sort+ true,+ );+ }+ }+ return decorations;+ },+ provide: (field) => EditorView.decorations.from(field),+});++/**+ * Plugin that keeps code lens decorations in sync with the document and the+ * datasource/bucket state.+ */+class CodeLensPlugin {+ private readonly view: EditorView;+ private readonly cellId: CellId;+ private readonly includeCache: boolean;+ private readonly unsubscribes: Array<() => void>;++ // Delay (in ms) before recomputing lenses after user changes or store updates+ private readonly debounceMs = 300;+ private readonly scheduleUpdate: DebouncedFunc<() => void>;++ constructor(view: EditorView, cellId: CellId, includeCache: boolean) {+ this.view = view;+ this.cellId = cellId;+ this.includeCache = includeCache;+ this.scheduleUpdate = debounce(() => this.run(), this.debounceMs);+ const onStoreChange = () => this.scheduleUpdate();+ this.unsubscribes = [+ store.sub(datasetTablesAtom, onStoreChange),+ store.sub(dataConnectionsMapAtom, onStoreChange),+ store.sub(storageNamespacesAtom, onStoreChange),+ // The declaring-cell filter depends on variables+ store.sub(variablesAtom, onStoreChange),+ ];+ this.scheduleUpdate();+ }++ update(update: ViewUpdate) {+ // Recompute on edits, and when the cell's language changes (e.g. Python ->+ // SQL) so stale Python-only icons are cleared even if the text is unchanged+ const adapterChanged =+ update.startState.field(languageAdapterState, false)?.type !==+ update.state.field(languageAdapterState, false)?.type;+ if (update.docChanged || adapterChanged) {+ this.scheduleUpdate();+ }+ }++ destroy() {+ this.scheduleUpdate.cancel();+ for (const unsubscribe of this.unsubscribes) {+ unsubscribe();+ }+ }++ private run() {+ const { state } = this.view;+ const lenses: CodeLensSpec[] = [];++ // Only python cells: SQL/markdown docs aren't python, and a cache icon+ // inside a SQL string would be misleading.+ const adapterType = state.field(languageAdapterState, false)?.type;+ if (adapterType == null || adapterType === "python") {+ const entities = getLensEntities(this.cellId);+ const targets = findDeclarationSites({+ state,+ names: new Set(entities.keys()),+ });+ for (const target of targets) {+ const kind = entities.get(target.name);+ if (kind) {+ lenses.push({ pos: target.to, kind, name: target.name });+ }+ }+ if (this.includeCache) {+ for (const site of findCacheSites(state)) {+ lenses.push({+ pos: site.to,+ kind: "cache",+ name: `cache:${site.from}`,+ cache: { boundName: site.boundName, cacheName: site.cacheName },+ });+ }+ }+ }++ // Defer dispatch to avoid triggering during an editor update cycle+ queueMicrotask(() => {+ this.view.dispatch({ effects: setCodeLenses.of(lenses) });+ });+ }+}++const codeLensTheme = EditorView.baseTheme({+ ".mo-code-lens": {+ display: "inline-flex",+ verticalAlign: "baseline",+ // Optically center the icon against the text+ transform: "translateY(1.5px)",+ marginLeft: "0.3em",+ cursor: "pointer",+ opacity: "0.5",+ },+ ".mo-code-lens:hover": {+ opacity: "1",+ },+});++/**+ * Inline icons linking datasource/bucket variables and `mo.cache` /+ * `mo.persistent_cache` calls to their panels.+ * Gated behind the `editor_code_lens` feature flag.+ */+export function codeLensBundle(cellId: CellId): Extension {+ if (!getFeatureFlag("editor_code_lens")) {+ return [];+ }+ return [+ codeLensField,+ codeLensHoverField,+ ViewPlugin.define(+ (view) => new CodeLensPlugin(view, cellId, getFeatureFlag("cache_panel")),+ ),+ codeLensTheme,+ ];+}diff --git a/frontend/src/core/codemirror/code-lens/icons.ts b/frontend/src/core/codemirror/code-lens/icons.tsnew file mode 100644index 0000000000..234a0da70b--- /dev/null+++ b/frontend/src/core/codemirror/code-lens/icons.ts@@ -0,0 +1,36 @@+/* Copyright 2026 Marimo. All rights reserved. */++import type { CodeLensKind } from "./entities";++// Inline SVG markup mirroring the lucide icons used by the target panels:+// table-2 (dataframes), database (SQL engines), hard-drive (Remote storage),+// database-zap (Cache).+const svg = (contents: string) =>+ `<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">${contents}</svg>`;++const TABLE = svg(+ '<path d="M9 3H5a2 2 0 0 0-2 2v4m6-6h10a2 2 0 0 1 2 2v4M9 3v18m0 0h10a2 2 0 0 0 2-2V9M9 21H5a2 2 0 0 1-2-2V9m0 0h18"/>',+);+const DATABASE = svg(+ '<ellipse cx="12" cy="5" rx="9" ry="3"/><path d="M3 5V19A9 3 0 0 0 21 19V5"/><path d="M3 12A9 3 0 0 0 21 12"/>',+);+const HARD_DRIVE = svg(+ '<line x1="22" x2="2" y1="12" y2="12"/><path d="M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z"/><line x1="6" x2="6.01" y1="16" y2="16"/><line x1="10" x2="10.01" y1="16" y2="16"/>',+);+const DATABASE_ZAP = svg(+ '<ellipse cx="12" cy="5" rx="9" ry="3"/><path d="M3 5V19A9 3 0 0 0 15 21.84"/><path d="M21 5V8"/><path d="M21 12L18 17H22L19 22"/><path d="M3 12A9 3 0 0 0 14.59 14.87"/>',+);++export const LENS_ICONS: Record<CodeLensKind, string> = {+ table: TABLE,+ connection: DATABASE,+ bucket: HARD_DRIVE,+ cache: DATABASE_ZAP,+};++export const LENS_TOOLTIPS: Record<CodeLensKind, string> = {+ table: "Open in data sources",+ connection: "Open in data sources",+ bucket: "Open in remote storage",+ cache: "Open cache panel",+};diff --git a/frontend/src/core/codemirror/code-lens/popover.tsx b/frontend/src/core/codemirror/code-lens/popover.tsxnew file mode 100644index 0000000000..e0b14a618c--- /dev/null+++ b/frontend/src/core/codemirror/code-lens/popover.tsx@@ -0,0 +1,240 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { Provider, useAtomValue } from "jotai";+import { DatabaseZapIcon } from "lucide-react";+import type React from "react";+import { useEffect } from "react";+import { createRoot } from "react-dom/client";+import { useLocale } from "react-aria";+import { ProtocolIcon } from "@/components/storage/components";+import { Badge } from "@/components/ui/badge";+import { cacheInfoAtom } from "@/core/cache/requests";+import { dataConnectionsMapAtom } from "@/core/datasets/data-source-connections";+import type { ConnectionName } from "@/core/datasets/engines";+import { datasetTablesAtom } from "@/core/datasets/state";+import { getRequestClient } from "@/core/network/requests";+import { store } from "@/core/state/jotai";+import { storageNamespacesAtom } from "@/core/storage/state";+import { variablesAtom } from "@/core/variables/state";+import type { VariableName } from "@/core/variables/types";+import { assertNever } from "@/utils/assertNever";+import { formatTime } from "@/utils/formatting";+import { prettyNumber } from "@/utils/numbers";+import {+ CONTAINER_STYLES,+ MetadataRow,+ renderDatasourceInfo,+ renderEmptyInfo,+ renderTableInfo,+ SectionHeader,+} from "../language/languages/sql/renderers";+import type { CodeLensSpec } from "./entities";++/**+ * Mounts the hover popover for a code lens into `dom`; returns a dispose+ * function.+ */+export function mountLensPopover(+ dom: HTMLElement,+ spec: CodeLensSpec,+): () => void {+ const root = createRoot(dom);+ root.render(+ <Provider store={store}>+ <LensPopover spec={spec} />+ </Provider>,+ );+ // Defer so tearing the tooltip down from inside a React event (e.g. the+ // icon's click handler) doesn't unmount mid-render+ return () => queueMicrotask(() => root.unmount());+}++const LensPopover: React.FC<{ spec: CodeLensSpec }> = ({ spec }) => {+ switch (spec.kind) {+ case "table":+ return <TablePopover name={spec.name} />;+ case "connection":+ return <ConnectionPopover name={spec.name} />;+ case "bucket":+ return <BucketPopover name={spec.name} />;+ case "cache":+ return (+ <CachePopover+ boundName={spec.cache?.boundName ?? null}+ cacheName={spec.cache?.cacheName ?? null}+ />+ );+ default:+ assertNever(spec.kind);+ }+};++const TablePopover: React.FC<{ name: string }> = ({ name }) => {+ const tables = useAtomValue(datasetTablesAtom);+ const table = tables.find((t) => t.variable_name === name);+ return table ? renderTableInfo(table) : renderEmptyInfo("table");+};++const ConnectionPopover: React.FC<{ name: string }> = ({ name }) => {+ const connections = useAtomValue(dataConnectionsMapAtom);+ const connection = connections.get(name as ConnectionName);+ if (!connection) {+ return renderEmptyInfo("database");+ }+ return renderDatasourceInfo(connection);+};++const BucketPopover: React.FC<{ name: string }> = ({ name }) => {+ const namespaces = useAtomValue(storageNamespacesAtom);+ const namespace = namespaces.find((ns) => ns.name === name);+ if (!namespace) {+ return (+ <div className={CONTAINER_STYLES}>+ <span className="text-xs text-(--slate-11)">+ No storage information available.+ </span>+ </div>+ );+ }+ return (+ <div className={CONTAINER_STYLES}>+ <SectionHeader+ icon={+ <ProtocolIcon protocol={namespace.protocol} className="w-4 h-4" />+ }+ title={namespace.displayName}+ badge={+ <Badge variant="outline" className="text-xs">+ {namespace.protocol}+ </Badge>+ }+ />+ <div className="flex flex-col gap-2 py-2">+ <MetadataRow+ label="Variable"+ value={+ <code className="text-xs bg-(--slate-4) px-1 rounded">+ {namespace.name}+ </code>+ }+ />+ <MetadataRow+ label="Root"+ value={+ <code className="text-xs bg-(--slate-4) px-1 rounded">+ {namespace.rootPath || "(root)"}+ </code>+ }+ />+ <MetadataRow+ label="Backend"+ value={<span className="font-medium">{namespace.backendType}</span>}+ />+ </div>+ </div>+ );+};++// `_cache_call.__repr__` starts with "hits=N misses=N", which survives the+// variable-preview truncation+const CACHE_STATS_PATTERN = /\bhits=(\d+) misses=(\d+)/;++// The popover remounts on every hover (see `mountLensPopover`), so this has+// to live at module scope rather than in component state: it debounces the+// notebook-wide `getCacheInfo` fetch across repeated hovers.+let lastCacheInfoFetchAt: number | null = null;+const CACHE_INFO_REFETCH_INTERVAL_MS = 5000;++function maybeFetchCacheInfo(): void {+ const now = Date.now();+ if (+ lastCacheInfoFetchAt != null &&+ now - lastCacheInfoFetchAt < CACHE_INFO_REFETCH_INTERVAL_MS+ ) {+ return;+ }+ lastCacheInfoFetchAt = now;+ getRequestClient()+ .getCacheInfo()+ .catch(() => {+ // Allow the next hover to retry rather than waiting out the interval.+ lastCacheInfoFetchAt = null;+ });+}++const CachePopover: React.FC<{+ boundName: string | null;+ cacheName: string | null;+}> = ({ boundName, cacheName }) => {+ const { locale } = useLocale();+ const variables = useAtomValue(variablesAtom);+ const cacheInfo = useAtomValue(cacheInfoAtom);++ const variable = boundName ? variables[boundName as VariableName] : undefined;+ const stats = variable?.dataType?.startsWith("_cache_call")+ ? variable.value?.match(CACHE_STATS_PATTERN)+ : undefined;+ const hasLocalStats = Boolean(stats);++ // Only fetch the notebook-wide fallback when there are no per-cache stats+ // to show, and throttle across repeated hovers so mousing over a lens+ // several times in a row doesn't fire a fresh request every time.+ useEffect(() => {+ if (hasLocalStats) {+ return;+ }+ maybeFetchCacheInfo();+ }, [hasLocalStats]);++ return (+ <div className={CONTAINER_STYLES}>+ <SectionHeader+ icon={<DatabaseZapIcon className="w-4 h-4 text-(--amber-9)" />}+ title={cacheName ?? boundName ?? "Cache"}+ />+ {stats ? (+ <div className="flex flex-col gap-2 py-2">+ <MetadataRow+ label="Hits"+ value={+ <span className="font-medium">+ {prettyNumber(Number(stats[1]), locale)}+ </span>+ }+ />+ <MetadataRow+ label="Misses"+ value={+ <span className="font-medium">+ {prettyNumber(Number(stats[2]), locale)}+ </span>+ }+ />+ </div>+ ) : (+ cacheInfo && (+ <div className="flex flex-col gap-2 py-2">+ <span className="text-xs font-medium text-(--slate-11)">+ Notebook-wide+ </span>+ <MetadataRow+ label="Hits"+ value={prettyNumber(cacheInfo.hits, locale)}+ />+ <MetadataRow+ label="Misses"+ value={prettyNumber(cacheInfo.misses, locale)}+ />+ <MetadataRow+ label="Time saved"+ value={formatTime(cacheInfo.time, locale)}+ />+ </div>+ )+ )}+ <div className="pt-2 text-xs text-(--slate-10)">+ Click to open the cache panel+ </div>+ </div>+ );+};diff --git a/frontend/src/core/codemirror/go-to-definition/commands.ts b/frontend/src/core/codemirror/go-to-definition/commands.tsindex 1a435d67b3..e10914de14 100644--- a/frontend/src/core/codemirror/go-to-definition/commands.ts+++ b/frontend/src/core/codemirror/go-to-definition/commands.ts@@ -4,20 +4,13 @@ import { syntaxTree } from "@codemirror/language";import type { EditorState } from "@codemirror/state";import { EditorView } from "@codemirror/view";import type { SyntaxNode, Tree, TreeCursor } from "@lezer/common";+import { PyKeyword, PyNode, SCOPE_CREATING_NODES } from "../python-node-names";import { scrollOwnerCell } from "../utils";-const SCOPE_CREATING_NODES = new Set([- "FunctionDefinition",- "LambdaExpression",- "ArrayComprehensionExpression",- "SetComprehensionExpression",- "DictionaryComprehensionExpression",- "ComprehensionExpression",- "ClassDefinition",+const POSITION_SENSITIVE_SCOPES: ReadonlySet<string> = new Set([+ PyNode.ClassDefinition,]);-const POSITION_SENSITIVE_SCOPES = new Set(["ClassDefinition"]);-interface ScopeContext {id: number;type: string;@@ -65,14 +58,14 @@ function findFirstMatchingVariable(}if (- node.name === "VariableName" &&+ node.name === PyNode.VariableName &&state.doc.sliceString(node.from, node.to) === variableName) {from = node.from;return false;}- if (node.name === "Comment" || node.name === "String") {+ if (node.name === PyNode.Comment || node.name === PyNode.String) {return false;}@@ -92,10 +85,12 @@ function getScopeChain(tree: Tree, usagePosition: number): ScopeContext[] {// Skip ClassDefinition if we've already seen a function/lambda.const inFunctionLikeScope = scopeChain.some((scope) =>- scope.type === "FunctionDefinition" ||- scope.type === "LambdaExpression",+ scope.type === PyNode.FunctionDefinition ||+ scope.type === PyNode.LambdaExpression,);- if (!(inFunctionLikeScope && currentNode.name === "ClassDefinition")) {+ if (+ !(inFunctionLikeScope && currentNode.name === PyNode.ClassDefinition)+ ) {scopeChain.push({id: currentNode.from,type: currentNode.name,@@ -130,30 +125,27 @@ function traverseChildren(function collectMatchingTargets(cursor: TreeCursor,- state: EditorState,- variableName: string,- scopeId: number,- declarations: VariableDeclaration[],+ options: {+ state: EditorState;+ variableName: string;+ scopeId: number;+ declarations: VariableDeclaration[];+ },) {+ const { state, variableName, scopeId, declarations } = options;switch (cursor.name) {- case "VariableName":+ case PyNode.VariableName:if (state.doc.sliceString(cursor.from, cursor.to) === variableName) {addDeclaration(declarations, scopeId, cursor.from);}break;- case "TupleExpression":- case "ArrayExpression": {+ case PyNode.TupleExpression:+ case PyNode.ArrayExpression: {const childCursor = cursor.node.cursor();childCursor.firstChild();do {- collectMatchingTargets(- childCursor,- state,- variableName,- scopeId,- declarations,- );+ collectMatchingTargets(childCursor, options);} while (childCursor.nextSibling());break;}@@ -164,15 +156,18 @@ function collectMatchingTargets(function collectFunctionParameters(node: SyntaxNode | Tree,- state: EditorState,- variableName: string,- scopeId: number,- declarations: VariableDeclaration[],+ options: {+ state: EditorState;+ variableName: string;+ scopeId: number;+ declarations: VariableDeclaration[];+ },) {+ const { state, variableName, scopeId, declarations } = options;const cursor = node.cursor();cursor.firstChild();do {- if (cursor.name !== "ParamList") {+ if (cursor.name !== PyNode.ParamList) {continue;}@@ -180,7 +175,7 @@ function collectFunctionParameters(paramCursor.firstChild();do {if (- paramCursor.name === "VariableName" &&+ paramCursor.name === PyNode.VariableName &&state.doc.sliceString(paramCursor.from, paramCursor.to) === variableName) {addDeclaration(declarations, scopeId, paramCursor.from);@@ -191,38 +186,37 @@ function collectFunctionParameters(function collectForTargets(node: SyntaxNode | Tree,- state: EditorState,- variableName: string,- scopeId: number,- declarations: VariableDeclaration[],+ options: {+ state: EditorState;+ variableName: string;+ scopeId: number;+ declarations: VariableDeclaration[];+ },) {const cursor = node.cursor();cursor.firstChild();let foundFor = false;do {- if (cursor.name === "for") {+ if (cursor.name === PyKeyword.For) {foundFor = true;- } else if (foundFor && cursor.name === "in") {+ } else if (foundFor && cursor.name === PyKeyword.In) {break;} else if (foundFor) {- collectMatchingTargets(- cursor,- state,- variableName,- scopeId,- declarations,- );+ collectMatchingTargets(cursor, options);}} while (cursor.nextSibling());}function collectMatchingDeclarations(node: SyntaxNode | Tree,- state: EditorState,- variableName: string,- scopeStack: number[],- declarations: VariableDeclaration[],+ options: {+ state: EditorState;+ variableName: string;+ scopeStack: number[];+ declarations: VariableDeclaration[];+ },) {+ const { state, variableName, scopeStack, declarations } = options;const cursor = node.cursor();const nodeName = cursor.name;const nodeStart = cursor.from;@@ -234,13 +228,13 @@ function collectMatchingDeclarations(const currentScope = currentScopeStack[currentScopeStack.length - 1] ?? -1;switch (nodeName) {- case "FunctionDefinition":- case "ClassDefinition": {+ case PyNode.FunctionDefinition:+ case PyNode.ClassDefinition: {const subCursor = node.cursor();subCursor.firstChild();do {if (- subCursor.name === "VariableName" &&+ subCursor.name === PyNode.VariableName &&state.doc.sliceString(subCursor.from, subCursor.to) === variableName) {const parentScope = scopeStack[scopeStack.length - 1] ?? -1;@@ -249,41 +243,44 @@ function collectMatchingDeclarations(}} while (subCursor.nextSibling());- if (nodeName === "FunctionDefinition") {- collectFunctionParameters(- node,+ if (nodeName === PyNode.FunctionDefinition) {+ collectFunctionParameters(node, {state,variableName,- nodeStart,+ scopeId: nodeStart,declarations,- );+ });}break;}- case "LambdaExpression":- collectFunctionParameters(- node,+ case PyNode.LambdaExpression:+ collectFunctionParameters(node, {state,variableName,- nodeStart,+ scopeId: nodeStart,declarations,- );+ });break;- case "ArrayComprehensionExpression":- case "DictionaryComprehensionExpression":- case "SetComprehensionExpression":- case "ComprehensionExpression":- case "ForStatement":- collectForTargets(node, state, variableName, currentScope, declarations);+ case PyNode.ArrayComprehensionExpression:+ case PyNode.DictionaryComprehensionExpression:+ case PyNode.SetComprehensionExpression:+ case PyNode.ComprehensionExpression:+ case PyNode.ForStatement:+ collectForTargets(node, {+ state,+ variableName,+ scopeId: currentScope,+ declarations,+ });break;- case "AssignStatement": {+ case PyNode.AssignStatement: {const assignOpPositions: number[] = [];const subCursor = node.cursor();subCursor.firstChild();do {- if (subCursor.name === "AssignOp") {+ if (subCursor.name === PyNode.AssignOp) {assignOpPositions.push(subCursor.from);}} while (subCursor.nextSibling());@@ -298,18 +295,17 @@ function collectMatchingDeclarations(targetCursor.firstChild();do {if (targetCursor.from < lastAssignOpPosition) {- collectMatchingTargets(- targetCursor,+ collectMatchingTargets(targetCursor, {state,variableName,- currentScope,+ scopeId: currentScope,declarations,- );+ });}} while (targetCursor.nextSibling());break;}- case "ImportStatement": {+ case PyNode.ImportStatement: {// The grammar emits one ImportStatement for both `import x [as y]` and// `from m import x [as y], ...`. Direct children include the keywords// (`from`/`import`/`as`), commas, dots, and every VariableName from the@@ -330,19 +326,19 @@ function collectMatchingDeclarations(pending = null;};do {- if (subCursor.name === "import") {+ if (subCursor.name === PyKeyword.Import) {pastImport = true;continue;}if (!pastImport) {continue;}- if (subCursor.name === "as") {+ if (subCursor.name === PyKeyword.As) {// Next VariableName is the alias and replaces `pending`.pending = null;continue;}- if (subCursor.name === "VariableName") {+ if (subCursor.name === PyNode.VariableName) {// Flush any previous pending name (no `as` followed it).commit();pending = {@@ -358,17 +354,17 @@ function collectMatchingDeclarations(commit();break;}- case "TryStatement":- case "WithStatement": {+ case PyNode.TryStatement:+ case PyNode.WithStatement: {const subCursor = node.cursor();subCursor.firstChild();let foundAs = false;do {- if (subCursor.name === "as") {+ if (subCursor.name === PyKeyword.As) {foundAs = true;} else if (foundAs &&- subCursor.name === "VariableName" &&+ subCursor.name === PyNode.VariableName &&state.doc.sliceString(subCursor.from, subCursor.to) === variableName) {addDeclaration(declarations, currentScope, subCursor.from);@@ -382,13 +378,12 @@ function collectMatchingDeclarations(}traverseChildren(cursor, (childNode) => {- collectMatchingDeclarations(- childNode,+ collectMatchingDeclarations(childNode, {state,variableName,- currentScopeStack,+ scopeStack: currentScopeStack,declarations,- );+ });});}@@ -400,7 +395,12 @@ function findScopedDefinitionPosition(const tree = syntaxTree(state);const declarations: VariableDeclaration[] = [];- collectMatchingDeclarations(tree, state, variableName, [], declarations);+ collectMatchingDeclarations(tree, {+ state,+ variableName,+ scopeStack: [],+ declarations,+ });const clampedUsagePosition = Math.max(0,diff --git a/frontend/src/core/codemirror/language/languages/sql/renderers.tsx b/frontend/src/core/codemirror/language/languages/sql/renderers.tsxindex 2209a8dc18..77c299ccd1 100644--- a/frontend/src/core/codemirror/language/languages/sql/renderers.tsx+++ b/frontend/src/core/codemirror/language/languages/sql/renderers.tsx@@ -52,7 +52,7 @@ const SOURCE_TYPE_COLORS = {catalog: "bg-(--purple-4) text-(--purple-11)",} as const;-const CONTAINER_STYLES = "p-3 min-w-[250px] flex flex-col divide-y";+export const CONTAINER_STYLES = "p-3 min-w-[250px] flex flex-col divide-y";const columnsText = new PluralWord("column", "columns");const rowsText = new PluralWord("row", "rows");@@ -61,7 +61,7 @@ const tablesText = new PluralWord("table", "tables");const databasesText = new PluralWord("database", "databases");// Helper components and functions-const SectionHeader: React.FC<{+export const SectionHeader: React.FC<{icon: React.ReactNode;title: string;badge?: React.ReactNode;@@ -73,7 +73,7 @@ const SectionHeader: React.FC<{</div>);-const MetadataRow: React.FC<{+export const MetadataRow: React.FC<{label: string;value: React.ReactNode;}> = ({ label, value }) => (diff --git a/frontend/src/core/codemirror/python-node-names.ts b/frontend/src/core/codemirror/python-node-names.tsnew file mode 100644index 0000000000..bd4e7f68ce--- /dev/null+++ b/frontend/src/core/codemirror/python-node-names.ts@@ -0,0 +1,90 @@+/* Copyright 2026 Marimo. All rights reserved. */++/**+ * Named constants for `@lezer/python` grammar node kinds, referenced+ * throughout the codemirror Python analyzers.+ *+ * See https://code.haverbeke.berlin/lezer/python/src/branch/main/src/python.grammar+ */+export const PyNode = {+ // Names+ VariableName: "VariableName",++ // Declarations / scopes+ FunctionDefinition: "FunctionDefinition",+ ClassDefinition: "ClassDefinition",+ LambdaExpression: "LambdaExpression",+ ParamList: "ParamList",+ Decorator: "Decorator",++ // Statements+ AssignStatement: "AssignStatement",+ ForStatement: "ForStatement",+ ImportStatement: "ImportStatement",+ TryStatement: "TryStatement",+ WithStatement: "WithStatement",++ // Expressions+ TupleExpression: "TupleExpression",+ ArrayExpression: "ArrayExpression",+ ParenthesizedExpression: "ParenthesizedExpression",+ CallExpression: "CallExpression",+ ArgList: "ArgList",+ AssignOp: "AssignOp",+ ArrayComprehensionExpression: "ArrayComprehensionExpression",+ SetComprehensionExpression: "SetComprehensionExpression",+ DictionaryComprehensionExpression: "DictionaryComprehensionExpression",+ ComprehensionExpression: "ComprehensionExpression",++ // Never contain live code+ Comment: "Comment",+ String: "String",+ FormatString: "FormatString",+} as const;++export type PyNodeName = (typeof PyNode)[keyof typeof PyNode];++/**+ * Keyword tokens from the same grammar (also named nodes, just lowercase+ * and not part of `expression`/`statement`).+ */+export const PyKeyword = {+ For: "for",+ In: "in",+ As: "as",+ Import: "import",+} as const;++export type PyKeywordName = (typeof PyKeyword)[keyof typeof PyKeyword];++/**+ * Node kinds that introduce a new variable scope: function/lambda bodies+ * (and their parameters), comprehensions (their loop variables are scoped+ * to the comprehension), and class bodies.+ */+export const SCOPE_CREATING_NODES: ReadonlySet<string> = new Set([+ PyNode.FunctionDefinition,+ PyNode.LambdaExpression,+ PyNode.ArrayComprehensionExpression,+ PyNode.SetComprehensionExpression,+ PyNode.DictionaryComprehensionExpression,+ PyNode.ComprehensionExpression,+ PyNode.ClassDefinition,+]);++/**+ * Node kinds that never contain live code: comments and string/f-string+ * literals.+ *+ * Note `FormatString` nodes *do* contain real, parsed expressions for+ * their `{...}` interpolations (as child `FormatReplacement` nodes) — this+ * set is only safe to use for point checks (e.g. `resolveInner(pos).name`,+ * which already resolves to the innermost node at that exact position) and+ * NOT for pruning a `tree.iterate()` walk, which would also skip those+ * interpolations' real child nodes.+ */+export const NON_CODE_NODES: ReadonlySet<string> = new Set([+ PyNode.Comment,+ PyNode.String,+ PyNode.FormatString,+]);diff --git a/frontend/src/core/codemirror/reactive-references/analyzer.ts b/frontend/src/core/codemirror/reactive-references/analyzer.tsindex ca1bb1f78d..c37ea8a0c6 100644--- a/frontend/src/core/codemirror/reactive-references/analyzer.ts+++ b/frontend/src/core/codemirror/reactive-references/analyzer.ts@@ -5,6 +5,7 @@ import type { EditorState } from "@codemirror/state";import type { SyntaxNode, Tree, TreeCursor } from "@lezer/common";import { type CellId, SETUP_CELL_ID } from "@/core/cells/ids";import type { VariableName, Variables } from "@/core/variables/types";+import { PyKeyword, PyNode, SCOPE_CREATING_NODES } from "../python-node-names";export interface ReactiveVariableRange {from: number;@@ -12,16 +13,6 @@ export interface ReactiveVariableRange {variableName: string;}-const SCOPE_CREATING_NODES = new Set([- "FunctionDefinition",- "LambdaExpression",- "ArrayComprehensionExpression",- "SetComprehensionExpression",- "DictionaryComprehensionExpression",- "ComprehensionExpression",- "ClassDefinition",-]);-/*** Analyzes the given editor state to find variable names that represent* reactive dependencies from other cells (similar to ObservableHQ's approach).@@ -88,11 +79,11 @@ export function findReactiveVariables(options: {}switch (nodeName) {- case "FunctionDefinition": {+ case PyNode.FunctionDefinition: {const subCursor = node.cursor();subCursor.firstChild();do {- if (subCursor.name === "VariableName") {+ if (subCursor.name === PyNode.VariableName) {const functionName = options.state.doc.sliceString(subCursor.from,subCursor.to,@@ -111,11 +102,11 @@ export function findReactiveVariables(options: {const paramCursor = node.cursor();paramCursor.firstChild();do {- if (paramCursor.name === "ParamList") {+ if (paramCursor.name === PyNode.ParamList) {const paramListCursor = paramCursor.node.cursor();paramListCursor.firstChild();do {- if (paramListCursor.name === "VariableName") {+ if (paramListCursor.name === PyNode.VariableName) {const paramName = options.state.doc.sliceString(paramListCursor.from,paramListCursor.to,@@ -128,16 +119,16 @@ export function findReactiveVariables(options: {break;}- case "LambdaExpression": {+ case PyNode.LambdaExpression: {// Lambda paramsconst subCursor = node.cursor();subCursor.firstChild();do {- if (subCursor.name === "ParamList") {+ if (subCursor.name === PyNode.ParamList) {const paramCursor = subCursor.node.cursor();paramCursor.firstChild();do {- if (paramCursor.name === "VariableName") {+ if (paramCursor.name === PyNode.VariableName) {const paramName = options.state.doc.sliceString(paramCursor.from,paramCursor.to,@@ -150,29 +141,29 @@ export function findReactiveVariables(options: {break;}- case "ArrayComprehensionExpression":- case "DictionaryComprehensionExpression":- case "SetComprehensionExpression":- case "ComprehensionExpression": {+ case PyNode.ArrayComprehensionExpression:+ case PyNode.DictionaryComprehensionExpression:+ case PyNode.SetComprehensionExpression:+ case PyNode.ComprehensionExpression: {// Domprehension variables - look for VariableName or TupleExpression after 'for'const subCursor = node.cursor();subCursor.firstChild();let foundFor = false;do {- if (subCursor.name === "for") {+ if (subCursor.name === PyKeyword.For) {foundFor = true;- } else if (foundFor && subCursor.name === "VariableName") {+ } else if (foundFor && subCursor.name === PyNode.VariableName) {const varName = options.state.doc.sliceString(subCursor.from,subCursor.to,);allDeclarations.get(nodeStart)?.add(varName);- } else if (foundFor && subCursor.name === "TupleExpression") {+ } else if (foundFor && subCursor.name === PyNode.TupleExpression) {// Handle tuple destructuring like (k, v)const tupleCursor = subCursor.node.cursor();tupleCursor.firstChild();do {- if (tupleCursor.name === "VariableName") {+ if (tupleCursor.name === PyNode.VariableName) {const varName = options.state.doc.sliceString(tupleCursor.from,tupleCursor.to,@@ -180,18 +171,18 @@ export function findReactiveVariables(options: {allDeclarations.get(nodeStart)?.add(varName);}} while (tupleCursor.nextSibling());- } else if (foundFor && subCursor.name === "in") {+ } else if (foundFor && subCursor.name === PyKeyword.In) {foundFor = false; // Stop collecting variables after 'in'}} while (subCursor.nextSibling());break;}- case "ClassDefinition": {+ case PyNode.ClassDefinition: {const subCursor = node.cursor();subCursor.firstChild();do {- if (subCursor.name === "VariableName") {+ if (subCursor.name === PyNode.VariableName) {const className = options.state.doc.sliceString(subCursor.from,subCursor.to,@@ -210,7 +201,7 @@ export function findReactiveVariables(options: {break;}- case "AssignStatement": {+ case PyNode.AssignStatement: {// Assignments - capture all variables being assigned to (variables that come before the last AssignOp)const subCursor = node.cursor();@@ -218,7 +209,7 @@ export function findReactiveVariables(options: {const assignOpPositions: number[] = [];subCursor.firstChild();do {- if (subCursor.name === "AssignOp") {+ if (subCursor.name === PyNode.AssignOp) {assignOpPositions.push(subCursor.from);}} while (subCursor.nextSibling());@@ -248,15 +239,15 @@ export function findReactiveVariables(options: {break;}- case "ForStatement": {+ case PyNode.ForStatement: {// For loop variablesconst subCursor = node.cursor();subCursor.firstChild();let foundFor = false;do {- if (subCursor.name === "for") {+ if (subCursor.name === PyKeyword.For) {foundFor = true;- } else if (foundFor && subCursor.name === "VariableName") {+ } else if (foundFor && subCursor.name === PyNode.VariableName) {const varName = options.state.doc.sliceString(subCursor.from,subCursor.to,@@ -268,14 +259,14 @@ export function findReactiveVariables(options: {allDeclarations.set(currentScope, new Set());}allDeclarations.get(currentScope)?.add(varName);- } else if (foundFor && subCursor.name === "in") {+ } else if (foundFor && subCursor.name === PyKeyword.In) {foundFor = false; // Stop collecting variables after 'in'}} while (subCursor.nextSibling());break;}- case "ImportStatement": {+ case PyNode.ImportStatement: {// The grammar emits a single ImportStatement for both `import x [as y]`// and `from m import x [as y], ...`. Direct children mix keywords,// module-path names (before `import`), imported names, and aliases.@@ -299,19 +290,19 @@ export function findReactiveVariables(options: {pending = null;};do {- if (subCursor.name === "import") {+ if (subCursor.name === PyKeyword.Import) {pastImport = true;continue;}if (!pastImport) {continue;}- if (subCursor.name === "as") {+ if (subCursor.name === PyKeyword.As) {// Drop the imported name; the next VariableName is the alias.pending = null;continue;}- if (subCursor.name === "VariableName") {+ if (subCursor.name === PyNode.VariableName) {commit();pending = options.state.doc.sliceString(subCursor.from,@@ -325,15 +316,15 @@ export function findReactiveVariables(options: {break;}- case "TryStatement": {+ case PyNode.TryStatement: {// Exception variable binding - look for 'as' followed by VariableNameconst subCursor = node.cursor();subCursor.firstChild();let foundAs = false;do {- if (subCursor.name === "as") {+ if (subCursor.name === PyKeyword.As) {foundAs = true;- } else if (foundAs && subCursor.name === "VariableName") {+ } else if (foundAs && subCursor.name === PyNode.VariableName) {const varName = options.state.doc.sliceString(subCursor.from,subCursor.to,@@ -350,14 +341,14 @@ export function findReactiveVariables(options: {break;}- case "WithStatement": {+ case PyNode.WithStatement: {const subCursor = node.cursor();subCursor.firstChild();let foundAs = false;do {- if (subCursor.name === "as") {+ if (subCursor.name === PyKeyword.As) {foundAs = true;- } else if (foundAs && subCursor.name === "VariableName") {+ } else if (foundAs && subCursor.name === PyNode.VariableName) {const varName = options.state.doc.sliceString(subCursor.from,subCursor.to,@@ -405,7 +396,7 @@ export function findReactiveVariables(options: {for (const scope of scopeStack) {const scopeType = scopeTypes.get(scope);- if (scopeType === "ClassDefinition") {+ if (scopeType === PyNode.ClassDefinition) {// for class scopes, check position-based declarationsif (isVariableDeclaredInClassScope(varName, scope, cursorPosition)) {return true;@@ -429,7 +420,7 @@ export function findReactiveVariables(options: {// Names inside an import statement are module paths, imported names, or// aliases — none of them are reactive *uses* of an outer-cell global.- if (nodeName === "ImportStatement") {+ if (nodeName === PyNode.ImportStatement) {return;}@@ -440,7 +431,7 @@ export function findReactiveVariables(options: {currentScopeStack = [...scopeStack, nodeStart];}- if (nodeName === "VariableName") {+ if (nodeName === PyNode.VariableName) {const varName = options.state.doc.sliceString(cursor.from, cursor.to);if (shouldHighlightVariable(varName, cursor)) {@@ -498,13 +489,17 @@ export function findReactiveVariables(options: {function isKeywordArgumentName(cursor: TreeCursor): boolean {const temp = cursor.node.cursor();temp.moveTo(cursor.from);- if (temp.parent() && temp.name === "CallExpression" && temp.firstChild()) {+ if (+ temp.parent() &&+ temp.name === PyNode.CallExpression &&+ temp.firstChild()+ ) {do {// @ts-expect-error: comparing disjoint string literals is intentional due to do/while traversal- if (temp.name === "ArgList" && temp.firstChild()) {+ if (temp.name === PyNode.ArgList && temp.firstChild()) {do {if (temp.from === cursor.from && temp.to === cursor.to) {- return temp.nextSibling() && temp.name === "AssignOp";+ return temp.nextSibling() && temp.name === PyNode.AssignOp;}} while (temp.nextSibling());break;@@ -519,14 +514,14 @@ function isAssignmentTarget(cursor: TreeCursor): boolean {const temp = cursor.node.cursor();// Check if parent is AssignStatement- if (temp.parent() && temp.name === "AssignStatement") {+ if (temp.parent() && temp.name === PyNode.AssignStatement) {// Now check if this VariableName is before the AssignOpconst assignStatementCursor = temp.node.cursor();assignStatementCursor.firstChild();let assignOpPosition = -1;do {- if (assignStatementCursor.name === "AssignOp") {+ if (assignStatementCursor.name === PyNode.AssignOp) {assignOpPosition = assignStatementCursor.from;break;}@@ -556,7 +551,7 @@ function isPropertyAccess(cursor: TreeCursor): boolean {* Checks if the syntax tree contains any syntax errors.* If there are errors, we shouldn't show reactive variable highlighting.*/-function hasSyntaxErrors(tree: Tree): boolean {+export function hasSyntaxErrors(tree: Tree): boolean {const cursor = tree.cursor();do {// Lezer uses "⚠" as the error node name for syntax errors@@ -583,11 +578,11 @@ function extractAssignmentTargets(},) {switch (cursor.name) {- case "VariableName": {+ case PyNode.VariableName: {const varName = options.state.doc.sliceString(cursor.from, cursor.to);const isInClassScope =options.currentScope !== -1 &&- options.scopeTypes.get(options.currentScope) === "ClassDefinition";+ options.scopeTypes.get(options.currentScope) === PyNode.ClassDefinition;if (isInClassScope) {// For class-level assignments, track the position of the assignment@@ -606,7 +601,7 @@ function extractAssignmentTargets(break;}- case "TupleExpression": {+ case PyNode.TupleExpression: {// Handle tuple unpacking like (x, (y, z)) = ...const tupleCursor = cursor.node.cursor();tupleCursor.firstChild();@@ -616,7 +611,7 @@ function extractAssignmentTargets(break;}- case "ArrayExpression": {+ case PyNode.ArrayExpression: {// Handle list unpacking like [a, b, c] = ...const arrayCursor = cursor.node.cursor();arrayCursor.firstChild();diff --git a/frontend/src/core/config/feature-flag.tsx b/frontend/src/core/config/feature-flag.tsxindex 695f691ecf..cefb4b9389 100644--- a/frontend/src/core/config/feature-flag.tsx+++ b/frontend/src/core/config/feature-flag.tsx@@ -13,6 +13,7 @@ export interface ExperimentalFeatures {external_agents: boolean;debugger: boolean; // Live frame-watching debugger (gutter breakpoints + pdb)line_timing: boolean; // Green active-line highlight + per-line elapsed timer+ editor_code_lens: boolean; // Inline icons in cell editors linking datasources/buckets/caches to their panels// Add new feature flags here}@@ -20,10 +21,11 @@ const defaultValues: ExperimentalFeatures = {markdown: true,wasm_layouts: false,rtc_v2: false,- cache_panel: false,+ cache_panel: import.meta.env.DEV,external_agents: import.meta.env.DEV,debugger: false,line_timing: false,+ editor_code_lens: import.meta.env.DEV,};export function getFeatureFlag<T extends keyof ExperimentalFeatures>(diff --git a/marimo/_smoke_tests/editor_code_lens.py b/marimo/_smoke_tests/editor_code_lens.pynew file mode 100644index 0000000000..a92d7179c7--- /dev/null+++ b/marimo/_smoke_tests/editor_code_lens.py@@ -0,0 +1,83 @@+# /// script+# requires-python = ">=3.11"+# dependencies = [+# "marimo",+# "polars",+# "duckdb",+# "fsspec",+# ]+# ///++import marimo++__generated_with = "0.23.13"+app = marimo.App(width="medium")+++def _(mo):+ mo.md(r"""+ # Editor code lens++ Requires the `editor_code_lens` experimental flag (on by default in dev+ builds; otherwise run `setFeatureFlag("editor_code_lens", true)` in the+ browser console). Cache icons also require the `cache_panel` flag.++ Each cell below creates something that gets a small inline icon next to+ it in the editor. Clicking the icon opens the matching panel:++ - dataframe or SQL engine → variables panel, data sources section+ - fsspec/obstore bucket → files panel, remote storage section+ - `mo.cache` / `mo.persistent_cache` → cache panel+ """)+ return+++def _():+ import duckdb+ import fsspec+ import polars as pl++ import marimo as mo++ return duckdb, fsspec, mo, pl+++def _(pl):+ # Dataframe: icon after `df`+ df = pl.DataFrame({"a": [1, 2, 3], "b": ["x", "y", "z"]})+ return+++def _(duckdb):+ # SQL engine: icon after `engine`+ engine = duckdb.connect()+ return+++def _(fsspec):+ # Storage bucket: icon after `bucket`+ bucket = fsspec.filesystem("memory")+ bucket.pipe_file("smoke-test/hello.txt", b"hello from the code lens")+ return+++def _(mo):+ # Cache: icons after `mo.cache` and `mo.persistent_cache`+ @mo.cache()+ def add(a: int, b: int) -> int:+ return a + b++ with mo.persistent_cache("editor_code_lens_smoke_test"):+ total = add(1, 2)+ total+ return+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_smoke_tests/editor_code_lens_stress.py b/marimo/_smoke_tests/editor_code_lens_stress.pynew file mode 100644index 0000000000..4ded3fa2c4--- /dev/null+++ b/marimo/_smoke_tests/editor_code_lens_stress.py@@ -0,0 +1,1084 @@+# /// script+# requires-python = ">=3.11"+# dependencies = [+# "marimo",+# "polars",+# "duckdb",+# "fsspec",+# ]+# ///++import marimo++__generated_with = "0.23.15"+app = marimo.App(width="medium")+++def _(mo):+ mo.md(r"""+ # Editor code lens (stress test)++ Stress-tests `editor_code_lens` with many datasources, SQL engines, storage+ buckets, and cache sites. Requires `editor_code_lens` (on in dev builds)+ and `cache_panel` for cache icons.++ Current notebook scale: 200 tables, 50 engines, 50 buckets, 100 cache sites.+ """)+ return+++def _():+ import duckdb+ import fsspec+ import polars as pl++ import marimo as mo++ return duckdb, fsspec, mo, pl+++def _(pl):+ table_0 = pl.DataFrame({'i': [0], 'v': ['a']})+ table_1 = pl.DataFrame({'i': [1], 'v': ['a']})+ table_2 = pl.DataFrame({'i': [2], 'v': ['a']})+ table_3 = pl.DataFrame({'i': [3], 'v': ['a']})+ table_4 = pl.DataFrame({'i': [4], 'v': ['a']})+ table_5 = pl.DataFrame({'i': [5], 'v': ['a']})+ table_6 = pl.DataFrame({'i': [6], 'v': ['a']})+ table_7 = pl.DataFrame({'i': [7], 'v': ['a']})+ table_8 = pl.DataFrame({'i': [8], 'v': ['a']})+ table_9 = pl.DataFrame({'i': [9], 'v': ['a']})+ return+++def _(pl):+ table_10 = pl.DataFrame({'i': [10], 'v': ['a']})+ table_11 = pl.DataFrame({'i': [11], 'v': ['a']})+ table_12 = pl.DataFrame({'i': [12], 'v': ['a']})+ table_13 = pl.DataFrame({'i': [13], 'v': ['a']})+ table_14 = pl.DataFrame({'i': [14], 'v': ['a']})+ table_15 = pl.DataFrame({'i': [15], 'v': ['a']})+ table_16 = pl.DataFrame({'i': [16], 'v': ['a']})+ table_17 = pl.DataFrame({'i': [17], 'v': ['a']})+ table_18 = pl.DataFrame({'i': [18], 'v': ['a']})+ table_19 = pl.DataFrame({'i': [19], 'v': ['a']})+ return+++def _(pl):+ table_20 = pl.DataFrame({'i': [20], 'v': ['a']})+ table_21 = pl.DataFrame({'i': [21], 'v': ['a']})+ table_22 = pl.DataFrame({'i': [22], 'v': ['a']})+ table_23 = pl.DataFrame({'i': [23], 'v': ['a']})+ table_24 = pl.DataFrame({'i': [24], 'v': ['a']})+ table_25 = pl.DataFrame({'i': [25], 'v': ['a']})+ table_26 = pl.DataFrame({'i': [26], 'v': ['a']})+ table_27 = pl.DataFrame({'i': [27], 'v': ['a']})+ table_28 = pl.DataFrame({'i': [28], 'v': ['a']})+ table_29 = pl.DataFrame({'i': [29], 'v': ['a']})+ return+++def _(pl):+ table_30 = pl.DataFrame({'i': [30], 'v': ['a']})+ table_31 = pl.DataFrame({'i': [31], 'v': ['a']})+ table_32 = pl.DataFrame({'i': [32], 'v': ['a']})+ table_33 = pl.DataFrame({'i': [33], 'v': ['a']})+ table_34 = pl.DataFrame({'i': [34], 'v': ['a']})+ table_35 = pl.DataFrame({'i': [35], 'v': ['a']})+ table_36 = pl.DataFrame({'i': [36], 'v': ['a']})+ table_37 = pl.DataFrame({'i': [37], 'v': ['a']})+ table_38 = pl.DataFrame({'i': [38], 'v': ['a']})+ table_39 = pl.DataFrame({'i': [39], 'v': ['a']})+ return+++def _(pl):+ table_40 = pl.DataFrame({'i': [40], 'v': ['a']})+ table_41 = pl.DataFrame({'i': [41], 'v': ['a']})+ table_42 = pl.DataFrame({'i': [42], 'v': ['a']})+ table_43 = pl.DataFrame({'i': [43], 'v': ['a']})+ table_44 = pl.DataFrame({'i': [44], 'v': ['a']})+ table_45 = pl.DataFrame({'i': [45], 'v': ['a']})+ table_46 = pl.DataFrame({'i': [46], 'v': ['a']})+ table_47 = pl.DataFrame({'i': [47], 'v': ['a']})+ table_48 = pl.DataFrame({'i': [48], 'v': ['a']})+ table_49 = pl.DataFrame({'i': [49], 'v': ['a']})+ return+++def _(pl):+ table_50 = pl.DataFrame({'i': [50], 'v': ['a']})+ table_51 = pl.DataFrame({'i': [51], 'v': ['a']})+ table_52 = pl.DataFrame({'i': [52], 'v': ['a']})+ table_53 = pl.DataFrame({'i': [53], 'v': ['a']})+ table_54 = pl.DataFrame({'i': [54], 'v': ['a']})+ table_55 = pl.DataFrame({'i': [55], 'v': ['a']})+ table_56 = pl.DataFrame({'i': [56], 'v': ['a']})+ table_57 = pl.DataFrame({'i': [57], 'v': ['a']})+ table_58 = pl.DataFrame({'i': [58], 'v': ['a']})+ table_59 = pl.DataFrame({'i': [59], 'v': ['a']})+ return+++def _(pl):+ table_60 = pl.DataFrame({'i': [60], 'v': ['a']})+ table_61 = pl.DataFrame({'i': [61], 'v': ['a']})+ table_62 = pl.DataFrame({'i': [62], 'v': ['a']})+ table_63 = pl.DataFrame({'i': [63], 'v': ['a']})+ table_64 = pl.DataFrame({'i': [64], 'v': ['a']})+ table_65 = pl.DataFrame({'i': [65], 'v': ['a']})+ table_66 = pl.DataFrame({'i': [66], 'v': ['a']})+ table_67 = pl.DataFrame({'i': [67], 'v': ['a']})+ table_68 = pl.DataFrame({'i': [68], 'v': ['a']})+ table_69 = pl.DataFrame({'i': [69], 'v': ['a']})+ return+++def _(pl):+ table_70 = pl.DataFrame({'i': [70], 'v': ['a']})+ table_71 = pl.DataFrame({'i': [71], 'v': ['a']})+ table_72 = pl.DataFrame({'i': [72], 'v': ['a']})+ table_73 = pl.DataFrame({'i': [73], 'v': ['a']})+ table_74 = pl.DataFrame({'i': [74], 'v': ['a']})+ table_75 = pl.DataFrame({'i': [75], 'v': ['a']})+ table_76 = pl.DataFrame({'i': [76], 'v': ['a']})+ table_77 = pl.DataFrame({'i': [77], 'v': ['a']})+ table_78 = pl.DataFrame({'i': [78], 'v': ['a']})+ table_79 = pl.DataFrame({'i': [79], 'v': ['a']})+ return+++def _(pl):+ table_80 = pl.DataFrame({'i': [80], 'v': ['a']})+ table_81 = pl.DataFrame({'i': [81], 'v': ['a']})+ table_82 = pl.DataFrame({'i': [82], 'v': ['a']})+ table_83 = pl.DataFrame({'i': [83], 'v': ['a']})+ table_84 = pl.DataFrame({'i': [84], 'v': ['a']})+ table_85 = pl.DataFrame({'i': [85], 'v': ['a']})+ table_86 = pl.DataFrame({'i': [86], 'v': ['a']})+ table_87 = pl.DataFrame({'i': [87], 'v': ['a']})+ table_88 = pl.DataFrame({'i': [88], 'v': ['a']})+ table_89 = pl.DataFrame({'i': [89], 'v': ['a']})+ return+++def _(pl):+ table_90 = pl.DataFrame({'i': [90], 'v': ['a']})+ table_91 = pl.DataFrame({'i': [91], 'v': ['a']})+ table_92 = pl.DataFrame({'i': [92], 'v': ['a']})+ table_93 = pl.DataFrame({'i': [93], 'v': ['a']})+ table_94 = pl.DataFrame({'i': [94], 'v': ['a']})+ table_95 = pl.DataFrame({'i': [95], 'v': ['a']})+ table_96 = pl.DataFrame({'i': [96], 'v': ['a']})+ table_97 = pl.DataFrame({'i': [97], 'v': ['a']})+ table_98 = pl.DataFrame({'i': [98], 'v': ['a']})+ table_99 = pl.DataFrame({'i': [99], 'v': ['a']})+ return+++def _(pl):+ table_100 = pl.DataFrame({'i': [100], 'v': ['a']})+ table_101 = pl.DataFrame({'i': [101], 'v': ['a']})+ table_102 = pl.DataFrame({'i': [102], 'v': ['a']})+ table_103 = pl.DataFrame({'i': [103], 'v': ['a']})+ table_104 = pl.DataFrame({'i': [104], 'v': ['a']})+ table_105 = pl.DataFrame({'i': [105], 'v': ['a']})+ table_106 = pl.DataFrame({'i': [106], 'v': ['a']})+ table_107 = pl.DataFrame({'i': [107], 'v': ['a']})+ table_108 = pl.DataFrame({'i': [108], 'v': ['a']})+ table_109 = pl.DataFrame({'i': [109], 'v': ['a']})+ return+++def _(pl):+ table_110 = pl.DataFrame({'i': [110], 'v': ['a']})+ table_111 = pl.DataFrame({'i': [111], 'v': ['a']})+ table_112 = pl.DataFrame({'i': [112], 'v': ['a']})+ table_113 = pl.DataFrame({'i': [113], 'v': ['a']})+ table_114 = pl.DataFrame({'i': [114], 'v': ['a']})+ table_115 = pl.DataFrame({'i': [115], 'v': ['a']})+ table_116 = pl.DataFrame({'i': [116], 'v': ['a']})+ table_117 = pl.DataFrame({'i': [117], 'v': ['a']})+ table_118 = pl.DataFrame({'i': [118], 'v': ['a']})+ table_119 = pl.DataFrame({'i': [119], 'v': ['a']})+ return+++def _(pl):+ table_120 = pl.DataFrame({'i': [120], 'v': ['a']})+ table_121 = pl.DataFrame({'i': [121], 'v': ['a']})+ table_122 = pl.DataFrame({'i': [122], 'v': ['a']})+ table_123 = pl.DataFrame({'i': [123], 'v': ['a']})+ table_124 = pl.DataFrame({'i': [124], 'v': ['a']})+ table_125 = pl.DataFrame({'i': [125], 'v': ['a']})+ table_126 = pl.DataFrame({'i': [126], 'v': ['a']})+ table_127 = pl.DataFrame({'i': [127], 'v': ['a']})+ table_128 = pl.DataFrame({'i': [128], 'v': ['a']})+ table_129 = pl.DataFrame({'i': [129], 'v': ['a']})+ return+++def _(pl):+ table_130 = pl.DataFrame({'i': [130], 'v': ['a']})+ table_131 = pl.DataFrame({'i': [131], 'v': ['a']})+ table_132 = pl.DataFrame({'i': [132], 'v': ['a']})+ table_133 = pl.DataFrame({'i': [133], 'v': ['a']})+ table_134 = pl.DataFrame({'i': [134], 'v': ['a']})+ table_135 = pl.DataFrame({'i': [135], 'v': ['a']})+ table_136 = pl.DataFrame({'i': [136], 'v': ['a']})+ table_137 = pl.DataFrame({'i': [137], 'v': ['a']})+ table_138 = pl.DataFrame({'i': [138], 'v': ['a']})+ table_139 = pl.DataFrame({'i': [139], 'v': ['a']})+ return+++def _(pl):+ table_140 = pl.DataFrame({'i': [140], 'v': ['a']})+ table_141 = pl.DataFrame({'i': [141], 'v': ['a']})+ table_142 = pl.DataFrame({'i': [142], 'v': ['a']})+ table_143 = pl.DataFrame({'i': [143], 'v': ['a']})+ table_144 = pl.DataFrame({'i': [144], 'v': ['a']})+ table_145 = pl.DataFrame({'i': [145], 'v': ['a']})+ table_146 = pl.DataFrame({'i': [146], 'v': ['a']})+ table_147 = pl.DataFrame({'i': [147], 'v': ['a']})+ table_148 = pl.DataFrame({'i': [148], 'v': ['a']})+ table_149 = pl.DataFrame({'i': [149], 'v': ['a']})+ return+++def _(pl):+ table_150 = pl.DataFrame({'i': [150], 'v': ['a']})+ table_151 = pl.DataFrame({'i': [151], 'v': ['a']})+ table_152 = pl.DataFrame({'i': [152], 'v': ['a']})+ table_153 = pl.DataFrame({'i': [153], 'v': ['a']})+ table_154 = pl.DataFrame({'i': [154], 'v': ['a']})+ table_155 = pl.DataFrame({'i': [155], 'v': ['a']})+ table_156 = pl.DataFrame({'i': [156], 'v': ['a']})+ table_157 = pl.DataFrame({'i': [157], 'v': ['a']})+ table_158 = pl.DataFrame({'i': [158], 'v': ['a']})+ table_159 = pl.DataFrame({'i': [159], 'v': ['a']})+ return+++def _(pl):+ table_160 = pl.DataFrame({'i': [160], 'v': ['a']})+ table_161 = pl.DataFrame({'i': [161], 'v': ['a']})+ table_162 = pl.DataFrame({'i': [162], 'v': ['a']})+ table_163 = pl.DataFrame({'i': [163], 'v': ['a']})+ table_164 = pl.DataFrame({'i': [164], 'v': ['a']})+ table_165 = pl.DataFrame({'i': [165], 'v': ['a']})+ table_166 = pl.DataFrame({'i': [166], 'v': ['a']})+ table_167 = pl.DataFrame({'i': [167], 'v': ['a']})+ table_168 = pl.DataFrame({'i': [168], 'v': ['a']})+ table_169 = pl.DataFrame({'i': [169], 'v': ['a']})+ return+++def _(pl):+ table_170 = pl.DataFrame({'i': [170], 'v': ['a']})+ table_171 = pl.DataFrame({'i': [171], 'v': ['a']})+ table_172 = pl.DataFrame({'i': [172], 'v': ['a']})+ table_173 = pl.DataFrame({'i': [173], 'v': ['a']})+ table_174 = pl.DataFrame({'i': [174], 'v': ['a']})+ table_175 = pl.DataFrame({'i': [175], 'v': ['a']})+ table_176 = pl.DataFrame({'i': [176], 'v': ['a']})+ table_177 = pl.DataFrame({'i': [177], 'v': ['a']})+ table_178 = pl.DataFrame({'i': [178], 'v': ['a']})+ table_179 = pl.DataFrame({'i': [179], 'v': ['a']})+ return+++def _(pl):+ table_180 = pl.DataFrame({'i': [180], 'v': ['a']})+ table_181 = pl.DataFrame({'i': [181], 'v': ['a']})+ table_182 = pl.DataFrame({'i': [182], 'v': ['a']})+ table_183 = pl.DataFrame({'i': [183], 'v': ['a']})+ table_184 = pl.DataFrame({'i': [184], 'v': ['a']})+ table_185 = pl.DataFrame({'i': [185], 'v': ['a']})+ table_186 = pl.DataFrame({'i': [186], 'v': ['a']})+ table_187 = pl.DataFrame({'i': [187], 'v': ['a']})+ table_188 = pl.DataFrame({'i': [188], 'v': ['a']})+ table_189 = pl.DataFrame({'i': [189], 'v': ['a']})+ return+++def _(pl):+ table_190 = pl.DataFrame({'i': [190], 'v': ['a']})+ table_191 = pl.DataFrame({'i': [191], 'v': ['a']})+ table_192 = pl.DataFrame({'i': [192], 'v': ['a']})+ table_193 = pl.DataFrame({'i': [193], 'v': ['a']})+ table_194 = pl.DataFrame({'i': [194], 'v': ['a']})+ table_195 = pl.DataFrame({'i': [195], 'v': ['a']})+ table_196 = pl.DataFrame({'i': [196], 'v': ['a']})+ table_197 = pl.DataFrame({'i': [197], 'v': ['a']})+ table_198 = pl.DataFrame({'i': [198], 'v': ['a']})+ table_199 = pl.DataFrame({'i': [199], 'v': ['a']})+ return+++def _(duckdb):+ engine_0 = duckdb.connect(":memory:")+ engine_1 = duckdb.connect(":memory:")+ engine_2 = duckdb.connect(":memory:")+ engine_3 = duckdb.connect(":memory:")+ engine_4 = duckdb.connect(":memory:")+ return+++def _(duckdb):+ engine_5 = duckdb.connect(":memory:")+ engine_6 = duckdb.connect(":memory:")+ engine_7 = duckdb.connect(":memory:")+ engine_8 = duckdb.connect(":memory:")+ engine_9 = duckdb.connect(":memory:")+ return+++def _(duckdb):+ engine_10 = duckdb.connect(":memory:")+ engine_11 = duckdb.connect(":memory:")+ engine_12 = duckdb.connect(":memory:")+ engine_13 = duckdb.connect(":memory:")+ engine_14 = duckdb.connect(":memory:")+ return+++def _(duckdb):+ engine_15 = duckdb.connect(":memory:")+ engine_16 = duckdb.connect(":memory:")+ engine_17 = duckdb.connect(":memory:")+ engine_18 = duckdb.connect(":memory:")+ engine_19 = duckdb.connect(":memory:")+ return+++def _(duckdb):+ engine_20 = duckdb.connect(":memory:")+ engine_21 = duckdb.connect(":memory:")+ engine_22 = duckdb.connect(":memory:")+ engine_23 = duckdb.connect(":memory:")+ engine_24 = duckdb.connect(":memory:")+ return+++def _(duckdb):+ engine_25 = duckdb.connect(":memory:")+ engine_26 = duckdb.connect(":memory:")+ engine_27 = duckdb.connect(":memory:")+ engine_28 = duckdb.connect(":memory:")+ engine_29 = duckdb.connect(":memory:")+ return+++def _(duckdb):+ engine_30 = duckdb.connect(":memory:")+ engine_31 = duckdb.connect(":memory:")+ engine_32 = duckdb.connect(":memory:")+ engine_33 = duckdb.connect(":memory:")+ engine_34 = duckdb.connect(":memory:")+ return+++def _(duckdb):+ engine_35 = duckdb.connect(":memory:")+ engine_36 = duckdb.connect(":memory:")+ engine_37 = duckdb.connect(":memory:")+ engine_38 = duckdb.connect(":memory:")+ engine_39 = duckdb.connect(":memory:")+ return+++def _(duckdb):+ engine_40 = duckdb.connect(":memory:")+ engine_41 = duckdb.connect(":memory:")+ engine_42 = duckdb.connect(":memory:")+ engine_43 = duckdb.connect(":memory:")+ engine_44 = duckdb.connect(":memory:")+ return+++def _(duckdb):+ engine_45 = duckdb.connect(":memory:")+ engine_46 = duckdb.connect(":memory:")+ engine_47 = duckdb.connect(":memory:")+ engine_48 = duckdb.connect(":memory:")+ engine_49 = duckdb.connect(":memory:")+ return+++def _(fsspec):+ bucket_0 = fsspec.filesystem('memory')+ bucket_1 = fsspec.filesystem('memory')+ bucket_2 = fsspec.filesystem('memory')+ bucket_3 = fsspec.filesystem('memory')+ bucket_4 = fsspec.filesystem('memory')+ bucket_0.pipe_file('stress/hello.txt', b'hello')+ return+++def _(fsspec):+ bucket_5 = fsspec.filesystem('memory')+ bucket_6 = fsspec.filesystem('memory')+ bucket_7 = fsspec.filesystem('memory')+ bucket_8 = fsspec.filesystem('memory')+ bucket_9 = fsspec.filesystem('memory')+ return+++def _(fsspec):+ bucket_10 = fsspec.filesystem('memory')+ bucket_11 = fsspec.filesystem('memory')+ bucket_12 = fsspec.filesystem('memory')+ bucket_13 = fsspec.filesystem('memory')+ bucket_14 = fsspec.filesystem('memory')+ return+++def _(fsspec):+ bucket_15 = fsspec.filesystem('memory')+ bucket_16 = fsspec.filesystem('memory')+ bucket_17 = fsspec.filesystem('memory')+ bucket_18 = fsspec.filesystem('memory')+ bucket_19 = fsspec.filesystem('memory')+ return+++def _(fsspec):+ bucket_20 = fsspec.filesystem('memory')+ bucket_21 = fsspec.filesystem('memory')+ bucket_22 = fsspec.filesystem('memory')+ bucket_23 = fsspec.filesystem('memory')+ bucket_24 = fsspec.filesystem('memory')+ return+++def _(fsspec):+ bucket_25 = fsspec.filesystem('memory')+ bucket_26 = fsspec.filesystem('memory')+ bucket_27 = fsspec.filesystem('memory')+ bucket_28 = fsspec.filesystem('memory')+ bucket_29 = fsspec.filesystem('memory')+ return+++def _(fsspec):+ bucket_30 = fsspec.filesystem('memory')+ bucket_31 = fsspec.filesystem('memory')+ bucket_32 = fsspec.filesystem('memory')+ bucket_33 = fsspec.filesystem('memory')+ bucket_34 = fsspec.filesystem('memory')+ return+++def _(fsspec):+ bucket_35 = fsspec.filesystem('memory')+ bucket_36 = fsspec.filesystem('memory')+ bucket_37 = fsspec.filesystem('memory')+ bucket_38 = fsspec.filesystem('memory')+ bucket_39 = fsspec.filesystem('memory')+ return+++def _(fsspec):+ bucket_40 = fsspec.filesystem('memory')+ bucket_41 = fsspec.filesystem('memory')+ bucket_42 = fsspec.filesystem('memory')+ bucket_43 = fsspec.filesystem('memory')+ bucket_44 = fsspec.filesystem('memory')+ return+++def _(fsspec):+ bucket_45 = fsspec.filesystem('memory')+ bucket_46 = fsspec.filesystem('memory')+ bucket_47 = fsspec.filesystem('memory')+ bucket_48 = fsspec.filesystem('memory')+ bucket_49 = fsspec.filesystem('memory')+ return+++def _(mo):+ @mo.cache+ def cached_0(x: int) -> int:+ return x + 0++ @mo.cache+ def cached_1(x: int) -> int:+ return x + 1++ @mo.cache+ def cached_2(x: int) -> int:+ return x + 2++ @mo.cache+ def cached_3(x: int) -> int:+ return x + 3++ @mo.cache+ def cached_4(x: int) -> int:+ return x + 4++ with mo.persistent_cache("stress_cache_0"):+ _ = cached_0(1)+ return+++def _(mo):+ @mo.cache+ def cached_5(x: int) -> int:+ return x + 5++ @mo.cache+ def cached_6(x: int) -> int:+ return x + 6++ @mo.cache+ def cached_7(x: int) -> int:+ return x + 7++ @mo.cache+ def cached_8(x: int) -> int:+ return x + 8++ @mo.cache+ def cached_9(x: int) -> int:+ return x + 9++ with mo.persistent_cache("stress_cache_5"):+ _ = cached_5(1)+ return+++def _(mo):+ @mo.cache+ def cached_10(x: int) -> int:+ return x + 10++ @mo.cache+ def cached_11(x: int) -> int:+ return x + 11++ @mo.cache+ def cached_12(x: int) -> int:+ return x + 12++ @mo.cache+ def cached_13(x: int) -> int:+ return x + 13++ @mo.cache+ def cached_14(x: int) -> int:+ return x + 14++ with mo.persistent_cache("stress_cache_10"):+ _ = cached_10(1)+ return+++def _(mo):+ @mo.cache+ def cached_15(x: int) -> int:+ return x + 15++ @mo.cache+ def cached_16(x: int) -> int:+ return x + 16++ @mo.cache+ def cached_17(x: int) -> int:+ return x + 17++ @mo.cache+ def cached_18(x: int) -> int:+ return x + 18++ @mo.cache+ def cached_19(x: int) -> int:+ return x + 19++ with mo.persistent_cache("stress_cache_15"):+ _ = cached_15(1)+ return+++def _(mo):+ @mo.cache+ def cached_20(x: int) -> int:+ return x + 20++ @mo.cache+ def cached_21(x: int) -> int:+ return x + 21++ @mo.cache+ def cached_22(x: int) -> int:+ return x + 22++ @mo.cache+ def cached_23(x: int) -> int:+ return x + 23++ @mo.cache+ def cached_24(x: int) -> int:+ return x + 24++ with mo.persistent_cache("stress_cache_20"):+ _ = cached_20(1)+ return+++def _(mo):+ @mo.cache+ def cached_25(x: int) -> int:+ return x + 25++ @mo.cache+ def cached_26(x: int) -> int:+ return x + 26++ @mo.cache+ def cached_27(x: int) -> int:+ return x + 27++ @mo.cache+ def cached_28(x: int) -> int:+ return x + 28++ @mo.cache+ def cached_29(x: int) -> int:+ return x + 29++ with mo.persistent_cache("stress_cache_25"):+ _ = cached_25(1)+ return+++def _(mo):+ @mo.cache+ def cached_30(x: int) -> int:+ return x + 30++ @mo.cache+ def cached_31(x: int) -> int:+ return x + 31++ @mo.cache+ def cached_32(x: int) -> int:+ return x + 32++ @mo.cache+ def cached_33(x: int) -> int:+ return x + 33++ @mo.cache+ def cached_34(x: int) -> int:+ return x + 34++ with mo.persistent_cache("stress_cache_30"):+ _ = cached_30(1)+ return+++def _(mo):+ @mo.cache+ def cached_35(x: int) -> int:+ return x + 35++ @mo.cache+ def cached_36(x: int) -> int:+ return x + 36++ @mo.cache+ def cached_37(x: int) -> int:+ return x + 37++ @mo.cache+ def cached_38(x: int) -> int:+ return x + 38++ @mo.cache+ def cached_39(x: int) -> int:+ return x + 39++ with mo.persistent_cache("stress_cache_35"):+ _ = cached_35(1)+ return+++def _(mo):+ @mo.cache+ def cached_40(x: int) -> int:+ return x + 40++ @mo.cache+ def cached_41(x: int) -> int:+ return x + 41++ @mo.cache+ def cached_42(x: int) -> int:+ return x + 42++ @mo.cache+ def cached_43(x: int) -> int:+ return x + 43++ @mo.cache+ def cached_44(x: int) -> int:+ return x + 44++ with mo.persistent_cache("stress_cache_40"):+ _ = cached_40(1)+ return+++def _(mo):+ @mo.cache+ def cached_45(x: int) -> int:+ return x + 45++ @mo.cache+ def cached_46(x: int) -> int:+ return x + 46++ @mo.cache+ def cached_47(x: int) -> int:+ return x + 47++ @mo.cache+ def cached_48(x: int) -> int:+ return x + 48++ @mo.cache+ def cached_49(x: int) -> int:+ return x + 49++ with mo.persistent_cache("stress_cache_45"):+ _ = cached_45(1)+ return+++def _(mo):+ @mo.cache+ def cached_50(x: int) -> int:+ return x + 50++ @mo.cache+ def cached_51(x: int) -> int:+ return x + 51++ @mo.cache+ def cached_52(x: int) -> int:+ return x + 52++ @mo.cache+ def cached_53(x: int) -> int:+ return x + 53++ @mo.cache+ def cached_54(x: int) -> int:+ return x + 54++ with mo.persistent_cache("stress_cache_50"):+ _ = cached_50(1)+ return+++def _(mo):+ @mo.cache+ def cached_55(x: int) -> int:+ return x + 55++ @mo.cache+ def cached_56(x: int) -> int:+ return x + 56++ @mo.cache+ def cached_57(x: int) -> int:+ return x + 57++ @mo.cache+ def cached_58(x: int) -> int:+ return x + 58++ @mo.cache+ def cached_59(x: int) -> int:+ return x + 59++ with mo.persistent_cache("stress_cache_55"):+ _ = cached_55(1)+ return+++def _(mo):+ @mo.cache+ def cached_60(x: int) -> int:+ return x + 60++ @mo.cache+ def cached_61(x: int) -> int:+ return x + 61++ @mo.cache+ def cached_62(x: int) -> int:+ return x + 62++ @mo.cache+ def cached_63(x: int) -> int:+ return x + 63++ @mo.cache+ def cached_64(x: int) -> int:+ return x + 64++ with mo.persistent_cache("stress_cache_60"):+ _ = cached_60(1)+ return+++def _(mo):+ @mo.cache+ def cached_65(x: int) -> int:+ return x + 65++ @mo.cache+ def cached_66(x: int) -> int:+ return x + 66++ @mo.cache+ def cached_67(x: int) -> int:+ return x + 67++ @mo.cache+ def cached_68(x: int) -> int:+ return x + 68++ @mo.cache+ def cached_69(x: int) -> int:+ return x + 69++ with mo.persistent_cache("stress_cache_65"):+ _ = cached_65(1)+ return+++def _(mo):+ @mo.cache+ def cached_70(x: int) -> int:+ return x + 70++ @mo.cache+ def cached_71(x: int) -> int:+ return x + 71++ @mo.cache+ def cached_72(x: int) -> int:+ return x + 72++ @mo.cache+ def cached_73(x: int) -> int:+ return x + 73++ @mo.cache+ def cached_74(x: int) -> int:+ return x + 74++ with mo.persistent_cache("stress_cache_70"):+ _ = cached_70(1)+ return+++def _(mo):+ @mo.cache+ def cached_75(x: int) -> int:+ return x + 75++ @mo.cache+ def cached_76(x: int) -> int:+ return x + 76++ @mo.cache+ def cached_77(x: int) -> int:+ return x + 77++ @mo.cache+ def cached_78(x: int) -> int:+ return x + 78++ @mo.cache+ def cached_79(x: int) -> int:+ return x + 79++ with mo.persistent_cache("stress_cache_75"):+ _ = cached_75(1)+ return+++def _(mo):+ @mo.cache+ def cached_80(x: int) -> int:+ return x + 80++ @mo.cache+ def cached_81(x: int) -> int:+ return x + 81++ @mo.cache+ def cached_82(x: int) -> int:+ return x + 82++ @mo.cache+ def cached_83(x: int) -> int:+ return x + 83++ @mo.cache+ def cached_84(x: int) -> int:+ return x + 84++ with mo.persistent_cache("stress_cache_80"):+ _ = cached_80(1)+ return+++def _(mo):+ @mo.cache+ def cached_85(x: int) -> int:+ return x + 85++ @mo.cache+ def cached_86(x: int) -> int:+ return x + 86++ @mo.cache+ def cached_87(x: int) -> int:+ return x + 87++ @mo.cache+ def cached_88(x: int) -> int:+ return x + 88++ @mo.cache+ def cached_89(x: int) -> int:+ return x + 89++ with mo.persistent_cache("stress_cache_85"):+ _ = cached_85(1)+ return+++def _(mo):+ @mo.cache+ def cached_90(x: int) -> int:+ return x + 90++ @mo.cache+ def cached_91(x: int) -> int:+ return x + 91++ @mo.cache+ def cached_92(x: int) -> int:+ return x + 92++ @mo.cache+ def cached_93(x: int) -> int:+ return x + 93++ @mo.cache+ def cached_94(x: int) -> int:+ return x + 94++ with mo.persistent_cache("stress_cache_90"):+ _ = cached_90(1)+ return+++def _(mo):+ @mo.cache+ def cached_95(x: int) -> int:+ return x + 95++ @mo.cache+ def cached_96(x: int) -> int:+ return x + 96++ @mo.cache+ def cached_97(x: int) -> int:+ return x + 97++ @mo.cache+ def cached_98(x: int) -> int:+ return x + 98++ @mo.cache+ def cached_99(x: int) -> int:+ return x + 99++ with mo.persistent_cache("stress_cache_95"):+ _ = cached_95(1)+ return+++if __name__ == "__main__":+ app.run()