From f6d85e6f3fb8e0f788736271cea395118f8b9020 Mon Sep 17 00:00:00 2001 From: codeasier Date: Sat, 3 Oct 2026 00:47:17 +0800 Subject: [PATCH] fix(api): manage analyzer connection lifetime explicitly --- docs/en/snapshot-analyzer-api.md | 41 ++++ docs/zh/snapshot-analyzer-api.md | 37 +++ src/pt_snap_cli/api.py | 46 +++- src/pt_snap_cli/cli.py | 6 + src/pt_snap_cli/context.py | 8 +- src/pt_snap_cli/core/overview_service.py | 6 + src/pt_snap_cli/core/query_service.py | 11 + src/pt_snap_cli/core/report_service.py | 4 + tests/test_analyzer_lifecycle.py | 288 +++++++++++++++++++++++ tests/test_api.py | 14 +- tests/test_query_cache_perf.py | 4 +- tests/test_snapshot_analyzer_cache.py | 29 +-- 12 files changed, 470 insertions(+), 24 deletions(-) create mode 100644 tests/test_analyzer_lifecycle.py diff --git a/docs/en/snapshot-analyzer-api.md b/docs/en/snapshot-analyzer-api.md index 3120632..3efb823 100644 --- a/docs/en/snapshot-analyzer-api.md +++ b/docs/en/snapshot-analyzer-api.md @@ -25,6 +25,47 @@ and `device_id` is its default explicit query-device override. When `db_path` is omitted, the database uses the same resolution order as the CLI: `PT_SNAP_DB_PATH`, the nearest `.pt-snap/focus.json`, then legacy global config. +## Connection Lifetime and Cache Ownership + +An analyzer reuses read-only SQLite connections for queries and overviews. Use +`with` to release them deterministically, including when an operation raises: + +```python +with SnapshotAnalyzer(Path("/path/to/snapshot.db")) as scoped_analyzer: + overview = scoped_analyzer.get_database_overview() + result = scoped_analyzer.execute_query("leak_detection") +``` + +For a long-lived instance such as `analyzer` in the examples below, call +`analyzer.close()` in a `finally` block when finished. `close()` is idempotent; +context-manager exit calls it and does not suppress exceptions. After closing, +focus, discovery, metadata, overview and query methods, and entering another +`with` block, raise `RuntimeError("SnapshotAnalyzer is closed.")`. Create a new +analyzer to resume work. + +By default the analyzer owns its cache and closes all cached connections. +If you pass `context_cache=shared_cache`, the cache is **borrowed**: closing the +analyzer does not invalidate it or close connections used by other analyzers. +The caller must call `shared_cache.close()` after all borrowers have finished: + +```python +from contextlib import closing +from pt_snap_cli.core.context_cache import ContextCache + +with closing(ContextCache()) as shared_cache: + with SnapshotAnalyzer(Path("/path/to/snapshot.db"), context_cache=shared_cache) as first: + first.get_database_overview() + with SnapshotAnalyzer(Path("/path/to/snapshot.db"), context_cache=shared_cache) as second: + second.execute_query("leak_detection") # Reuses the still-open cache. +``` + +The public `context_cache` property and `invalidate_context_cache(db_path=None)` +remain available, even after closing. Explicit invalidation still closes the +selected cached connections, including shared ones. Unlike analyzer `close()`, +invalidation (or `context_cache.close()`) does not end an open analyzer's +lifetime: the next query or overview can populate its cache again. Direct use +of the public cache is managed by its caller independently of analyzer lifetime. + ## Inspect and Change Focus ```python diff --git a/docs/zh/snapshot-analyzer-api.md b/docs/zh/snapshot-analyzer-api.md index 3febe2e..9fa013f 100644 --- a/docs/zh/snapshot-analyzer-api.md +++ b/docs/zh/snapshot-analyzer-api.md @@ -23,6 +23,43 @@ analyzer = SnapshotAnalyzer( 显式设备覆盖。省略 `db_path` 时,数据库解析顺序与 CLI 相同:`PT_SNAP_DB_PATH`、 最近的 `.pt-snap/focus.json`,最后是 legacy 全局配置。 +## 连接生命周期与缓存所有权 + +analyzer 会为查询和概览复用只读 SQLite 连接。使用 `with` 可确定性释放连接, +操作抛出异常时也会清理: + +```python +with SnapshotAnalyzer(Path("/path/to/snapshot.db")) as scoped_analyzer: + overview = scoped_analyzer.get_database_overview() + result = scoped_analyzer.execute_query("leak_detection") +``` + +对于下文示例中 `analyzer` 这样的长生命周期实例,使用完毕后应在 `finally` 中调用 +`analyzer.close()`。`close()` 是幂等的;上下文管理器退出时会调用它,且不会吞掉异常。 +关闭后,focus、发现、metadata、概览和查询方法,以及再次进入 `with`,均抛出 +`RuntimeError("SnapshotAnalyzer is closed.")`。需要继续工作时请新建 analyzer。 + +默认情况下 analyzer 拥有缓存,关闭时会释放缓存内所有连接。如果传入 +`context_cache=shared_cache`,该缓存属于**借用**:关闭 analyzer 不会使缓存失效, +也不会关闭其他 analyzer 仍依赖的连接。调用方须在所有借用者使用完毕后调用 +`shared_cache.close()`: + +```python +from contextlib import closing +from pt_snap_cli.core.context_cache import ContextCache + +with closing(ContextCache()) as shared_cache: + with SnapshotAnalyzer(Path("/path/to/snapshot.db"), context_cache=shared_cache) as first: + first.get_database_overview() + with SnapshotAnalyzer(Path("/path/to/snapshot.db"), context_cache=shared_cache) as second: + second.execute_query("leak_detection") # 复用仍然打开的缓存。 +``` + +公开的 `context_cache` 属性与 `invalidate_context_cache(db_path=None)` 保持可用, +关闭后也可访问。显式失效操作仍会关闭指定的缓存连接,包括共享连接。与 analyzer 的 +`close()` 不同,缓存失效(或 `context_cache.close()`)不会终止尚未关闭的 analyzer: +下一次查询或概览可以重新填充缓存。直接使用公开 cache 时,其生命周期由调用方独立管理。 + ## 查看和修改 Focus ```python diff --git a/src/pt_snap_cli/api.py b/src/pt_snap_cli/api.py index e8e5b7d..6d6d6de 100644 --- a/src/pt_snap_cli/api.py +++ b/src/pt_snap_cli/api.py @@ -4,6 +4,7 @@ from dataclasses import dataclass from pathlib import Path +from types import TracebackType from typing import Any from pt_snap_cli.config import Config @@ -54,6 +55,8 @@ def __init__( # Explicit ``is not None`` because an empty cache is falsy via # ``__len__`` and would be silently replaced otherwise. self._context_cache = context_cache if context_cache is not None else ContextCache() + self._owns_context_cache: bool = context_cache is None + self._closed: bool = False self._query_service = QueryService(self._focus_service, context_cache=self._context_cache) self._metadata_service = ImportMetadataService() self._capability_service = CapabilityService( @@ -65,16 +68,50 @@ def __init__( context_cache=self._context_cache, ) + def close(self) -> None: + """End this analyzer's lifetime, closing only its internally owned cache. + + Safe to call repeatedly. An injected cache remains the caller's + responsibility and can still be used by other analyzers. + """ + if self._closed: + return + self._closed = True + self._query_service.close() + if self._owns_context_cache: + self._context_cache.close() + + def __enter__(self) -> SnapshotAnalyzer: + self._ensure_open() + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: + self.close() + + def _ensure_open(self) -> None: + if self._closed: + raise RuntimeError("SnapshotAnalyzer is closed.") + @property def context_cache(self) -> ContextCache: """Return the :class:`ContextCache` this analyzer uses.""" return self._context_cache def invalidate_context_cache(self, db_path: Path | str | None = None) -> None: - """Drop a cached context (or every cached context when ``db_path`` is None).""" + """Drop cached contexts, including from an explicitly shared cache. + + This cleanup operation remains available after close(). While open, + the analyzer can create fresh contexts on its next query or overview. + """ self._context_cache.invalidate(db_path) def get_focus(self) -> FocusState: + self._ensure_open() state = self._focus_service.get_focus( explicit_db_path=self._db_path, explicit_device_id=self._device_id, @@ -89,6 +126,7 @@ def get_focus(self) -> FocusState: ) def set_focus(self, db_path: str | None = None, device_id: int | None = None) -> FocusState: + self._ensure_open() if db_path is None and device_id is None: return self.get_focus() candidate_db = Path(db_path) if db_path is not None else self._db_path @@ -117,6 +155,7 @@ def set_focus(self, db_path: str | None = None, device_id: int | None = None) -> return self.get_focus() def list_templates(self, category: str | None = None) -> list[dict[str, Any]]: + self._ensure_open() return [ { "name": template.name, @@ -127,6 +166,7 @@ def list_templates(self, category: str | None = None) -> list[dict[str, Any]]: ] def get_template_info(self, name: str) -> dict[str, Any] | None: + self._ensure_open() try: info = self._query_service.get_template_info(name) except TemplateNotFoundError: @@ -144,6 +184,7 @@ def execute_query( exact_total: bool = False, timeout_s: float | None = None, ) -> dict[str, Any]: + self._ensure_open() try: result = self._query_service.execute_query( template=template, @@ -170,9 +211,11 @@ def execute_query( } def list_capabilities(self) -> dict[str, Any]: + self._ensure_open() return self._capability_service.catalog_to_dict(self._capability_service.catalog()) def get_database_overview(self, db_path: str | None = None) -> dict[str, Any]: + self._ensure_open() resolved_path = db_path if db_path is not None else self._db_path try: overview = self._overview_service.inspect(resolved_path) @@ -187,6 +230,7 @@ def get_database_overview(self, db_path: str | None = None) -> dict[str, Any]: return self._overview_service.overview_to_dict(overview) def get_database_metadata(self, db_path: str | None = None) -> dict[str, Any]: + self._ensure_open() resolved = self._focus_service.resolve_focus( explicit_db_path=db_path if db_path is not None else self._db_path, explicit_device_id=self._device_id, diff --git a/src/pt_snap_cli/cli.py b/src/pt_snap_cli/cli.py index b4a1096..5be27c7 100644 --- a/src/pt_snap_cli/cli.py +++ b/src/pt_snap_cli/cli.py @@ -845,6 +845,8 @@ def query_database( json.JSONDecodeError, ) as e: _error_from_exc(e, text_prefix="Error executing query: ") + finally: + query_service.close() @report_app.command("peak-memory") @@ -922,6 +924,8 @@ def report_peak_memory( DatabaseSchemaError, ) as e: _error_from_exc(e, text_prefix="Error generating report: ") + finally: + report_service.close() if json_output: typer.echo(json.dumps(asdict(report), indent=2)) @@ -1362,6 +1366,8 @@ def show_database_overview( DatabaseSchemaError, ) as e: _error_from_exc(e) + finally: + service.close() if json_output: _emit_json(json_success(**service.overview_to_dict(overview))) diff --git a/src/pt_snap_cli/context.py b/src/pt_snap_cli/context.py index 6fe8bb0..c64b772 100644 --- a/src/pt_snap_cli/context.py +++ b/src/pt_snap_cli/context.py @@ -70,7 +70,13 @@ def __init__( if not self.db_path.exists(): raise DatabaseNotFoundError(f"Database not found: {self.db_path}") - self._validate_schema() + try: + self._validate_schema() + except BaseException: + # A failed constructor never reaches its owner's cache. Release + # even a persistent connection before propagating the failure. + self.close() + raise def _validate_schema(self) -> None: """Validate database has required schema (dictionary table).""" diff --git a/src/pt_snap_cli/core/overview_service.py b/src/pt_snap_cli/core/overview_service.py index d24dde7..ea974ef 100644 --- a/src/pt_snap_cli/core/overview_service.py +++ b/src/pt_snap_cli/core/overview_service.py @@ -29,6 +29,12 @@ def __init__( self._focus_service = focus_service or FocusService() self._metadata_service = metadata_service or ImportMetadataService() self._context_cache = context_cache if context_cache is not None else ContextCache() + self._owns_context_cache: bool = context_cache is None + + def close(self) -> None: + """Release owned connections; borrowed caches and later reuse are unaffected.""" + if self._owns_context_cache: + self._context_cache.close() def inspect( self, diff --git a/src/pt_snap_cli/core/query_service.py b/src/pt_snap_cli/core/query_service.py index e4fbdfc..a2b9d6e 100644 --- a/src/pt_snap_cli/core/query_service.py +++ b/src/pt_snap_cli/core/query_service.py @@ -74,6 +74,7 @@ def __init__( # SQLite connect/close handshake. See ContextCache for the LRU and # mtime invalidation semantics. self._context_cache = context_cache if context_cache is not None else ContextCache() + self._owns_context_cache: bool = context_cache is None self._executor: QueryExecutor | None = None self._executor_context: Context | None = None @@ -82,6 +83,16 @@ def context_cache(self) -> ContextCache: """Return the :class:`ContextCache` backing this service.""" return self._context_cache + def close(self) -> None: + """Release owned connections and executor references; allow later reuse. + + An injected cache is borrowed and must be closed by its owner. + """ + self._executor = None + self._executor_context = None + if self._owns_context_cache: + self._context_cache.close() + def invalidate_context_cache(self, db_path: Path | str | None = None) -> None: """Drop a cached context (or all of them when ``db_path`` is None).""" self._context_cache.invalidate(db_path) diff --git a/src/pt_snap_cli/core/report_service.py b/src/pt_snap_cli/core/report_service.py index f7dd460..4b38973 100644 --- a/src/pt_snap_cli/core/report_service.py +++ b/src/pt_snap_cli/core/report_service.py @@ -21,6 +21,10 @@ def __init__(self, focus_service: FocusService | None = None) -> None: self._focus_service = focus_service or FocusService() self._query_service = QueryService(self._focus_service) + def close(self) -> None: + """Release connections owned by this report service; allow later reuse.""" + self._query_service.close() + def peak_memory_report( self, db_path: Path | str | None = None, diff --git a/tests/test_analyzer_lifecycle.py b/tests/test_analyzer_lifecycle.py new file mode 100644 index 0000000..1d41ff8 --- /dev/null +++ b/tests/test_analyzer_lifecycle.py @@ -0,0 +1,288 @@ +"""Real SQLite connection lifetime contracts for API and short-lived CLI owners.""" + +import gc +import sqlite3 +import warnings +from contextlib import closing +from pathlib import Path + +import pytest +from typer.testing import CliRunner + +from pt_snap_cli.api import SnapshotAnalyzer +from pt_snap_cli.cli import app +from pt_snap_cli.core import DatabaseSchemaError, QueryExecutionError, TemplateNotFoundError +from pt_snap_cli.core.context_cache import ContextCache +from pt_snap_cli.core.overview_service import OverviewService +from pt_snap_cli.core.query_service import QueryService + + +@pytest.fixture(autouse=True) +def isolated_focus(monkeypatch, tmp_path): + monkeypatch.chdir(tmp_path) + monkeypatch.delenv("PT_SNAP_DB_PATH", raising=False) + monkeypatch.delenv("PT_SNAP_QUERY_TIMEOUT", raising=False) + monkeypatch.setattr(Path, "home", lambda: tmp_path) + + +@pytest.fixture +def db(tmp_path): + path = tmp_path / "snapshot.db" + with closing(sqlite3.connect(path)) as conn: + conn.executescript( + "CREATE TABLE dictionary (id INTEGER);" + "CREATE TABLE trace_entry_0 (id INTEGER, active INTEGER, allocated INTEGER, " + "reserved INTEGER, callstack TEXT);" + "INSERT INTO trace_entry_0 VALUES (1, 0, 0, 0, '');" + "CREATE TABLE block_0 (id INTEGER, address INTEGER, size INTEGER, " + "requestedSize INTEGER, state INTEGER, allocEventId INTEGER, freeEventId INTEGER);" + ) + return path + + +def assert_closed(conn): + with pytest.raises(sqlite3.ProgrammingError, match="closed database"): + conn.execute("SELECT 1") + + +@pytest.fixture +def connections(monkeypatch): + """Observe actual handles, including ones never published to a cache.""" + opened = [] + original_connect = sqlite3.connect + + def connect(*args, **kwargs): + conn = original_connect(*args, **kwargs) + opened.append(conn) + return conn + + monkeypatch.setattr(sqlite3, "connect", connect) + yield opened + try: + for conn in opened: + assert_closed(conn) + finally: + for conn in opened: + conn.close() + + +@pytest.mark.parametrize("operation", ["query", "overview"]) +def test_close_releases_real_cached_connection(db, connections, operation): + analyzer = SnapshotAnalyzer(db) + try: + if operation == "query": + analyzer.execute_query("memory_peak") + else: + analyzer.get_database_overview() + ctx = analyzer.context_cache.get(db) + with ctx.connect() as conn: + assert conn.execute("SELECT 1").fetchone()[0] == 1 + analyzer.close() + assert len(analyzer.context_cache) == 0 + assert_closed(conn) + analyzer.close() + finally: + analyzer.close() + + +def test_with_reuses_query_overview_connection_then_closes_all_databases(db, connections, tmp_path): + second_db = tmp_path / "second.db" + second_db.write_bytes(db.read_bytes()) + analyzer = SnapshotAnalyzer(db) + with analyzer as entered: + assert entered is analyzer + analyzer.execute_query("memory_peak") + first_ctx = analyzer.context_cache.get(db) + analyzer.get_database_overview() + assert analyzer.context_cache.get(db) is first_ctx + analyzer.get_database_overview(str(second_db)) + assert len(analyzer.context_cache) == 2 + assert len(analyzer.context_cache) == 0 + assert connections + + +@pytest.mark.parametrize("failure", ["body", "template", "sql", "schema", "overview"]) +def test_exception_exit_closes_connections_without_suppressing_error(db, connections, failure): + expected = { + "body": RuntimeError, + "template": TemplateNotFoundError, + "sql": QueryExecutionError, + "schema": ValueError, + "overview": ValueError, + }[failure] + if failure in ("sql", "schema", "overview"): + with closing(sqlite3.connect(db)) as conn: + if failure == "sql": + conn.execute("DROP TABLE block_0") + elif failure == "schema": + conn.execute("DROP TABLE dictionary") + else: + conn.execute("ALTER TABLE trace_entry_0 RENAME COLUMN id TO bad_id") + analyzer = SnapshotAnalyzer(db) + with pytest.raises(expected): + with analyzer: + if failure == "body": + analyzer.get_database_overview() + raise RuntimeError("body failed") + if failure == "template": + analyzer.execute_query("not_a_template") + elif failure == "sql": + analyzer.execute_query("leak_detection") + else: + analyzer.get_database_overview() + assert len(analyzer.context_cache) == 0 + assert connections + + +@pytest.mark.parametrize( + "method,args", + [ + ("get_focus", ()), + ("set_focus", ("missing.db",)), + ("list_templates", ()), + ("get_template_info", ("memory_peak",)), + ("execute_query", ("memory_peak",)), + ("list_capabilities", ()), + ("get_database_overview", ()), + ("get_database_metadata", ()), + ("__enter__", ()), + ], +) +def test_closed_analyzer_rejects_operations_without_opening_connections( + db, connections, method, args +): + analyzer = SnapshotAnalyzer(db) + analyzer.close() + analyzer.close() + with pytest.raises(RuntimeError, match="^SnapshotAnalyzer is closed\\.$"): + getattr(analyzer, method)(*args) + analyzer.invalidate_context_cache() + assert len(analyzer.context_cache) == 0 + assert connections == [] + + +@pytest.mark.parametrize("exception_exit", [False, True]) +def test_borrower_close_preserves_other_analyzers_connection(db, connections, exception_exit): + with closing(ContextCache()) as shared: + with SnapshotAnalyzer(db, context_cache=shared) as second: + first = SnapshotAnalyzer(db, context_cache=shared) + assert first.context_cache is shared # Even an initially empty cache is borrowed. + try: + with first: + first.execute_query("memory_peak") + second.execute_query("memory_peak") + ctx = shared.get(db) + with ctx.connect() as conn: + assert conn.execute("SELECT 1").fetchone()[0] == 1 + if exception_exit: + raise LookupError("caller failed") + except LookupError: + assert exception_exit + first.close() + second.get_database_overview() + second.execute_query("memory_peak") + assert shared.get(db) is ctx + assert conn.execute("SELECT 1").fetchone()[0] == 1 + assert len(shared) == 1 + assert_closed(conn) + + +@pytest.mark.parametrize("cleanup", ["invalidate_one", "invalidate_all", "public_close"]) +def test_existing_cache_cleanup_allows_open_analyzer_to_resume(db, connections, cleanup): + with SnapshotAnalyzer(db) as analyzer: + analyzer.execute_query("memory_peak") + old_ctx = analyzer.context_cache.get(db) + with old_ctx.connect() as old_conn: + pass + if cleanup == "public_close": + analyzer.context_cache.close() + else: + analyzer.invalidate_context_cache(db if cleanup == "invalidate_one" else None) + assert_closed(old_conn) + analyzer.execute_query("memory_peak") + analyzer.get_database_overview() + assert analyzer.context_cache.get(db) is not old_ctx + + +def test_explicit_invalidation_of_borrowed_cache_remains_available_after_close(db, connections): + with closing(ContextCache()) as shared: + with SnapshotAnalyzer(db, context_cache=shared) as first: + first.get_database_overview() + with SnapshotAnalyzer(db, context_cache=shared) as second: + ctx = shared.get(db) + with ctx.connect() as conn: + pass + first.invalidate_context_cache(db) + assert_closed(conn) + second.execute_query("memory_peak") + assert shared.get(db) is not ctx + + +@pytest.mark.parametrize("service_type", [QueryService, OverviewService]) +@pytest.mark.parametrize("borrowed", [False, True]) +def test_service_cleanup_respects_ownership_and_allows_reuse( + db, connections, service_type, borrowed +): + def run(service): + if isinstance(service, QueryService): + service.execute_query("memory_peak", db_path=db) + else: + service.inspect(db) + + with closing(ContextCache()) as shared: + with closing(service_type(context_cache=shared if borrowed else None)) as service: + run(service) + service.close() + service.close() + if borrowed: + assert len(shared) == 1 + with shared.get(db).connect() as conn: + assert conn.execute("SELECT 1").fetchone()[0] == 1 + else: + for conn in connections: + assert_closed(conn) + run(service) + + +@pytest.mark.parametrize("operation", ["query", "overview", "report"]) +@pytest.mark.parametrize("failure", [False, True]) +def test_cli_closes_short_lived_service_connections(db, connections, operation, failure): + if failure: + with closing(sqlite3.connect(db)) as conn: + conn.execute("ALTER TABLE trace_entry_0 RENAME COLUMN id TO bad_id") + commands = { + "query": ["query", str(db), "--template-use", "memory_peak", "--json"], + "overview": ["overview", str(db), "--json"], + "report": ["report", "peak-memory", str(db), "--json"], + } + result = CliRunner().invoke(app, commands[operation]) + assert result.exit_code == (1 if failure else 0), result.output + assert connections + + +def test_query_schema_failure_closes_connection_before_cache_publication(db, connections): + with closing(sqlite3.connect(db)) as conn: + conn.execute("DROP TABLE dictionary") + with SnapshotAnalyzer(db) as analyzer: + with pytest.raises(DatabaseSchemaError, match="dictionary"): + analyzer.execute_query("memory_peak") + assert len(analyzer.context_cache) == 0 + for conn in connections: + assert_closed(conn) + + +@pytest.mark.parametrize("operation", ["query", "overview"]) +def test_explicit_cleanup_is_resource_warning_free_on_collection(db, operation): + # Python 3.13 reports unclosed SQLite connections during collection. Keep + # this independent of the handle-tracking fixture so collection really runs. + gc.collect() + with warnings.catch_warnings(record=True) as recorded: + warnings.simplefilter("always", ResourceWarning) + with SnapshotAnalyzer(db) as analyzer: + if operation == "query": + analyzer.execute_query("memory_peak") + else: + analyzer.get_database_overview() + del analyzer + gc.collect() + assert not [item for item in recorded if issubclass(item.category, ResourceWarning)] diff --git a/tests/test_api.py b/tests/test_api.py index a049884..d792cb4 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -3,6 +3,7 @@ import json import sqlite3 import tempfile +from contextlib import closing from pathlib import Path from unittest.mock import patch @@ -166,7 +167,7 @@ def test_set_focus_new_database_clears_unspecified_device( self, valid_db: Path, tmp_path: Path ) -> None: second_db = tmp_path / "device-one.db" - with sqlite3.connect(second_db) as conn: + with closing(sqlite3.connect(second_db)) as conn: conn.execute( "CREATE TABLE dictionary (`table` TEXT, `column` TEXT, `key` TEXT, `value` TEXT)" ) @@ -253,8 +254,8 @@ def test_execute_query_requires_focus(self) -> None: analyzer.execute_query("leak_detection") def test_execute_query_with_focus(self, valid_db: Path) -> None: - analyzer = SnapshotAnalyzer(db_path=valid_db) - result = analyzer.execute_query("leak_detection", max_rows=10) + with SnapshotAnalyzer(db_path=valid_db) as analyzer: + result = analyzer.execute_query("leak_detection", max_rows=10) assert "total" in result assert "returned" in result assert "device_id" in result @@ -268,8 +269,8 @@ def test_execute_query_with_focus(self, valid_db: Path) -> None: def test_execute_query_max_rows_zero(self, valid_db: Path) -> None: """max_rows=0 returns all rows.""" - analyzer = SnapshotAnalyzer(db_path=valid_db) - result = analyzer.execute_query("leak_detection", max_rows=0) + with SnapshotAnalyzer(db_path=valid_db) as analyzer: + result = analyzer.execute_query("leak_detection", max_rows=0) # leak_detection on empty table returns 0 rows assert result["total"] == 0 assert result["returned"] == 0 @@ -314,7 +315,8 @@ def test_list_capabilities(self) -> None: assert "pt-snap-helper" in skill_names def test_get_database_overview(self, valid_db: Path) -> None: - payload = SnapshotAnalyzer(db_path=valid_db).get_database_overview() + with SnapshotAnalyzer(db_path=valid_db) as analyzer: + payload = analyzer.get_database_overview() assert payload["db_path"] == str(valid_db.resolve()) assert payload["devices"] == [ {"device_id": 0, "first_event_id": None, "last_event_id": None} diff --git a/tests/test_query_cache_perf.py b/tests/test_query_cache_perf.py index b91ffa8..7f83b17 100644 --- a/tests/test_query_cache_perf.py +++ b/tests/test_query_cache_perf.py @@ -54,9 +54,8 @@ def test_repeated_execute_query_uses_cached_connection() -> None: the cumulative time is dominated by the query cost and not by connection setup.""" db_path = _make_db() + analyzer = SnapshotAnalyzer(db_path=db_path) try: - analyzer = SnapshotAnalyzer(db_path=db_path) - # Warm up the cache (first call pays the schema-validation cost). analyzer.execute_query("leak_detection") @@ -75,4 +74,5 @@ def test_repeated_execute_query_uses_cached_connection() -> None: # into the multi-second range even on fast disks). assert elapsed < 2.0, f"10 cached queries took {elapsed:.3f}s" finally: + analyzer.close() db_path.unlink(missing_ok=True) diff --git a/tests/test_snapshot_analyzer_cache.py b/tests/test_snapshot_analyzer_cache.py index 2756362..a584757 100644 --- a/tests/test_snapshot_analyzer_cache.py +++ b/tests/test_snapshot_analyzer_cache.py @@ -15,6 +15,7 @@ import sqlite3 import tempfile import time +from contextlib import closing from pathlib import Path import pytest @@ -55,13 +56,17 @@ def valid_db() -> Path: db_path.unlink(missing_ok=True) +@pytest.fixture +def analyzer(valid_db): + with SnapshotAnalyzer(db_path=valid_db) as instance: + yield instance + + class TestSnapshotAnalyzerContextCache: - def test_repeated_queries_reuse_cached_context(self, valid_db: Path) -> None: + def test_repeated_queries_reuse_cached_context(self, valid_db: Path, analyzer) -> None: """Two consecutive ``execute_query`` calls must share one cached Context so that the second call avoids the schema validation and sqlite3.connect handshake.""" - analyzer = SnapshotAnalyzer(db_path=valid_db) - first_ctx = analyzer.context_cache.get(valid_db) analyzer.execute_query("leak_detection") second_ctx = analyzer.context_cache.get(valid_db) @@ -69,9 +74,7 @@ def test_repeated_queries_reuse_cached_context(self, valid_db: Path) -> None: assert first_ctx is second_ctx assert len(analyzer.context_cache) == 1 - def test_invalidate_context_cache_forces_refresh(self, valid_db: Path) -> None: - analyzer = SnapshotAnalyzer(db_path=valid_db) - + def test_invalidate_context_cache_forces_refresh(self, valid_db: Path, analyzer) -> None: first_ctx = analyzer.context_cache.get(valid_db) analyzer.invalidate_context_cache(valid_db) assert len(analyzer.context_cache) == 0 @@ -79,8 +82,7 @@ def test_invalidate_context_cache_forces_refresh(self, valid_db: Path) -> None: second_ctx = analyzer.context_cache.get(valid_db) assert second_ctx is not first_ctx - def test_db_file_replacement_invalidates_cache(self, valid_db: Path) -> None: - analyzer = SnapshotAnalyzer(db_path=valid_db) + def test_db_file_replacement_invalidates_cache(self, valid_db: Path, analyzer) -> None: first_ctx = analyzer.context_cache.get(valid_db) # Recreate the file with new content. ``os.replace`` updates @@ -101,9 +103,8 @@ def test_db_file_replacement_invalidates_cache(self, valid_db: Path) -> None: assert second_ctx.device_ids == [1] def test_analyzer_can_use_externally_supplied_cache(self, valid_db: Path) -> None: - shared = ContextCache(maxsize=2) - analyzer = SnapshotAnalyzer(db_path=valid_db, context_cache=shared) - - assert analyzer.context_cache is shared - analyzer.execute_query("leak_detection") - assert len(shared) == 1 + with closing(ContextCache(maxsize=2)) as shared: + with SnapshotAnalyzer(db_path=valid_db, context_cache=shared) as analyzer: + assert analyzer.context_cache is shared + analyzer.execute_query("leak_detection") + assert len(shared) == 1