Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion src/semble/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,10 @@ def _load_matching_metadata(
persistence_path = PersistencePath.from_path(find_index_from_cache_folder(path, content))
if persistence_path.non_existing():
return None
metadata = json.loads(persistence_path.metadata.read_text(encoding="utf-8"))
try:
metadata = json.loads(persistence_path.metadata.read_text(encoding="utf-8"))
except ValueError: # Truncated by a process killed mid-save; treat as a miss so the index is rebuilt.
return None
if model_path is None:
model_path = resolve_model_name()
if not _metadata_matches(metadata, model_path, content):
Expand Down
7 changes: 6 additions & 1 deletion src/semble/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@
import io
import json
import logging
import os
import re
import signal
import sys
import warnings
from collections.abc import Iterator
Expand Down Expand Up @@ -100,6 +102,7 @@ def main() -> None:


def _mcp_main() -> None:
signal.signal(signal.SIGTERM, lambda *_: os._exit(0))
parser = argparse.ArgumentParser(
prog="semble",
description="Instant local code search for agents.",
Expand All @@ -112,7 +115,9 @@ def _mcp_main() -> None:
from semble.mcp import serve

content = _resolve_content(args.content, args.include_text_files)
asyncio.run(serve(content))
asyncio.new_event_loop().run_until_complete(serve(content))
# Skip asyncio.run's shutdown, which waits for threads still loading the model or building an index.
os._exit(0)
Comment thread
greptile-apps[bot] marked this conversation as resolved.


def _resolve_content(content: list[str], include_text_files: bool) -> list[ContentType]:
Expand Down
2 changes: 1 addition & 1 deletion src/semble/version.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
__version_triple__ = (0, 6, 1)
__version_triple__ = (0, 6, 2)
__version__ = ".".join(map(str, __version_triple__))
5 changes: 1 addition & 4 deletions tests/index/test_create.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,10 +135,7 @@ def test_load_previous_for_incremental_fails_closed(corrupt: str, tmp_path: Path
bm25["doc_order"].reverse()
bm25_path.write_bytes(orjson.dumps(bm25))
elif corrupt == "corrupt_json":
(index_path / "metadata.json").write_bytes(b"{not json")
with patch("semble.cache.find_index_from_cache_folder", return_value=index_path):
assert load_previous_for_incremental("/some/path", "my/model", [ContentType.CODE]) is None
return
(index_path / "chunks.json").write_bytes(b"{not json")
(index_path / "metadata.json").write_bytes(orjson.dumps(metadata))

with patch("semble.cache.find_index_from_cache_folder", return_value=index_path):
Expand Down
8 changes: 7 additions & 1 deletion tests/test_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ def _write_metadata(


def test_get_validated_cache_invalid_index(tmp_path: Path) -> None:
"""Returns None when the index directory is missing or incomplete."""
"""Returns None when the index directory is missing, incomplete, or has truncated metadata."""
with patch("semble.cache.find_index_from_cache_folder", return_value=tmp_path / "missing"):
assert get_validated_cache("/path", None, [ContentType.CODE]) is None

Expand All @@ -157,6 +157,12 @@ def test_get_validated_cache_invalid_index(tmp_path: Path) -> None:
with patch("semble.cache.find_index_from_cache_folder", return_value=index_path):
assert get_validated_cache("/path", None, [ContentType.CODE]) is None

_write_metadata(index_path, "my/model", ["code"], 0.0)
metadata = index_path / "metadata.json"
metadata.write_text(metadata.read_text()[:20])
with patch("semble.cache.find_index_from_cache_folder", return_value=index_path):
assert get_validated_cache("/path", "my/model", [ContentType.CODE]) is None


@pytest.mark.parametrize(
("stored_model", "stored_content", "req_model", "req_content"),
Expand Down
25 changes: 19 additions & 6 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import asyncio
import hashlib
import json
import signal
import sys
import warnings
from importlib.resources import files
from pathlib import Path
from unittest.mock import MagicMock, patch
from unittest.mock import AsyncMock, MagicMock, patch

import pytest

Expand All @@ -20,13 +22,24 @@
["semble"],
],
)
def test_main_calls_asyncio_run(argv: list[str], monkeypatch: pytest.MonkeyPatch) -> None:
"""main() delegates to asyncio.run(serve(...)) when no CLI subcommand is given."""
def test_mcp_main_serves_then_exits(argv: list[str], monkeypatch: pytest.MonkeyPatch) -> None:
"""main() serves MCP, then hard-exits with 0 on stdin EOF or SIGTERM instead of joining worker threads."""
monkeypatch.setattr(sys, "argv", argv)
with patch("asyncio.run") as mock_run:
mock_run.side_effect = lambda coro: coro.close()
loop = asyncio.new_event_loop()
with (
patch("semble.cli.asyncio.new_event_loop", return_value=loop),
patch("semble.mcp.serve", new=AsyncMock()) as mock_serve,
patch("semble.cli.signal.signal") as mock_signal,
patch("semble.cli.os._exit") as mock_exit,
):
main()
mock_run.assert_called_once()
mock_serve.assert_awaited_once()
mock_exit.assert_called_once_with(0)
signum, handler = mock_signal.call_args.args
assert signum == signal.SIGTERM
handler(signum, None)
mock_exit.assert_called_with(0)
loop.close()


@pytest.mark.parametrize(
Expand Down
Loading