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.

chore: profile kernel execution (#2088)

Akshay Agrawal9968200e28d3
diff --git a/development_docs/traces.md b/development_docs/traces.md
index 1e2c2f293d..471904422e 100644
--- a/development_docs/traces.md
+++ b/development_docs/traces.md
@@ -1,4 +1,6 @@
-# Server Telemetry
+# Tracing and profiling
+
+## Server traces
For debugging purposes, we emit OpenTelemetry traces from the server. We emit traces to `~/.marimo/traces/spans.jsonl`. We don't emit any sensitive information in the traces, and these traces stay local to your machine. The traces get wiped on each sever restart.
@@ -8,10 +10,24 @@ You can analyze the traces using tools like Jaeger or Zipkin, or our marimo note
marimo edit scripts/analyze_traces.py
```
-## Enable Traces
+### Enable Traces
To enable traces, set the `MARIMO_TRACING` environment variable to `true`:
```bash
MARIMO_TRACING=true ./your_server_command
```
+
+## Profiling the kernel
+
+You can generate profiling statistics of the kernel in edit mode using the
+hidden --profile-dir command-line option:
+
+```bash
+marimo edit --profile-dir profiles/ notebook.py
+```
+
+If the notebook exits gracefully (i.e., is shut down manually), profiling
+statistics will be written to the profiles/ directory. You can then use
+standard tools to analyze the dumped statistics. To view flamegraphs,
+we recommend snakeviz or tuna (`pip install snakeviz; snakeviz path_to_profile`)
diff --git a/marimo/_cli/cli.py b/marimo/_cli/cli.py
index b4a04eddf2..fe073e8a4b 100644
--- a/marimo/_cli/cli.py
+++ b/marimo/_cli/cli.py
@@ -254,6 +254,7 @@ edit_help_msg = "\n".join(
type=bool,
help="Don't check if a new version of marimo is available for download.",
)
[email protected]("--profile-dir", default=None, type=str, hidden=True)
@click.argument("name", required=False)
@click.argument("args", nargs=-1, type=click.UNPROCESSED)
def edit(
@@ -266,9 +267,11 @@ def edit(
base_url: str,
allow_origins: Optional[tuple[str, ...]],
skip_update_check: bool,
+ profile_dir: Optional[str],
name: Optional[str],
args: tuple[str, ...],
) -> None:
+ GLOBAL_SETTINGS.PROFILE_DIR = profile_dir
if not skip_update_check and os.getenv("MARIMO_SKIP_UPDATE_CHECK") != "1":
GLOBAL_SETTINGS.CHECK_STATUS_UPDATE = True
# Check for version updates
diff --git a/marimo/_config/settings.py b/marimo/_config/settings.py
index 4a2372b3f5..b16bc54d91 100644
--- a/marimo/_config/settings.py
+++ b/marimo/_config/settings.py
@@ -11,6 +11,7 @@ class GlobalSettings:
QUIET: bool = False
CHECK_STATUS_UPDATE: bool = False
TRACING: bool = os.getenv("MARIMO_TRACING", "false") in ("true", "1")
+ PROFILE_DIR: str | None = None
GLOBAL_SETTINGS = GlobalSettings()
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index 19bf3158ec..e7a6ae228f 100644
--- a/marimo/_runtime/runtime.py
+++ b/marimo/_runtime/runtime.py
@@ -1722,11 +1722,19 @@ def launch_kernel(
virtual_files_supported: bool,
redirect_console_to_browser: bool,
interrupt_queue: QueueType[bool] | None = None,
+ profile_path: Optional[str] = None,
) -> None:
LOGGER.debug("Launching kernel")
if is_edit_mode:
restore_signals()
+ profiler = None
+ if profile_path is not None:
+ import cProfile
+
+ profiler = cProfile.Profile()
+ profiler.enable()
+
n_tries = 0
pipe: Optional[TypedConnection[KernelMessage]] = None
while n_tries < 100:
@@ -1853,3 +1861,7 @@ def launch_kernel(
if stderr is not None:
stderr._watcher.stop()
get_context().virtual_file_registry.shutdown()
+
+ if profiler is not None and profile_path is not None:
+ profiler.disable()
+ profiler.dump_stats(profile_path)
diff --git a/marimo/_server/sessions.py b/marimo/_server/sessions.py
index 687ec2737e..c54358d78d 100644
--- a/marimo/_server/sessions.py
+++ b/marimo/_server/sessions.py
@@ -23,6 +23,7 @@ import signal
import subprocess
import sys
import threading
+import time
from multiprocessing import connection
from multiprocessing.queues import Queue as MPQueue
from pathlib import Path
@@ -33,6 +34,7 @@ from marimo import _loggers
from marimo._ast.cell import CellConfig, CellId_t
from marimo._cli.print import red
from marimo._config.manager import UserConfigManager
+from marimo._config.settings import GLOBAL_SETTINGS
from marimo._messaging.ops import (
Alert,
FocusCell,
@@ -190,6 +192,7 @@ class KernelManager:
self._virtual_files_supported,
self.redirect_console_to_browser,
self.queue_manager.win32_interrupt_queue,
+ self.profile_path,
),
# The process can't be a daemon, because daemonic processes
# can't create children
@@ -231,6 +234,8 @@ class KernelManager:
self.redirect_console_to_browser,
# win32 interrupt queue
None,
+ # profile path
+ None,
),
# daemon threads can create child processes, unlike
# daemon processes
@@ -242,6 +247,27 @@ class KernelManager:
# call accept
self._read_conn = TypedConnection[KernelMessage].of(listener.accept())
+ @property
+ def profile_path(self) -> str | None:
+ self._profile_path: str | None
+
+ if hasattr(self, "_profile_path"):
+ return self._profile_path
+
+ profile_dir = GLOBAL_SETTINGS.PROFILE_DIR
+ if profile_dir is not None:
+ self._profile_path = os.path.join(
+ profile_dir,
+ (
+ os.path.basename(self.app_metadata.filename) + str(uuid4())
+ if self.app_metadata.filename is not None
+ else str(uuid4())
+ ),
+ )
+ else:
+ self._profile_path = None
+ return self._profile_path
+
def is_alive(self) -> bool:
return self.kernel_task is not None and self.kernel_task.is_alive()
@@ -262,6 +288,19 @@ class KernelManager:
assert self.kernel_task is not None, "kernel not started"
if isinstance(self.kernel_task, mp.Process):
+ if self.profile_path is not None and self.kernel_task.is_alive():
+ self.queue_manager.control_queue.put(requests.StopRequest())
+ # Hack: Wait for kernel to exit and write out profile;
+ # joining the process hangs, but not sure why.
+ print(
+ "\tWriting profile statistics to",
+ self.profile_path,
+ " ...",
+ )
+ while not os.path.exists(self.profile_path):
+ time.sleep(0.1)
+ time.sleep(1)
+
self.queue_manager.close_queues()
if self.kernel_task.is_alive():
self.kernel_task.terminate()