Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

improvement: fallback to jedi interpeter in completion (#1559)

Akshay Agrawalba31235c1617
diff --git a/marimo/_runtime/complete.py b/marimo/_runtime/complete.py
index da9c472b4b..07674dabc7 100644
--- a/marimo/_runtime/complete.py
+++ b/marimo/_runtime/complete.py
@@ -2,7 +2,9 @@
from __future__ import annotations
import html
-from typing import cast
+import threading
+import time
+from typing import TYPE_CHECKING, Any, cast
import jedi # type: ignore # noqa: F401
import jedi.api # type: ignore # noqa: F401
@@ -18,9 +20,18 @@ from marimo._server.types import QueueType
from marimo._utils.format_signature import format_signature
from marimo._utils.rst_to_html import convert_rst_to_html
+if TYPE_CHECKING:
+ import threading
+
LOGGER = loggers.marimo_logger()
+# Don't execute properties or __get_item__: when falling back to the Jedi
+# interpreter, this leads to an incorrect type hint of properties as modules,
+# but at least it prevents execution of side-effecting code.
+jedi.settings.allow_unsafe_interpreter_executions = False
+
+
def _is_dunder_name(name: str) -> bool:
return name.startswith("__") and name.endswith("__")
@@ -146,32 +157,77 @@ def _get_type_hint(completion: jedi.api.classes.BaseName) -> str:
def _get_completion_info(completion: jedi.api.classes.BaseName) -> str:
if completion.type != "statement":
- return _get_docstring(completion)
+ try:
+ return _get_docstring(completion)
+ except Exception as e:
+ LOGGER.debug("jedi failed to get docstring: %s", str(e))
+ return ""
else:
- return _get_type_hint(completion)
+ try:
+ return _get_type_hint(completion)
+ except Exception as e:
+ LOGGER.debug("jedi failed to get type hint: %s", str(e))
+ return ""
-def _get_completion_options(
- completion: jedi.api.classes.BaseName, script: jedi.Script
+def _get_completion_option(
+ completion: jedi.api.classes.Completion,
+ script: jedi.Script,
+ compute_completion_info: bool,
) -> CompletionOption:
name = completion.name
kind = completion.type
- # Choose whether the completion info should be from the name
- # or the enclosing function's signature, if any
- symbol_to_lookup = completion
- if completion.type == "param":
- # Show the function/class docstring if available
- signatures = script.get_signatures()
- if len(signatures) == 1:
- symbol_to_lookup = signatures[0]
- completion_info = _get_completion_info(symbol_to_lookup)
+ if compute_completion_info:
+ # Choose whether the completion info should be from the name
+ # or the enclosing function's signature, if any
+ symbol_to_lookup = completion
+ if completion.type == "param":
+ # Show the function/class docstring if available
+ signatures = script.get_signatures()
+ if len(signatures) == 1:
+ symbol_to_lookup = signatures[0]
+ completion_info = _get_completion_info(symbol_to_lookup)
+ else:
+ completion_info = ""
return CompletionOption(
name=name, type=kind, completion_info=completion_info
)
+def _get_completion_options(
+ completions: list[jedi.api.classes.Completion],
+ script: jedi.Script,
+ prefix: str,
+ limit: int,
+ timeout: float,
+) -> list[CompletionOption]:
+ if len(completions) > limit:
+ return [
+ _get_completion_option(
+ completion, script, compute_completion_info=False
+ )
+ for completion in completions
+ if _should_include_name(completion.name, prefix)
+ ]
+
+ completion_options: list[CompletionOption] = []
+ start_time = time.time()
+ for completion in completions:
+ if not _should_include_name(completion.name, prefix):
+ continue
+ elapsed_time = time.time() - start_time
+ completion_options.append(
+ _get_completion_option(
+ completion,
+ script,
+ compute_completion_info=elapsed_time < timeout,
+ )
+ )
+ return completion_options
+
+
def _write_completion_result(
stream: Stream,
completion_id: str,
@@ -200,24 +256,90 @@ def _drain_queue(
return request
-def completion_worker(
- completion_queue: QueueType[CompletionRequest],
- graph: dataflow.DirectedGraph,
- stream: Stream,
-) -> None:
- """Code completion worker"""
-
- while True:
- request = _drain_queue(completion_queue)
- complete(request, graph, stream)
+def _get_completions_with_script(
+ codes: list[str], document: str
+) -> tuple[jedi.Script, list[jedi.api.classes.Completion]]:
+ script = jedi.Script("\n".join(codes + [document]))
+ completions = script.complete()
+ return script, completions
+
+
+def _get_completions_with_interpreter(
+ document: str, glbls: dict[str, Any], glbls_lock: threading.RLock
+) -> tuple[jedi.Script, list[jedi.api.classes.Completion]]:
+ # Jedi fails to statically analyze some libraries, like ibis,
+ # so we fall back to interpreter-based completions.
+ #
+ # Interpreter-based completions execute code, so we need to grab a
+ # lock on the globals dict. This is best-effort -- if the kernel
+ # has locked globals, we simply don't complete instead of waiting
+ # for the lock to be released.
+ script = jedi.Interpreter(document, [glbls])
+ locked = False
+ completions = []
+ locked = glbls_lock.acquire(blocking=False)
+ if locked:
+ completions = script.complete()
+ return script, completions
+
+
+def _get_completions(
+ codes: list[str],
+ document: str,
+ glbls: dict[str, Any],
+ glbls_lock: threading.RLock,
+ prefer_interpreter_completion: bool,
+) -> tuple[jedi.Script, list[jedi.api.classes.Completion]]:
+ if prefer_interpreter_completion:
+ script, completions = _get_completions_with_interpreter(
+ document, glbls, glbls_lock
+ )
+ if not completions:
+ script, completions = _get_completions_with_script(codes, document)
+ return script, completions
+ else:
+ script, completions = _get_completions_with_script(codes, document)
+ if not completions:
+ script, completions = _get_completions_with_interpreter(
+ document, glbls, glbls_lock
+ )
+ return script, completions
def complete(
request: CompletionRequest,
graph: dataflow.DirectedGraph,
+ glbls: dict[str, Any],
+ glbls_lock: threading.RLock,
stream: Stream,
- docstrings_limit: int = 1000,
+ docstrings_limit: int = 80,
+ timeout: float | None = None,
+ prefer_interpreter_completion: bool = False,
) -> None:
+ """Gets code completions for a request.
+
+ If `prefer_interpreter_completion`, a runtime-based method is used,
+ falling back to a static analysis method. Otherwise the static method
+ is used, with the interpreter method as a fallback.
+
+ Static completions are safer since they don't execute code, but they
+ are slower and sometimes fail. Interpreter executions are faster
+ and more comprehensive, but can only be carried out when the kernel
+ isn't executing or otherwise handling a request.
+
+ **Args.**
+
+ - `request`: the completion request
+ - `graph`: dataflow graph backing the marimo program
+ - `glbls`: global namespace
+ - `glbls_lock`: lock protecting the global namespace, for interpreter-based
+ completion
+ - `stream`: Stream through which to communicate completion results
+ - `docstrings_limit`: limit past which we won't attempt to fetch type hints
+ and docstrings
+ - `timeout`: timeout after which we'll stop fetching type hints/docstrings
+ - `prefer_interpreter_completion`: whether to prefer interpreter completion
+ """
if not request.document.strip():
_write_no_completions(stream, request.id)
return
@@ -232,8 +354,13 @@ def complete(
]
try:
- script = jedi.Script("\n".join(codes + [request.document]))
- completions = script.complete()
+ script, completions = _get_completions(
+ codes,
+ request.document,
+ glbls,
+ glbls_lock,
+ prefer_interpreter_completion,
+ )
prefix_length = (
completions[0].get_completion_prefix_length() if completions else 0
)
@@ -246,7 +373,7 @@ def complete(
and len(request.document) >= 1
and request.document[-1] != "."
):
- # Don't complete ...
+ # Empty prefix, not dot notation; don't complete ...
completions = []
# Get docstring in function context. A bit of a hack, since
@@ -278,18 +405,21 @@ def complete(
return
prefix = request.document[-prefix_length:]
- if len(completions) < docstrings_limit:
- options = [
- _get_completion_options(c, script)
- for c in completions
- if _should_include_name(c.name, prefix)
- ]
- else:
- options = [
- CompletionOption(name=c.name, type=c.type, completion_info="")
- for c in completions
- if _should_include_name(c.name, prefix)
- ]
+ if timeout is None and isinstance(script, jedi.Interpreter):
+ # We're holding the globals lock; set a short timeout so we don't
+ # block the kernel
+ timeout = 1
+ elif timeout is None:
+ # We're not blocking the kernel so we can afford to take longer
+ timeout = 2
+
+ options = _get_completion_options(
+ completions,
+ script,
+ prefix=prefix,
+ limit=docstrings_limit,
+ timeout=timeout,
+ )
_write_completion_result(
stream=stream,
completion_id=request.id,
@@ -300,3 +430,40 @@ def complete(
# jedi failed to provide completion
LOGGER.debug("Completion with jedi failed: ", str(e))
_write_no_completions(stream, request.id)
+ finally:
+ try:
+ # if an interpreter was used, the lock might be held
+ glbls_lock.release()
+ except Exception:
+ # RLock raises if released when not acquired.
+ pass
+
+
+def completion_worker(
+ completion_queue: QueueType[CompletionRequest],
+ graph: dataflow.DirectedGraph,
+ glbls: dict[str, Any],
+ glbls_lock: threading.RLock,
+ stream: Stream,
+) -> None:
+ """Code completion worker.
+
+
+ **Args:**
+
+ - `completion_queue`: queue from which requests are pulled.
+ - `graph`: dataflow graph backing the marimo program
+ - `glbls`: dictionary of global variables in interpreter memory
+ - `glbls_lock`: lock protecting globals
+ - `stream`: stream used to communicate completion results
+ """
+
+ while True:
+ request = _drain_queue(completion_queue)
+ complete(
+ request=request,
+ graph=graph,
+ glbls=glbls,
+ glbls_lock=glbls_lock,
+ stream=stream,
+ )
diff --git a/marimo/_runtime/context/utils.py b/marimo/_runtime/context/utils.py
index 31b0dede2c..9dfb0cf731 100644
--- a/marimo/_runtime/context/utils.py
+++ b/marimo/_runtime/context/utils.py
@@ -1,9 +1,8 @@
# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
from marimo._output.rich_help import mddoc
-from marimo._runtime.context import (
- ContextNotInitializedError,
- get_context,
-)
+from marimo._runtime.context import ContextNotInitializedError, get_context
from marimo._runtime.context.kernel_context import KernelRuntimeContext
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index a2b5ad3fbb..ced3f04bf8 100644
--- a/marimo/_runtime/runtime.py
+++ b/marimo/_runtime/runtime.py
@@ -287,6 +287,8 @@ class Kernel:
self.stderr = stderr
self.stdin = stdin
self.enqueue_control_request = enqueue_control_request
+ self._globals_lock = threading.RLock()
+ self._completion_worker_started = False
self.debugger = debugger_override
if self.debugger is not None:
@@ -394,20 +396,45 @@ class Kernel:
def globals(self) -> dict[Any, Any]:
return self._module.__dict__
+ @contextlib.contextmanager
+ def lock_globals(self) -> Iterator[None]:
+ # The only other thread accessing globals is the completion worker. If
+ # we haven't started a completion worker, there's no need to lock
+ # globals.
+ if self._completion_worker_started:
+ with self._globals_lock:
+ yield
+ else:
+ yield
+
def start_completion_worker(
self, completion_queue: QueueType[CompletionRequest]
) -> None:
"""Must be called after context is initialized"""
threading.Thread(
target=completion_worker,
- args=(completion_queue, self.graph, get_context().stream),
+ args=(
+ completion_queue,
+ self.graph,
+ self.globals,
+ self._globals_lock,
+ get_context().stream,
+ ),
daemon=True,
).start()
+ self._completion_worker_started = True
def code_completion(
self, request: CompletionRequest, docstrings_limit: int
) -> None:
- complete(request, self.graph, get_context().stream, docstrings_limit)
+ complete(
+ request,
+ self.graph,
+ self.globals,
+ self._globals_lock,
+ get_context().stream,
+ docstrings_limit,
+ )
@contextlib.contextmanager
def _install_execution_context(
@@ -1336,41 +1363,46 @@ class Kernel:
"""Handle a message from the client.
The message is dispatched to the appropriate method based on its type.
+
+ Coarsely locks globals to avoid race conditions with code completion.
"""
- if isinstance(request, CreationRequest):
- await self.instantiate(request)
- CompletedRun().broadcast()
- elif isinstance(request, ExecuteMultipleRequest):
- await self.run(request.execution_requests)
- CompletedRun().broadcast()
- elif isinstance(request, ExecuteStaleRequest):
- await self.run_stale_cells()
- elif isinstance(request, SetCellConfigRequest):
- await self.set_cell_config(request)
- elif isinstance(request, SetUserConfigRequest):
- self.set_user_config(request)
- elif isinstance(request, SetUIElementValueRequest):
- await self.set_ui_element_value(request)
- CompletedRun().broadcast()
- elif isinstance(request, FunctionCallRequest):
- status, ret = await self.function_call_request(request)
- FunctionCallResult(
- function_call_id=request.function_call_id,
- return_value=ret,
- status=status,
- ).broadcast()
- CompletedRun().broadcast()
- elif isinstance(request, DeleteRequest):
- await self.delete(request)
- elif isinstance(request, InstallMissingPackagesRequest):
- await self.install_missing_packages(request)
- CompletedRun().broadcast()
- elif isinstance(request, PreviewDatasetColumnRequest):
- await self.preview_dataset_column(request)
- elif isinstance(request, StopRequest):
- return None
- else:
- raise ValueError(f"Unknown request {request}")
+ # acquiring and releasing an RLock takes ~100ns; the overhead is
+ # negligible because the lock is coarse.
+ with self.lock_globals():
+ if isinstance(request, CreationRequest):
+ await self.instantiate(request)
+ CompletedRun().broadcast()
+ elif isinstance(request, ExecuteMultipleRequest):
+ await self.run(request.execution_requests)
+ CompletedRun().broadcast()
+ elif isinstance(request, ExecuteStaleRequest):
+ await self.run_stale_cells()
+ elif isinstance(request, SetCellConfigRequest):
+ await self.set_cell_config(request)
+ elif isinstance(request, SetUserConfigRequest):
+ self.set_user_config(request)
+ elif isinstance(request, SetUIElementValueRequest):
+ await self.set_ui_element_value(request)
+ CompletedRun().broadcast()
+ elif isinstance(request, FunctionCallRequest):
+ status, ret = await self.function_call_request(request)
+ FunctionCallResult(
+ function_call_id=request.function_call_id,
+ return_value=ret,
+ status=status,
+ ).broadcast()
+ CompletedRun().broadcast()
+ elif isinstance(request, DeleteRequest):
+ await self.delete(request)
+ elif isinstance(request, InstallMissingPackagesRequest):
+ await self.install_missing_packages(request)
+ CompletedRun().broadcast()
+ elif isinstance(request, PreviewDatasetColumnRequest):
+ await self.preview_dataset_column(request)
+ elif isinstance(request, StopRequest):
+ return None
+ else:
+ raise ValueError(f"Unknown request {request}")
def launch_kernel(