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
41 changes: 41 additions & 0 deletions docs/en/snapshot-analyzer-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
37 changes: 37 additions & 0 deletions docs/zh/snapshot-analyzer-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
46 changes: 45 additions & 1 deletion src/pt_snap_cli/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -44,37 +45,73 @@
*,
context_cache: ContextCache | None = None,
) -> None:
self._config = Config()

Check warning on line 48 in src/pt_snap_cli/api.py

View workflow job for this annotation

GitHub Actions / Lint & Format

Type annotation for attribute `_config` is required because this class is not decorated with `@final` (reportUnannotatedClassAttribute)
self._db_path = db_path

Check warning on line 49 in src/pt_snap_cli/api.py

View workflow job for this annotation

GitHub Actions / Lint & Format

Type annotation for attribute `_db_path` is required because this class is not decorated with `@final` (reportUnannotatedClassAttribute)
self._device_id = device_id

Check warning on line 50 in src/pt_snap_cli/api.py

View workflow job for this annotation

GitHub Actions / Lint & Format

Type annotation for attribute `_device_id` is required because this class is not decorated with `@final` (reportUnannotatedClassAttribute)
self._focus_service = FocusService(self._config)

Check warning on line 51 in src/pt_snap_cli/api.py

View workflow job for this annotation

GitHub Actions / Lint & Format

Type annotation for attribute `_focus_service` is required because this class is not decorated with `@final` (reportUnannotatedClassAttribute)
# Share one context cache across the analyzer so that long-lived
# SnapshotAnalyzer instances reuse a single
# SQLite connection and skip schema validation on every query.
# 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()

Check warning on line 57 in src/pt_snap_cli/api.py

View workflow job for this annotation

GitHub Actions / Lint & Format

Type annotation for attribute `_context_cache` is required because this class is not decorated with `@final` (reportUnannotatedClassAttribute)
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)

Check warning on line 60 in src/pt_snap_cli/api.py

View workflow job for this annotation

GitHub Actions / Lint & Format

Type annotation for attribute `_query_service` is required because this class is not decorated with `@final` (reportUnannotatedClassAttribute)
self._metadata_service = ImportMetadataService()

Check warning on line 61 in src/pt_snap_cli/api.py

View workflow job for this annotation

GitHub Actions / Lint & Format

Type annotation for attribute `_metadata_service` is required because this class is not decorated with `@final` (reportUnannotatedClassAttribute)
self._capability_service = CapabilityService(

Check warning on line 62 in src/pt_snap_cli/api.py

View workflow job for this annotation

GitHub Actions / Lint & Format

Type annotation for attribute `_capability_service` is required because this class is not decorated with `@final` (reportUnannotatedClassAttribute)
query_service=self._query_service,
)
self._overview_service = OverviewService(

Check warning on line 65 in src/pt_snap_cli/api.py

View workflow job for this annotation

GitHub Actions / Lint & Format

Type annotation for attribute `_overview_service` is required because this class is not decorated with `@final` (reportUnannotatedClassAttribute)
self._focus_service,
metadata_service=self._metadata_service,
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,
Expand All @@ -89,6 +126,7 @@
)

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
Expand All @@ -103,7 +141,7 @@

if candidate_db is not None:
try:
self._focus_service.validate_session_db(candidate_db, candidate_device)

Check warning on line 144 in src/pt_snap_cli/api.py

View workflow job for this annotation

GitHub Actions / Lint & Format

Result of call expression is of type "FocusState" and is not used; assign to variable "_" if this is intentional (reportUnusedCallResult)
except DatabaseMissingError as exc:
raise FileNotFoundError(str(exc)) from exc
except DatabaseSchemaError as exc:
Expand All @@ -117,6 +155,7 @@
return self.get_focus()

def list_templates(self, category: str | None = None) -> list[dict[str, Any]]:
self._ensure_open()
return [
{
"name": template.name,
Expand All @@ -127,6 +166,7 @@
]

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:
Expand All @@ -144,6 +184,7 @@
exact_total: bool = False,
timeout_s: float | None = None,
) -> dict[str, Any]:
self._ensure_open()
try:
result = self._query_service.execute_query(
template=template,
Expand All @@ -170,9 +211,11 @@
}

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)
Expand All @@ -187,6 +230,7 @@
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,
Expand Down
6 changes: 6 additions & 0 deletions src/pt_snap_cli/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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))
Expand Down Expand Up @@ -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)))
Expand Down
8 changes: 7 additions & 1 deletion src/pt_snap_cli/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)."""
Expand Down
6 changes: 6 additions & 0 deletions src/pt_snap_cli/core/overview_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
11 changes: 11 additions & 0 deletions src/pt_snap_cli/core/query_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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)
Expand Down
4 changes: 4 additions & 0 deletions src/pt_snap_cli/core/report_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Loading
Loading