This repository was archived by the owner on Aug 24, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
feat: concurrent-writer driver with convergence verification (bm#1248) #42
Closed
Closed
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,174 @@ | ||
| """Shared helpers for driving an external Basic Memory runtime. | ||
|
|
||
| Everything here talks to Basic Memory through its public contracts only — the | ||
| `bm` CLI and the `bm mcp` stdio server — never through internal imports, so the | ||
| same code runs unchanged against any BM version under comparison (installed | ||
| `bm`, or a checkout via ``uv run --project <path> basic-memory``). | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import asyncio | ||
| import threading | ||
| from concurrent.futures import Future | ||
| from dataclasses import dataclass | ||
| from pathlib import Path | ||
| from queue import Queue | ||
| from typing import Any | ||
|
|
||
| import anyio | ||
| from mcp.client.session import ClientSession | ||
| from mcp.client.stdio import StdioServerParameters, stdio_client | ||
| from mcp.types import CallToolResult | ||
|
|
||
|
|
||
| @dataclass | ||
| class _McpToolRequest: | ||
| name: str | ||
| arguments: dict[str, Any] | ||
| response: Future[CallToolResult] | ||
|
|
||
|
|
||
| class WarmMcpClient: | ||
| """One warm `bm mcp` stdio session, callable from any thread. | ||
|
|
||
| The session runs on its own thread with its own subprocess; `call_tool` | ||
| marshals requests through a queue so callers pay startup cost once per | ||
| session instead of once per tool call. Requests are strictly one at a time | ||
| per session — concurrency comes from running multiple sessions. | ||
| """ | ||
|
|
||
| def __init__( | ||
| self, | ||
| *, | ||
| command: str = "bm", | ||
| args: list[str] | None = None, | ||
| env: dict[str, str] | None = None, | ||
| startup_timeout_seconds: float = 30.0, | ||
| request_timeout_seconds: float = 60.0, | ||
| required_tool: str = "search_notes", | ||
| ) -> None: | ||
| self._command = command | ||
| self._args = args or ["mcp"] | ||
| self._env = env | ||
| self._startup_timeout_seconds = startup_timeout_seconds | ||
| self._request_timeout_seconds = request_timeout_seconds | ||
| self._required_tool = required_tool | ||
| self._requests: Queue[_McpToolRequest | None] = Queue() | ||
| self._ready = threading.Event() | ||
| self._startup_error: Exception | None = None | ||
| self._thread: threading.Thread | None = None | ||
|
|
||
| async def _serve(self) -> None: | ||
| params = StdioServerParameters(command=self._command, args=self._args, env=self._env) | ||
| async with stdio_client(params) as (read_stream, write_stream): | ||
| async with ClientSession(read_stream, write_stream) as session: | ||
| await session.initialize() | ||
| tools = await session.list_tools() | ||
| tool_names = {tool.name for tool in tools.tools} | ||
| if self._required_tool not in tool_names: | ||
| raise RuntimeError(f"bm mcp server does not expose '{self._required_tool}'") | ||
|
|
||
| self._ready.set() | ||
|
|
||
| while True: | ||
| loop = asyncio.get_running_loop() | ||
| request = await loop.run_in_executor(None, self._requests.get) | ||
| if request is None: | ||
| break | ||
| try: | ||
| result = await session.call_tool(request.name, request.arguments) | ||
| except Exception as exc: | ||
| request.response.set_exception(exc) | ||
| else: | ||
| request.response.set_result(result) | ||
|
|
||
| def _thread_main(self) -> None: | ||
| try: | ||
| anyio.run(self._serve) | ||
| except Exception as exc: | ||
| self._startup_error = exc | ||
| self._ready.set() | ||
|
|
||
| def start(self) -> None: | ||
| if self._thread is not None and self._thread.is_alive(): | ||
| return | ||
| self._thread = threading.Thread( | ||
| target=self._thread_main, | ||
| name="bm-benchmark-mcp-client", | ||
| daemon=True, | ||
| ) | ||
| self._thread.start() | ||
|
|
||
| if not self._ready.wait(timeout=self._startup_timeout_seconds): | ||
| raise TimeoutError("Timed out starting bm mcp session") | ||
| if self._startup_error is not None: | ||
| raise RuntimeError("Failed to start bm mcp session") from self._startup_error | ||
|
|
||
| def call_tool(self, name: str, arguments: dict[str, Any]) -> CallToolResult: | ||
| if self._thread is None or not self._thread.is_alive(): | ||
| raise RuntimeError("bm mcp session is not running") | ||
|
|
||
| response: Future[CallToolResult] = Future() | ||
| self._requests.put(_McpToolRequest(name=name, arguments=arguments, response=response)) | ||
| return response.result(timeout=self._request_timeout_seconds) | ||
|
|
||
| def stop(self) -> None: | ||
| if self._thread is None: | ||
| return | ||
| if self._thread.is_alive(): | ||
| self._requests.put(None) | ||
| self._thread.join(timeout=self._startup_timeout_seconds) | ||
| self._thread = None | ||
|
|
||
|
|
||
| def resolve_bm_command_prefix(bm_local_path: str | None) -> list[str]: | ||
| """Resolve how to invoke Basic Memory: installed `bm` or a local checkout.""" | ||
| if bm_local_path: | ||
| local_path = Path(bm_local_path) | ||
| if not local_path.exists(): | ||
| raise ValueError(f"--bm-local-path not found: {local_path}") | ||
| return ["uv", "run", "--project", str(local_path), "basic-memory"] | ||
| return ["bm"] | ||
|
|
||
|
|
||
| def status_json_is_ready(payload: dict[str, Any]) -> bool: | ||
| """Interpret `bm status --json` output across BM versions. | ||
|
|
||
| The schema varies by version; every known busy signal is checked, and an | ||
| unknown schema with no busy signal counts as ready. | ||
| """ | ||
| total = payload.get("total") | ||
| if isinstance(total, int): | ||
| return total == 0 | ||
|
|
||
| for list_key in ("new", "modified", "deleted", "skipped_files"): | ||
| value = payload.get(list_key) | ||
| if isinstance(value, list) and len(value) > 0: | ||
| return False | ||
|
|
||
| for dict_key in ("moves", "checksums"): | ||
| value = payload.get(dict_key) | ||
| if isinstance(value, dict) and len(value) > 0: | ||
| return False | ||
|
|
||
| status = payload.get("status") | ||
| if isinstance(status, str): | ||
| lowered = status.lower() | ||
| if "no changes" in lowered or "up to date" in lowered: | ||
| return True | ||
| if "sync" in lowered or "index" in lowered or "pending" in lowered: | ||
| return False | ||
|
|
||
| for key in ("is_syncing", "is_indexing", "sync_in_progress", "index_in_progress"): | ||
| value = payload.get(key) | ||
| if isinstance(value, bool): | ||
| return not value | ||
|
|
||
| for key in ("pending_files", "pending", "unindexed_files", "queued_files", "queue_size"): | ||
| value = payload.get(key) | ||
| if isinstance(value, int) and value != 0: | ||
| return False | ||
|
|
||
| # If the schema is unknown and no busy signal exists, treat status as ready. | ||
| return True | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When an operation exceeds
request_timeout_seconds, its MCP call remains in flight, butstop()waits only the 30-second startup timeout and then discards the thread reference even if the thread is still alive. A sufficiently hung write can therefore complete while_settle_index, reindex, or integrity verification is running, making the resulting artifacts race with an untracked writer; stop must cancel/terminate the subprocess or confirm the thread has exited before returning.AGENTS.md reference: AGENTS.md:L111-L117
Useful? React with 👍 / 👎.