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: lazyer initialization of tools (#6377)

Myles Scolnick211f5f3312d7
diff --git a/marimo/_ai/_tools/base.py b/marimo/_ai/_tools/base.py
index 7a97352e06..5f880875b3 100644
--- a/marimo/_ai/_tools/base.py
+++ b/marimo/_ai/_tools/base.py
@@ -17,10 +17,7 @@ from typing import (
get_origin,
)
-from starlette.applications import (
- Starlette, # noqa: TCH002 - required at runtime for MCP/Pydantic schema validation and isinstance checks
-)
-
+from marimo import _loggers
from marimo._ai._tools.utils.exceptions import ToolExecutionError
from marimo._config.config import CopilotMode
from marimo._server.ai.tools.types import (
@@ -34,6 +31,8 @@ from marimo._types.ids import SessionId
from marimo._utils.dataclass_to_openapi import PythonTypeToOpenAPI
from marimo._utils.parse_dataclass import parse_raw
+LOGGER = _loggers.marimo_logger()
+
ArgsT = TypeVar("ArgsT")
OutT = TypeVar("OutT")
@@ -43,6 +42,10 @@ OutC = TypeVar("OutC", covariant=True)
if TYPE_CHECKING:
from collections.abc import Awaitable, Callable
+ from starlette.applications import (
+ Starlette,
+ )
+
@dataclass
class ToolContext:
@@ -154,6 +157,7 @@ class ToolBase(Generic[ArgsT, OutT], ABC):
raise
except Exception as e:
# Standardize unexpected failures
+ LOGGER.error(f"Unexpected error in tool {self.name}: {e}")
raise ToolExecutionError(
self._default_error_message(),
code=self._default_error_code(),
diff --git a/marimo/_server/ai/providers.py b/marimo/_server/ai/providers.py
index bd67021f7d..a371868d0a 100644
--- a/marimo/_server/ai/providers.py
+++ b/marimo/_server/ai/providers.py
@@ -36,6 +36,8 @@ from marimo._server.ai.config import AnyProviderConfig
from marimo._server.ai.ids import AiModelId
from marimo._server.api.status import HTTPStatus
+TIMEOUT = 30
+
if TYPE_CHECKING:
from anthropic import ( # type: ignore[import-not-found]
AsyncClient,
@@ -489,7 +491,7 @@ class OpenAIProvider(
),
),
"stream": True,
- "timeout": 15,
+ "timeout": TIMEOUT,
}
if tools:
create_params["tools"] = convert_to_openai_tools(tools)
@@ -907,7 +909,7 @@ class BedrockProvider(
),
"max_completion_tokens": max_tokens,
"stream": True,
- "timeout": 15,
+ "timeout": TIMEOUT,
}
if tools:
config["tools"] = convert_to_openai_tools(tools)
diff --git a/marimo/_server/ai/tools/tool_manager.py b/marimo/_server/ai/tools/tool_manager.py
index 4adbfefa6d..cfe7d1d51c 100644
--- a/marimo/_server/ai/tools/tool_manager.py
+++ b/marimo/_server/ai/tools/tool_manager.py
@@ -1,6 +1,7 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
+from functools import cached_property
from typing import TYPE_CHECKING, Any, Callable, Optional
from starlette.applications import (
@@ -15,7 +16,6 @@ from marimo._ai._tools.tools.cells import (
)
from marimo._ai._tools.tools.notebooks import GetActiveNotebooks
from marimo._config.config import CopilotMode
-from marimo._config.manager import get_default_config_manager
from marimo._server.ai.tools.types import (
FunctionArgs,
ToolCallResult,
@@ -23,6 +23,8 @@ from marimo._server.ai.tools.types import (
ToolSource,
ValidationFunction,
)
+from marimo._server.api.deps import AppState
+from marimo._utils.once import once
if TYPE_CHECKING:
from mcp.types import ( # type: ignore[import-not-found]
@@ -43,28 +45,30 @@ class ToolManager:
self._validation_functions: dict[str, ValidationFunction] = {}
self.app: Starlette = app
- # TODO: this may be stale if the config is updated after the tool manager is created
- self._config = get_default_config_manager(
- current_path=None
- ).get_config()
- self._enable_mcp_tools = self._config.get("experimental", {}).get(
- "mcp_docs", False
- )
+ @cached_property
+ def _enable_mcp_tools(self) -> bool:
+ # This may be stale but it is ok, since we want to enable MCP on startup
+ app_state = AppState.from_app(self.app)
+ config = app_state.config_manager.get_config()
+ return bool(config.get("experimental", {}).get("mcp_docs", False))
+
+ @once
+ def _init_backend_tools(self) -> None:
+ """Initialize backend tools."""
+ context = ToolContext(app=self.app)
# Add backend tools here
# Backend tools MUST BE DEFINED in:
# - marimo._ai._tools.tools.*
- tool_context = ToolContext(app=self.app)
-
backend_tools: list[ToolBase[Any, Any]] = [
- GetActiveNotebooks(tool_context),
- GetCellRuntimeData(tool_context),
- GetLightweightCellMap(tool_context),
+ GetActiveNotebooks(context),
+ GetCellRuntimeData(context),
+ GetLightweightCellMap(context),
]
for tool in backend_tools:
- self.register_backend_tool(tool)
+ self._register_backend_tool(tool)
- def register_backend_tool(self, tool: ToolBase[Any, Any]) -> None:
+ def _register_backend_tool(self, tool: ToolBase[Any, Any]) -> None:
"""Register a backend tool with its handler function and optional validator."""
name = tool.name
tool_definition, validation_function = tool.as_backend_tool(
@@ -76,7 +80,7 @@ class ToolManager:
LOGGER.debug(f"Registered backend tool: {name}")
- def register_frontend_tool(self, tool: ToolDefinition) -> None:
+ def _register_frontend_tool(self, tool: ToolDefinition) -> None:
"""Register a frontend tool (definition only - no handler or validator needed)."""
if tool.source != "frontend":
raise ValueError("Tool source must be 'frontend'")
@@ -84,22 +88,32 @@ class ToolManager:
self._tools[tool.name] = tool
LOGGER.debug(f"Registered frontend tool: {tool.name}")
- def get_all_tools(self) -> list[ToolDefinition]:
+ def _get_all_tools(self) -> list[ToolDefinition]:
"""Get all available frontend, backend, and MCP tools."""
+ self._init_backend_tools()
+
local_tools = list(self._tools.values())
- mcp_tools = self.list_mcp_tools()
+ mcp_tools = self._list_mcp_tools()
all_tools = local_tools + mcp_tools
return all_tools
def get_tools_for_mode(self, mode: CopilotMode) -> list[ToolDefinition]:
- """Get all tools available for a specific mode."""
- all_tools = self.get_all_tools()
+ """Get all tools available for a specific mode.
+
+ Args:
+ mode: The mode to get tools for.
+
+ Returns:
+ A list of tool definitions available for the given mode.
+ """
+ all_tools = self._get_all_tools()
return [tool for tool in all_tools if mode in tool.mode]
- def get_tool(
+ def _get_tool(
self, name: str, source: Optional[ToolSource] = None
) -> Optional[ToolDefinition]:
"""Get tool definition by name."""
+
if source:
if source == "backend":
# Check if it's a backend tool
@@ -113,24 +127,24 @@ class ToolManager:
return tool
elif source == "mcp":
# Check MCP tools
- mcp_tools = self.list_mcp_tools()
+ mcp_tools = self._list_mcp_tools()
for mcp_tool in mcp_tools:
if mcp_tool.name == name:
return mcp_tool
return None
else:
# No source specified, check all sources
- all_tools = self.get_all_tools()
+ all_tools = self._get_all_tools()
for tool in all_tools:
if tool.name == name:
return tool
return None
- def validate_backend_tool_arguments(
+ def _validate_backend_tool_arguments(
self, tool_name: str, arguments: FunctionArgs
) -> tuple[bool, str]:
"""Validate tool arguments using tool-specific or basic validation."""
- tool = self.get_tool(tool_name)
+ tool = self._get_tool(tool_name)
if not tool:
return False, f"Tool '{tool_name}' not found"
@@ -162,7 +176,7 @@ class ToolManager:
return True, ""
- def list_mcp_tools(self) -> list[ToolDefinition]:
+ def _list_mcp_tools(self) -> list[ToolDefinition]:
"""Get all MCP tools from the MCP client."""
if not self._enable_mcp_tools:
return []
@@ -172,13 +186,13 @@ class ToolManager:
mcp_client = get_mcp_client()
mcp_tools = mcp_client.get_all_tools()
- return [self.convert_mcp_tool(tool) for tool in mcp_tools]
+ return [self._convert_mcp_tool(tool) for tool in mcp_tools]
except Exception as e:
LOGGER.error(f"Failed to get MCP tools: {str(e)}")
return []
- def convert_mcp_tool(self, mcp_tool: MCPRawTool) -> ToolDefinition:
+ def _convert_mcp_tool(self, mcp_tool: MCPRawTool) -> ToolDefinition:
"""Convert an MCP tool to marimo Tool format."""
# Get namespaced name from meta field (meta is dict[str, Any] | None)
meta = mcp_tool.meta or {}
@@ -199,8 +213,18 @@ class ToolManager:
async def invoke_tool(
self, tool_name: str, arguments: FunctionArgs
) -> ToolCallResult:
- """Invoke a tool by name and return the result."""
- tool = self.get_tool(tool_name)
+ """Invoke a tool by name and return the result.
+
+ Args:
+ tool_name: The name of the tool to invoke.
+ arguments: The arguments to pass to the tool.
+
+ Returns:
+ A ToolCallResult containing the result of the tool invocation.
+ """
+ self._init_backend_tools()
+
+ tool = self._get_tool(tool_name)
if not tool:
return ToolCallResult(
@@ -222,7 +246,7 @@ class ToolManager:
if tool.source == "backend":
# Handle backend tools
is_valid, validation_error = (
- self.validate_backend_tool_arguments(tool_name, arguments)
+ self._validate_backend_tool_arguments(tool_name, arguments)
)
if not is_valid:
return ToolCallResult(
diff --git a/marimo/_utils/once.py b/marimo/_utils/once.py
new file mode 100644
index 0000000000..2774202806
--- /dev/null
+++ b/marimo/_utils/once.py
@@ -0,0 +1,42 @@
+# Copyright 2025 Marimo. All rights reserved.
+import weakref
+from functools import wraps
+from typing import Any, Callable, TypeVar, cast
+
+F = TypeVar("F", bound=Callable[..., Any])
+
+
+def once(func: F) -> F:
+ """
+ Decorator to ensure a function is called only once.
+ For methods, this is once per instance.
+ For regular functions, this is once globally.
+ """
+ # For regular functions (no 'self' argument)
+ called: bool = False
+ # For methods (with 'self' argument) - track per instance
+ instance_called: weakref.WeakKeyDictionary[Any, bool] = (
+ weakref.WeakKeyDictionary()
+ )
+
+ @wraps(func)
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
+ nonlocal called
+
+ # Check if this is a method call (has self as first argument)
+ if args and hasattr(args[0], "__dict__"):
+ # This is likely a method call with 'self'
+ instance = args[0]
+ if instance not in instance_called:
+ instance_called[instance] = False
+
+ if not instance_called[instance]:
+ instance_called[instance] = True
+ return func(*args, **kwargs)
+ else:
+ # This is a regular function call
+ if not called:
+ called = True
+ return func(*args, **kwargs)
+
+ return cast(F, wrapper)
diff --git a/tests/_ai/tools/test_base.py b/tests/_ai/tools/test_base.py
index 7616f31b8d..60edc7b7c7 100644
--- a/tests/_ai/tools/test_base.py
+++ b/tests/_ai/tools/test_base.py
@@ -4,7 +4,10 @@ import inspect
from dataclasses import dataclass
from typing import Any
+import pytest
+
from marimo._ai._tools.base import ToolBase, ToolContext
+from marimo._ai._tools.utils.exceptions import ToolExecutionError
@dataclass
@@ -24,6 +27,19 @@ class _EchoTool(ToolBase[_Args, _Out]):
return _Out(doubled=args.value * 2)
+class _ErrorTool(ToolBase[_Args, _Out]):
+ """Tool that raises errors for testing."""
+
+ def handle(self, args: _Args) -> _Out:
+ if args.value < 0:
+ raise ToolExecutionError(
+ "Negative values not allowed", code="NEGATIVE_VALUE"
+ )
+ if args.value == 0:
+ raise ValueError("Zero is not allowed")
+ return _Out(doubled=args.value * 2)
+
+
def test_as_mcp_tool_fn_returns_async_callable() -> None:
tool = _EchoTool(ToolContext())
handler = tool.as_mcp_tool_fn()
@@ -53,3 +69,59 @@ def test_name_and_description_defaults() -> None:
assert tool.name == "_echo_tool"
# Description defaults to class docstring (stripped)
assert "Dummy tool" in (tool.description or "")
+
+
+async def test_tool_call_with_valid_args() -> None:
+ """Test __call__ method with valid arguments."""
+ tool = _EchoTool(ToolContext())
+ result = await tool(_Args(value=5))
+ assert result.doubled == 10
+
+
+async def test_tool_call_handles_tool_execution_error() -> None:
+ """Test __call__ properly propagates ToolExecutionError."""
+ tool = _ErrorTool(ToolContext())
+ with pytest.raises(ToolExecutionError) as exc_info:
+ await tool(_Args(value=-1))
+ assert exc_info.value.code == "NEGATIVE_VALUE"
+
+
+async def test_tool_call_wraps_unexpected_error() -> None:
+ """Test __call__ wraps unexpected errors in ToolExecutionError."""
+ tool = _ErrorTool(ToolContext())
+ with pytest.raises(ToolExecutionError) as exc_info:
+ await tool(_Args(value=0))
+ assert exc_info.value.code == "UNEXPECTED_ERROR"
+
+
+def test_tool_execution_error_basic() -> None:
+ """Test basic ToolExecutionError functionality."""
+ error = ToolExecutionError("Test error", code="TEST_CODE")
+ assert error.message == "Test error"
+ assert error.code == "TEST_CODE"
+ assert error.is_retryable is False
+
+ # Test structured message is JSON
+ import json
+
+ json.loads(str(error)) # Should not raise
+
+
+def test_as_backend_tool() -> None:
+ """Test as_backend_tool method."""
+ tool = _EchoTool(ToolContext())
+ definition, validator = tool.as_backend_tool(["ask"])
+
+ assert definition.name == "_echo_tool"
+ assert definition.source == "backend"
+ assert definition.mode == ["ask"]
+
+ # Test validator with valid args
+ is_valid, msg = validator({"value": 42})
+ assert is_valid is True
+ assert msg == ""
+
+ # Test validator with invalid args
+ is_valid, msg = validator({"invalid": "field"})
+ assert is_valid is False
+ assert "Invalid arguments" in msg
diff --git a/tests/_ai/tools/tools/test_cells.py b/tests/_ai/tools/tools/test_cells.py
index 566a161d6c..5ae2a18eb5 100644
--- a/tests/_ai/tools/tools/test_cells.py
+++ b/tests/_ai/tools/tools/test_cells.py
@@ -3,6 +3,8 @@ from __future__ import annotations
from dataclasses import dataclass, field
from unittest.mock import Mock
+import pytest
+
from marimo._ai._tools.base import ToolContext
from marimo._ai._tools.tools.cells import (
CellErrors,
@@ -171,3 +173,45 @@ def test_get_cell_variables():
}
assert result == expected
assert "z" not in result
+
+
+def test_get_cell_type_sql():
+ """Test _get_cell_type for SQL cells."""
+ tool = GetLightweightCellMap(ToolContext())
+
+ # Mock cell with SQL language
+ cell_mock = Mock()
+ cell_mock._cell = Mock()
+ cell_mock._cell.language = "sql"
+
+ cell_data = Mock()
+ cell_data.cell = cell_mock
+ cell_data.code = "SELECT * FROM table"
+
+ result = tool._get_cell_type(cell_data)
+ assert result == "sql"
+
+
+def test_get_cell_runtime_data_invalid_cell():
+ """Test GetCellRuntimeData with invalid cell ID."""
+ tool = GetCellRuntimeData(ToolContext())
+
+ # Mock cell manager that returns None
+ mock_cell_manager = Mock()
+ mock_cell_manager.get_cell_data.return_value = None
+
+ mock_session = Mock()
+ mock_session.app_file_manager.app.cell_manager = mock_cell_manager
+
+ context = Mock(spec=ToolContext)
+ context.get_session.return_value = mock_session
+ tool.context = context
+
+ from marimo._ai._tools.tools.cells import GetCellRuntimeDataArgs
+ from marimo._ai._tools.utils.exceptions import ToolExecutionError
+
+ args = GetCellRuntimeDataArgs(session_id="test", cell_id="invalid")
+
+ with pytest.raises(ToolExecutionError) as exc_info:
+ tool.handle(args)
+ assert exc_info.value.code == "CELL_NOT_FOUND"
diff --git a/tests/_ai/tools/tools/test_notebooks.py b/tests/_ai/tools/tools/test_notebooks.py
index 1c5e88815d..7230f4d308 100644
--- a/tests/_ai/tools/tools/test_notebooks.py
+++ b/tests/_ai/tools/tools/test_notebooks.py
@@ -120,3 +120,27 @@ def test_get_active_sessions_internal_multiple_sessions():
assert "s3" in session_ids
assert "s1" in session_ids
assert "s2" not in session_ids
+
+
+def test_get_active_notebooks_handle():
+ """Test GetActiveNotebooks.handle() end-to-end."""
+ tool = GetActiveNotebooks(ToolContext())
+ session = MockSession(
+ ConnectionState.OPEN, "/test/notebook.py", "session1"
+ )
+ session_manager = MockSessionManager({"session1": session})
+ session_manager.get_active_connection_count = Mock(return_value=1)
+
+ context = Mock(spec=ToolContext)
+ context.session_manager = session_manager
+ tool.context = context
+
+ from marimo._ai._tools.types import EmptyArgs
+
+ result = tool.handle(EmptyArgs())
+
+ assert result.status == "success"
+ assert result.data.summary.total_notebooks == 1
+ assert result.data.summary.total_sessions == 1
+ assert result.data.summary.active_connections == 1
+ assert len(result.data.notebooks) == 1
diff --git a/tests/_server/ai/tools/test_tool_manager.py b/tests/_server/ai/tools/test_tool_manager.py
new file mode 100644
index 0000000000..97e5be7c6a
--- /dev/null
+++ b/tests/_server/ai/tools/test_tool_manager.py
@@ -0,0 +1,130 @@
+from __future__ import annotations
+
+import pytest
+from starlette.applications import Starlette
+
+from marimo._config.manager import get_default_config_manager
+from marimo._server.ai.tools.tool_manager import ToolManager
+from marimo._server.ai.tools.types import ToolCallResult
+from tests._server.mocks import get_mock_session_manager
+
+
+def manager():
+ app = Starlette()
+ app.state.config_manager = get_default_config_manager(current_path=None)
+ app.state.session_manager = get_mock_session_manager()
+ manager = ToolManager(app)
+ assert len(manager._tools) == 0 # lazy init
+ return manager
+
+
+def test_get_tools_for_mode(manager: ToolManager):
+ """Test getting tools filtered by mode."""
+
+ # Mock the config to disable MCP
+ tools = manager.get_tools_for_mode("ask")
+
+ # Should have backend tools (GetActiveNotebooks, GetCellRuntimeData, GetLightweightCellMap)
+ assert len(tools) == 3
+ tool_names = {tool.name for tool in tools}
+ assert "get_active_notebooks" in tool_names
+ assert "get_cell_runtime_data" in tool_names
+ assert "get_lightweight_cell_map" in tool_names
+
+ # All should be backend tools for ask mode
+ for tool in tools:
+ assert tool.source == "backend"
+ assert "ask" in tool.mode
+
+
+async def test_invoke_tool_backend_success(manager: ToolManager):
+ """Test successful backend tool invocation."""
+
+ # Mock the config to disable MCP
+ result = await manager.invoke_tool("get_active_notebooks", {})
+
+ assert isinstance(result, ToolCallResult)
+ assert result.tool_name == "get_active_notebooks"
+ assert result.error is None
+ assert result.result is not None
+
+
+async def test_invoke_tool_not_found(manager: ToolManager):
+ """Test invoking non-existent tool."""
+
+ result = await manager.invoke_tool("nonexistent_tool", {})
+
+ assert result.tool_name == "nonexistent_tool"
+ assert result.result is None
+ assert "not found" in result.error or result.error is None
+
+
+async def test_invoke_tool_invalid_arguments(manager: ToolManager):
+ """Test invoking tool with invalid arguments."""
+
+ # Try to invoke with missing required arguments
+ result = await manager.invoke_tool("get_cell_runtime_data", {})
+
+ assert result.tool_name == "get_cell_runtime_data"
+ assert result.result is None
+ assert "Invalid arguments" in result.error or result.error is None
+
+
+def test_validate_backend_tool_arguments(manager: ToolManager):
+ """Test argument validation for backend tools."""
+
+ # Test valid arguments
+ is_valid, error = manager._validate_backend_tool_arguments(
+ "get_cell_runtime_data", {"session_id": "test", "cell_id": "cell1"}
+ )
+ assert is_valid is True
+ assert error == ""
+
+ # Test missing required argument
+ is_valid, error = manager._validate_backend_tool_arguments(
+ "get_cell_runtime_data",
+ {"session_id": "test"}, # missing cell_id
+ )
+ assert is_valid is False
+ assert "missing 1 required positional argument: 'cell_id'" in error
+
+
+def test_get_tool(manager: ToolManager):
+ """Test getting tool by name."""
+
+ manager._init_backend_tools()
+ tools = manager.get_tools_for_mode("ask")
+ assert len(tools) > 0
+
+ # Get backend tool
+ tool = manager._get_tool("get_active_notebooks", source="backend")
+ assert tool is not None
+ assert tool.name == "get_active_notebooks"
+ assert tool.source == "backend"
+
+ # Get non-existent tool
+ tool = manager._get_tool("nonexistent", source="backend")
+ assert tool is None
+
+
+def test_backend_tools_validation(manager: ToolManager):
+ """Test validation for backend tools."""
+ tools = manager._get_all_tools()
+ assert len(tools) > 0
+
+ backend_tools = [tool for tool in tools if tool.source == "backend"]
+ assert len(backend_tools) > 0
+
+ for tool in backend_tools:
+ assert tool.name
+ assert tool.description
+ assert tool.parameters
+ assert tool.source
+ assert tool.mode
+
+ # Validation of none
+ is_valid, error = manager._validation_functions[tool.name](
+ {"invalid": "argument"}
+ )
+ assert is_valid is False, error
diff --git a/tests/_utils/test_once.py b/tests/_utils/test_once.py
new file mode 100644
index 0000000000..398cb2963c
--- /dev/null
+++ b/tests/_utils/test_once.py
@@ -0,0 +1,403 @@
+# Copyright 2025 Marimo. All rights reserved.
+from typing import Any
+
+import pytest
+
+from marimo._utils.once import once
+
+
+def test_once_basic_functionality() -> None:
+ """Test that a function decorated with @once is called only once."""
+ call_count = 0
+
+ @once
+ def increment() -> int:
+ nonlocal call_count
+ call_count += 1
+ return call_count
+
+ # First call should execute
+ result1 = increment()
+ assert result1 == 1
+ assert call_count == 1
+
+ # Subsequent calls should not execute
+ result2 = increment()
+ assert result2 is None # Returns None on subsequent calls
+ assert call_count == 1
+
+ # Multiple calls should still not execute
+ increment()
+ increment()
+ assert call_count == 1
+
+
+def test_once_with_arguments() -> None:
+ """Test that @once works with functions that take arguments."""
+ call_count = 0
+ last_args = None
+ last_kwargs = None
+
+ @once
+ def test_func(a: int, b: str, c: int = 10) -> tuple[int, str, int]:
+ nonlocal call_count, last_args, last_kwargs
+ call_count += 1
+ last_args = (a, b, c)
+ return a, b, c
+
+ # First call with arguments
+ result1 = test_func(1, "hello", c=20)
+ assert result1 == (1, "hello", 20)
+ assert call_count == 1
+ assert last_args == (1, "hello", 20)
+
+ # Second call with different arguments - should not execute
+ result2 = test_func(2, "world", c=30)
+ assert result2 is None
+ assert call_count == 1
+ assert last_args == (1, "hello", 20) # Should still be from first call
+
+
+def test_once_with_return_value() -> None:
+ """Test that @once preserves the return value from the first call."""
+
+ @once
+ def get_value() -> str:
+ return "hello world"
+
+ result1 = get_value()
+ assert result1 == "hello world"
+
+ result2 = get_value()
+ assert result2 is None # Subsequent calls return None
+
+
+def test_once_with_side_effects() -> None:
+ """Test that @once prevents side effects from happening multiple times."""
+ side_effects = []
+
+ @once
+ def side_effect_func() -> None:
+ side_effects.append("executed")
+
+ side_effect_func()
+ assert side_effects == ["executed"]
+
+ side_effect_func()
+ side_effect_func()
+ assert side_effects == ["executed"] # Should still be just one
+
+
+def test_once_with_exception() -> None:
+ """Test that @once handles exceptions properly."""
+ call_count = 0
+
+ @once
+ def failing_func() -> None:
+ nonlocal call_count
+ call_count += 1
+ raise ValueError("Test error")
+
+ # First call should raise exception
+ with pytest.raises(ValueError, match="Test error"):
+ failing_func()
+ assert call_count == 1
+
+ # Subsequent calls should not execute (and not raise)
+ result = failing_func()
+ assert result is None
+ assert call_count == 1
+
+
+def test_once_on_class_method() -> None:
+ """Test that @once works on class methods and is per-instance."""
+
+ class TestClass:
+ def __init__(self) -> None:
+ self.call_count = 0
+
+ @once
+ def method(self) -> int:
+ self.call_count += 1
+ return self.call_count
+
+ # Test first instance
+ instance1 = TestClass()
+ result1 = instance1.method()
+ assert result1 == 1
+ assert instance1.call_count == 1
+
+ result2 = instance1.method()
+ assert result2 is None
+ assert instance1.call_count == 1
+
+ # Test second instance - should be independent (per-instance behavior)
+ instance2 = TestClass()
+ result3 = instance2.method()
+ assert result3 == 1 # Should execute because it's a different instance
+ assert instance2.call_count == 1
+
+ # Second instance subsequent call should be blocked
+ result4 = instance2.method()
+ assert result4 is None
+ assert instance2.call_count == 1
+
+ # First instance should still be blocked
+ instance1.method()
+ assert instance1.call_count == 1
+
+
+def test_once_on_static_method() -> None:
+ """Test that @once works on static methods."""
+ call_count = 0
+
+ class TestClass:
+ @staticmethod
+ @once
+ def static_method() -> int:
+ nonlocal call_count
+ call_count += 1
+ return call_count
+
+ result1 = TestClass.static_method()
+ assert result1 == 1
+ assert call_count == 1
+
+ result2 = TestClass.static_method()
+ assert result2 is None
+ assert call_count == 1
+
+ # Calling from different instances should still be blocked
+ instance = TestClass()
+ result3 = instance.static_method()
+ assert result3 is None
+ assert call_count == 1
+
+
+def test_once_on_class_method_decorator() -> None:
+ """Test that @once works with @classmethod."""
+ call_count = 0
+
+ class TestClass:
+ @classmethod
+ @once
+ def class_method(cls) -> int:
+ nonlocal call_count
+ call_count += 1
+ return call_count
+
+ result1 = TestClass.class_method()
+ assert result1 == 1
+ assert call_count == 1
+
+ result2 = TestClass.class_method()
+ assert result2 is None
+ assert call_count == 1
+
+
+def test_once_preserves_function_metadata() -> None:
+ """Test that @once preserves function name and docstring."""
+
+ @once
+ def documented_function() -> str:
+ """This is a test function."""
+ return "test"
+
+ assert documented_function.__name__ == "documented_function"
+ assert documented_function.__doc__ == "This is a test function."
+
+
+def test_once_multiple_decorators() -> None:
+ """Test that @once works with other decorators."""
+ call_count = 0
+
+ def another_decorator(func):
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
+ return f"decorated: {func(*args, **kwargs)}"
+
+ return wrapper
+
+ @another_decorator
+ @once
+ def test_func() -> str:
+ nonlocal call_count
+ call_count += 1
+ return "hello"
+
+ result1 = test_func()
+ assert result1 == "decorated: hello"
+ assert call_count == 1
+
+ result2 = test_func()
+ assert result2 == "decorated: None"
+ assert call_count == 1
+
+
+def test_once_with_complex_return_types() -> None:
+ """Test that @once works with complex return types."""
+
+ @once
+ def return_dict() -> dict[str, int]:
+ return {"a": 1, "b": 2}
+
+ @once
+ def return_list() -> list[str]:
+ return ["hello", "world"]
+
+ result1 = return_dict()
+ assert result1 == {"a": 1, "b": 2}
+
+ result2 = return_dict()
+ assert result2 is None
+
+ result3 = return_list()
+ assert result3 == ["hello", "world"]
+
+ result4 = return_list()
+ assert result4 is None
+
+
+def test_once_thread_safety_simulation() -> None:
+ """Test that @once behaves predictably in concurrent-like scenarios."""
+ call_count = 0
+ results = []
+
+ @once
+ def concurrent_func() -> int:
+ nonlocal call_count
+ call_count += 1
+ return call_count
+
+ # Simulate multiple "concurrent" calls
+ for _ in range(10):
+ result = concurrent_func()
+ results.append(result)
+
+ # Only first call should have executed
+ assert call_count == 1
+ assert results[0] == 1
+ assert all(r is None for r in results[1:])
+
+
+class OnceClassLevel:
+ """Test class to demonstrate per-class behavior of @once."""
+
+ def __init__(self) -> None:
+ self.instance_call_count = 0
+
+ @once
+ def instance_method(self) -> str:
+ self.instance_call_count += 1
+ return f"instance_{self.instance_call_count}"
+
+
+def test_once_class_level_behavior() -> None:
+ """Test that @once on methods is per-instance, not per-class."""
+ # Create multiple instances
+ obj1 = OnceClassLevel()
+ obj2 = OnceClassLevel()
+ obj3 = OnceClassLevel()
+
+ # Each instance should be able to call the method once
+ result1 = obj1.instance_method()
+ assert result1 == "instance_1"
+ assert obj1.instance_call_count == 1
+
+ # Each instance should be independent
+ result2 = obj2.instance_method()
+ assert result2 == "instance_1"
+ assert obj2.instance_call_count == 1
+
+ result3 = obj3.instance_method()
+ assert result3 == "instance_1"
+ assert obj3.instance_call_count == 1
+
+ # Subsequent calls on same instances should return None
+ assert obj1.instance_method() is None
+ assert obj2.instance_method() is None
+ assert obj3.instance_method() is None
+
+ # Call counts should remain the same
+ assert obj1.instance_call_count == 1
+ assert obj2.instance_call_count == 1
+ assert obj3.instance_call_count == 1
+
+
+def test_once_inheritance() -> None:
+ """Test that @once works correctly with inheritance."""
+
+ class Parent:
+ def __init__(self) -> None:
+ self.parent_calls = 0
+
+ @once
+ def parent_method(self) -> str:
+ self.parent_calls += 1
+ return "parent"
+
+ class Child(Parent):
+ def __init__(self) -> None:
+ super().__init__()
+ self.child_calls = 0
+
+ @once
+ def child_method(self) -> str:
+ self.child_calls += 1
+ return "child"
+
+ child = Child()
+
+ # Test parent method
+ assert child.parent_method() == "parent"
+ assert child.parent_calls == 1
+ assert child.parent_method() is None
+ assert child.parent_calls == 1
+
+ # Test child method
+ assert child.child_method() == "child"
+ assert child.child_calls == 1
+ assert child.child_method() is None
+ assert child.child_calls == 1
+
+
+def test_once_memory_cleanup() -> None:
+ """Test that @once properly cleans up memory with weak references."""
+ import gc
+
+ class TestClass:
+ def __init__(self, value: str) -> None:
+ self.value = value
+ self.call_count = 0
+
+ @once
+ def method(self) -> str:
+ self.call_count += 1
+ return f"{self.value}_{self.call_count}"
+
+ # Create instances and call methods
+ instance1 = TestClass("test1")
+ instance2 = TestClass("test2")
+
+ result1 = instance1.method()
+ result2 = instance2.method()
+
+ assert result1 == "test1_1"
+ assert result2 == "test2_1"
+
+ # Delete instances
+ del instance1
+ del instance2
+
+ # Force garbage collection
+ gc.collect()
+
+ # Create new instances with same values
+ instance3 = TestClass("test1")
+ instance4 = TestClass("test2")
+
+ # These should work because old instances were cleaned up
+ result3 = instance3.method()
+ result4 = instance4.method()
+
+ assert result3 == "test1_1" # Should execute because it's a new instance
+ assert result4 == "test2_1" # Should execute because it's a new instance