From df277cafbfc8434650b89cd9be656cad4f6ca31d Mon Sep 17 00:00:00 2001 From: codeasier Date: Tue, 21 Apr 2026 21:33:48 +0800 Subject: [PATCH] feat: add shared core services for CLI and MCP Centralize focus and query behavior in reusable services so the CLI, Python API, and MCP server share the same semantics and compatibility guarantees. --- src/pt_snap_cli/api.py | 139 ++++--- src/pt_snap_cli/cli.py | 505 +++++++++++--------------- src/pt_snap_cli/core/__init__.py | 43 +++ src/pt_snap_cli/core/errors.py | 38 ++ src/pt_snap_cli/core/focus_service.py | 168 +++++++++ src/pt_snap_cli/core/models.py | 61 ++++ src/pt_snap_cli/core/query_service.py | 170 +++++++++ src/pt_snap_cli/mcp/server.py | 27 -- tests/core/test_focus_service.py | 104 ++++++ tests/core/test_query_service.py | 123 +++++++ tests/test_cli.py | 38 ++ 11 files changed, 1023 insertions(+), 393 deletions(-) create mode 100644 src/pt_snap_cli/core/__init__.py create mode 100644 src/pt_snap_cli/core/errors.py create mode 100644 src/pt_snap_cli/core/focus_service.py create mode 100644 src/pt_snap_cli/core/models.py create mode 100644 src/pt_snap_cli/core/query_service.py create mode 100644 tests/core/test_focus_service.py create mode 100644 tests/core/test_query_service.py diff --git a/src/pt_snap_cli/api.py b/src/pt_snap_cli/api.py index 63235f5..88280d3 100644 --- a/src/pt_snap_cli/api.py +++ b/src/pt_snap_cli/api.py @@ -1,8 +1,4 @@ -"""High-level API for PyTorch memory snapshot analysis. - -This module provides a programmatic interface that both the CLI -and the MCP server can use. It has no MCP dependency. -""" +"""High-level API for PyTorch memory snapshot analysis.""" from __future__ import annotations @@ -11,14 +7,12 @@ from typing import Any from pt_snap_cli.config import Config -from pt_snap_cli.context import Context -from pt_snap_cli.query.executor import QueryExecutor -from pt_snap_cli.query.registry import ( - get_template_info as _get_template_info, -) -from pt_snap_cli.query.registry import ( - list_by_category_with_details, - list_queries_with_details, +from pt_snap_cli.core import ( + DatabaseMissingError, + DatabaseSchemaError, + FocusNotConfiguredError, + FocusService, + QueryService, ) @@ -43,60 +37,66 @@ def __init__( self._config = Config() self._db_path = db_path self._device_id = device_id - self._context: Context | None = None - self._executor: QueryExecutor | None = None - - def _ensure_context(self) -> tuple[Context, QueryExecutor]: - """Resolve focus and create context/executor if needed.""" - if self._context is not None and self._executor is not None: - return self._context, self._executor - - resolved = self._config.resolve_focus(self._db_path, explicit_device_id=self._device_id) - if resolved.db_path is None: - raise RuntimeError("No database configured. Call set_focus() first.") - self._context = Context(resolved.db_path) - self._executor = QueryExecutor(self._context) - return self._context, self._executor + self._focus_service = FocusService(self._config) + self._query_service = QueryService(self._focus_service) def get_focus(self) -> FocusState: - """Get current focus state.""" - resolved = self._config.resolve_focus(self._db_path, explicit_device_id=self._device_id) - devices: list[int] = [] - if resolved.db_path and resolved.db_path.exists(): - try: - ctx = Context(resolved.db_path) - devices = ctx.device_ids - except Exception: - pass + state = self._focus_service.get_focus( + explicit_db_path=self._db_path, + explicit_device_id=self._device_id, + ) return FocusState( - db_path=str(resolved.db_path) if resolved.db_path else None, - device_id=resolved.device_id, - source=resolved.source, - available_devices=devices, + db_path=str(state.db_path) if state.db_path is not None else None, + device_id=state.device_id, + source=state.source, + available_devices=state.available_devices, ) def set_focus(self, db_path: str | None = None, device_id: int | None = None) -> FocusState: - """Set focus to a new database/device.""" - if db_path: + if db_path is not None: + try: + self._focus_service.validate_session_db(db_path) + except DatabaseMissingError as exc: + raise FileNotFoundError(str(exc)) from exc + except DatabaseSchemaError as exc: + raise ValueError(str(exc)) from exc self._db_path = Path(db_path) - # Validate immediately - Context(self._db_path) if device_id is not None: self._device_id = device_id - # Reset cached context so next _ensure_context re-resolves - self._context = None - self._executor = None return self.get_focus() - def list_templates(self, category: str | None = None) -> list[dict]: - """List available query templates.""" - if category: - return list_by_category_with_details(category) - return list_queries_with_details() + def list_templates(self, category: str | None = None) -> list[dict[str, Any]]: + return [ + { + "name": template.name, + "description": template.description, + "category": template.category, + } + for template in self._query_service.list_templates(category) + ] + + def get_template_info(self, name: str) -> dict[str, Any] | None: + try: + info = self._query_service.get_template_info(name) + except Exception: + return None - def get_template_info(self, name: str) -> dict | None: - """Get detailed template information.""" - return _get_template_info(name) + return { + "name": info.name, + "description": info.description, + "category": info.category, + "devices": info.devices, + "parameters": { + param_name: { + "type": param.type, + "default": param.default, + "required": param.required, + "description": param.description, + } + for param_name, param in info.parameters.items() + }, + "output_schema": info.output_schema, + } def execute_query( self, @@ -105,20 +105,19 @@ def execute_query( device_id: int | None = None, max_rows: int | None = None, ) -> dict[str, Any]: - """Execute a query template. Returns {total, returned, device_id, rows}.""" - ctx, executor = self._ensure_context() - target_device = device_id or self._device_id - if target_device is None and ctx.device_ids: - target_device = ctx.device_ids[0] - - rows = executor.execute_template(template, params or {}, device_id=target_device) - total = len(rows) - if max_rows is not None and max_rows > 0: - rows = rows[:max_rows] - + try: + result = self._query_service.execute_query( + template=template, + params=params, + db_path=self._db_path, + device_id=device_id if device_id is not None else self._device_id, + max_rows=max_rows, + ) + except FocusNotConfiguredError as exc: + raise RuntimeError("No database configured. Call set_focus() first.") from exc return { - "total": total, - "returned": len(rows), - "device_id": target_device, - "rows": rows, + "total": result.total, + "returned": result.returned, + "device_id": result.device_id, + "rows": result.rows, } diff --git a/src/pt_snap_cli/cli.py b/src/pt_snap_cli/cli.py index 040f643..908501b 100644 --- a/src/pt_snap_cli/cli.py +++ b/src/pt_snap_cli/cli.py @@ -1,5 +1,9 @@ """CLI entry point for pt-snap-cli.""" +from __future__ import annotations + +import json +import shlex from pathlib import Path from typing import Annotated @@ -7,8 +11,21 @@ from pt_snap_cli import __version__ from pt_snap_cli.completion import complete_categories, complete_device_ids, complete_template_names -from pt_snap_cli.config import ENV_DB_PATH, Config, FocusResolutionError -from pt_snap_cli.context import Context, DatabaseNotFoundError, SchemaVersionError +from pt_snap_cli.config import ENV_DB_PATH +from pt_snap_cli.core import ( + DatabaseMissingError, + DatabaseSchemaError, + FocusFileInvalidError, + FocusNotConfiguredError, + FocusService, + InvalidCategoryError, + InvalidDeviceError, + QueryExecutionError, + QueryService, + TemplateNotFoundError, + TemplateRenderError, +) +from pt_snap_cli.query.registry import discover_categories app = typer.Typer( name="pt-snap", @@ -18,8 +35,15 @@ ) +def _focus_service() -> FocusService: + return FocusService() + + +def _query_service() -> QueryService: + return QueryService(_focus_service()) + + def version_callback(value: bool) -> None: - """Callback for --version flag.""" if value: typer.echo(f"pt-snap-cli version {__version__}") raise typer.Exit() @@ -51,32 +75,22 @@ def focus_database( bool, typer.Option("--global", help="Store the focus in legacy global config") ] = False, ) -> None: - """Set the current analysis focus (database and optional device). - - Validates the database and saves the focus to project by default. - After setting, you can use 'pt-snap query' without specifying db_path or device. - - Use --device to also persist a device ID for queries. - Use --session for an isolated shell/agent override. - Use --global for legacy user-wide configuration. - If called without arguments, shows the current focus. - """ - config = Config() + """Set the current analysis focus (database and optional device).""" + focus_service = _focus_service() if db_path is None and device is None: try: - resolved = config.resolve_focus() - except FocusResolutionError as e: - typer.secho(f"Error: {e}", fg=typer.colors.RED) - raise typer.Exit(1) from None - - if resolved.db_path: - typer.echo(f"Current database ({resolved.source}): {resolved.db_path}") - if resolved.focus_file: - typer.echo(f"Focus file: {resolved.focus_file}") - if resolved.device_id is not None: - typer.echo(f"Focused device: {resolved.device_id}") - if not resolved.db_path.exists(): + state = focus_service.get_focus() + except FocusFileInvalidError as e: + _error(str(e)) + + if state.db_path: + typer.echo(f"Current database ({state.source}): {state.db_path}") + if state.focus_file: + typer.echo(f"Focus file: {state.focus_file}") + if state.device_id is not None: + typer.echo(f"Focused device: {state.device_id}") + if not state.db_path.exists(): typer.secho("Warning: Database file does not exist!", fg=typer.colors.YELLOW) else: typer.echo("No current focus set.") @@ -84,90 +98,50 @@ def focus_database( raise typer.Exit() if session and global_focus: - typer.secho("Error: --session and --global cannot be used together.", fg=typer.colors.RED) - raise typer.Exit(1) + _error("--session and --global cannot be used together.") - # Handle device-only update (keep current db, change device) if db_path is None and device is not None: try: - resolved = config.resolve_focus() - except FocusResolutionError as e: - typer.secho(f"Error: {e}", fg=typer.colors.RED) - raise typer.Exit(1) from None - - if resolved.db_path is None: - typer.secho( - "Error: No database set. Use 'pt-snap focus ' first.", - fg=typer.colors.RED, - ) - raise typer.Exit(1) - if not resolved.db_path.exists(): - typer.secho(f"Error: Database not found: {resolved.db_path}", fg=typer.colors.RED) - raise typer.Exit(1) - - ctx = Context(resolved.db_path) - if device not in ctx.device_ids: - typer.secho( - f"Error: Device {device} not found. Available: {ctx.device_ids}", - fg=typer.colors.RED, - ) - raise typer.Exit(1) - - if global_focus or resolved.source == "global": - config.current_device_id = device - typer.secho(f"Focused device (global): {device}", fg=typer.colors.GREEN) - else: - focus_file = config.project_focus_path() - config.write_project_focus(resolved.db_path, device_id=device) - typer.secho(f"Focused device (project): {device}", fg=typer.colors.GREEN) - typer.echo(f"Focus file: {focus_file}") + state = focus_service.set_device(device) + except ( + FocusFileInvalidError, + FocusNotConfiguredError, + DatabaseMissingError, + InvalidDeviceError, + ) as e: + _error(str(e)) + + typer.secho(f"Focused device ({state.source}): {device}", fg=typer.colors.GREEN) + if state.source == "project" and state.focus_file: + typer.echo(f"Focus file: {state.focus_file}") raise typer.Exit() - # Handle db_path provided (with optional device) - if not db_path.exists(): - typer.secho(f"Error: Database file not found: {db_path}", fg=typer.colors.RED) - raise typer.Exit(1) - try: - ctx = Context(db_path) - resolved_db_path = db_path.expanduser().resolve() - - if device is not None and device not in ctx.device_ids: - typer.secho( - f"Error: Device {device} not found. Available: {ctx.device_ids}", - fg=typer.colors.RED, - ) - raise typer.Exit(1) - if session: - import shlex - - typer.echo(f"export {ENV_DB_PATH}={shlex.quote(str(resolved_db_path))}") + state = focus_service.validate_session_db(db_path) + typer.echo(f"export {ENV_DB_PATH}={shlex.quote(str(state.db_path))}") return if global_focus: - config.current_db_path = resolved_db_path - if device is not None: - config.current_device_id = device - typer.secho(f"Using global database: {resolved_db_path}", fg=typer.colors.GREEN) - if device is not None: - typer.echo(f"Focused device: {device}") + state = focus_service.set_global_focus(db_path, device) + typer.secho(f"Using global database: {state.db_path}", fg=typer.colors.GREEN) else: - focus_file = config.write_project_focus(resolved_db_path, device_id=device) - typer.secho(f"Using project database: {resolved_db_path}", fg=typer.colors.GREEN) - typer.echo(f"Focus file: {focus_file}") - if device is not None: - typer.echo(f"Focused device: {device}") - devices = ctx.device_ids - if devices: - typer.echo(f"Available devices: {', '.join(map(str, devices))}") + state = focus_service.set_project_focus(db_path, device) + typer.secho(f"Using project database: {state.db_path}", fg=typer.colors.GREEN) + if state.focus_file: + typer.echo(f"Focus file: {state.focus_file}") + if device is not None: + typer.echo(f"Focused device: {device}") + if state.available_devices: + typer.echo(f"Available devices: {', '.join(map(str, state.available_devices))}") else: typer.echo("No devices found in database.") - except (DatabaseNotFoundError, SchemaVersionError) as e: - typer.secho(f"Error: {e}", fg=typer.colors.RED) - raise typer.Exit(1) from None - except Exception as e: - typer.secho(f"Error: unexpected failure opening database: {e}", fg=typer.colors.RED) - raise typer.Exit(1) from None + except ( + DatabaseMissingError, + DatabaseSchemaError, + InvalidDeviceError, + FocusFileInvalidError, + ) as e: + _error(str(e)) @app.command("query") @@ -218,209 +192,157 @@ def query_database( ), ] = None, ) -> None: - """Execute queries on the memory snapshot database. - - The db_path argument is optional if you have configured a focus with 'pt-snap focus'. - The device argument is optional if you have set a focused device. - - Use --list to see all supported query templates. - Use --template-info {template_name} to see detailed template information. - - Examples: - pt-snap focus snapshot.pkl.db # Set project database - pt-snap focus snapshot.pkl.db --device 0 # Set database and device - pt-snap focus --device 1 # Change device only - pt-snap query --list # List templates - pt-snap query --template-use leak_detection # Uses focused db and device - pt-snap query --template-use block --device 0 --state 1 - pt-snap query custom.db --template-use leak_detection # Override with custom path - pt-snap query --template-info leak_detection - pt-snap query --list --category basic # List only basic queries - """ - from pt_snap_cli.query import QueryExecutor - from pt_snap_cli.query.registry import ( - discover_categories, - get_template_info, - list_by_category_with_details, - ) - - # Implicit list mode when --category is provided without --template-use + """Execute queries on the memory snapshot database.""" + focus_service = _focus_service() + query_service = _query_service() + if category is not None and not list_templates and not template_use and not template_info: list_templates = True if list_templates: - categories = discover_categories() - category_labels = {cat: cat.replace("_", " ").title() + " Queries" for cat in categories} - - if category is not None and category not in categories: - typer.secho( - f"Error: Invalid category '{category}'. Must be one of: {', '.join(categories)}", - fg=typer.colors.RED, - ) - raise typer.Exit(1) - - filter_cats = [category] if category in categories else categories - any_found = False - - for cat in filter_cats: - details = list_by_category_with_details(cat) - if details: - any_found = True - typer.secho(f"{category_labels[cat]}:", fg=typer.colors.GREEN, bold=True) - for info in details: - typer.secho(f" {info['name']}", fg=typer.colors.GREEN, bold=True) - typer.echo(f" {info['description']}") - typer.echo() - - if not any_found: - typer.echo("No query templates available.") + try: + categories = discover_categories() + category_labels = { + cat: cat.replace("_", " ").title() + " Queries" for cat in categories + } + if category is not None: + filter_cats = [category] + query_service.list_templates(category) + else: + filter_cats = categories + any_found = False + for cat in filter_cats: + details = query_service.list_templates(cat, validate_category=False) + if details: + any_found = True + typer.secho(f"{category_labels[cat]}:", fg=typer.colors.GREEN, bold=True) + for info in details: + typer.secho(f" {info.name}", fg=typer.colors.GREEN, bold=True) + typer.echo(f" {info.description}") + typer.echo() + if not any_found: + typer.echo("No query templates available.") + except InvalidCategoryError as e: + _error(str(e)) raise typer.Exit() if template_info: - info = get_template_info(template_info) - if info: - typer.secho(f"Template: {info['name']}", fg=typer.colors.GREEN, bold=True) - typer.echo(f"Description: {info['description']}") - typer.echo() - - typer.echo("Parameters:") - if info["parameters"]: - for param_name, param_details in info["parameters"].items(): - required_str = " (required)" if param_details["required"] else " (optional)" - default_str = ( - f" [default: {param_details['default']}]" - if param_details["default"] is not None - else "" - ) - typer.secho( - f" {param_name}: {param_details['type']}{required_str}{default_str}", - fg=typer.colors.YELLOW, - ) - typer.echo(f" {param_details['description']}") - else: - typer.echo(" None") - typer.echo() - - typer.echo("Output Schema:") - if info["output_schema"]: - for col in info["output_schema"]: - typer.echo(f" {col['column']}: {col['type']}") - else: - typer.echo(" Dynamic (depends on query)") - typer.echo() - - typer.echo("Example Usage:") - example_params = {} - for param_name, param_details in info["parameters"].items(): - if param_details["type"] == "int": - example_params[param_name] = ( - param_details["default"] if param_details["default"] is not None else 0 - ) - elif param_details["type"] == "float": - example_params[param_name] = ( - param_details["default"] if param_details["default"] is not None else 0.0 - ) - elif param_details["type"] == "str": - example_params[param_name] = ( - param_details["default"] - if param_details["default"] is not None - else "example" - ) - elif param_details["type"] == "bool": - example_params[param_name] = True - - if example_params: - import json - - params_str = json.dumps(example_params) - typer.echo( - f" pt-snap query {db_path or ''} --template-use {info['name']} --params '{params_str}'" + try: + info = query_service.get_template_info(template_info) + except TemplateNotFoundError: + typer.secho(f"Error: Template '{template_info}' not found", fg=typer.colors.RED) + raise typer.Exit() from None + + typer.secho(f"Template: {info.name}", fg=typer.colors.GREEN, bold=True) + typer.echo(f"Description: {info.description}") + typer.echo() + typer.echo("Parameters:") + if info.parameters: + for param_name, param_details in info.parameters.items(): + required_str = " (required)" if param_details.required else " (optional)" + default_str = ( + f" [default: {param_details.default}]" + if param_details.default is not None + else "" ) - else: - typer.echo( - f" pt-snap query {db_path or ''} --template-use {info['name']}" + typer.secho( + f" {param_name}: {param_details.type}{required_str}{default_str}", + fg=typer.colors.YELLOW, ) + typer.echo(f" {param_details.description}") else: - typer.secho(f"Error: Template '{template_info}' not found", fg=typer.colors.RED) + typer.echo(" None") + typer.echo() + typer.echo("Output Schema:") + if info.output_schema: + for col in info.output_schema: + typer.echo(f" {col['column']}: {col['type']}") + else: + typer.echo(" Dynamic (depends on query)") + typer.echo() + typer.echo("Example Usage:") + example_params = {} + for param_name, param_details in info.parameters.items(): + if param_details.type == "int": + example_params[param_name] = ( + param_details.default if param_details.default is not None else 0 + ) + elif param_details.type == "float": + example_params[param_name] = ( + param_details.default if param_details.default is not None else 0.0 + ) + elif param_details.type == "str": + example_params[param_name] = ( + param_details.default if param_details.default is not None else "example" + ) + elif param_details.type == "bool": + example_params[param_name] = True + if example_params: + typer.echo( + f" pt-snap query {db_path or ''} --template-use {info.name} --params '{json.dumps(example_params)}'" + ) + else: + typer.echo(f" pt-snap query {db_path or ''} --template-use {info.name}") raise typer.Exit() if not template_use: - typer.secho( - "Error: --template-use is required when not using --list or --template-info", - fg=typer.colors.RED, - ) - raise typer.Exit(1) + _error("--template-use is required when not using --list or --template-info") - config = Config() try: - resolved = config.resolve_focus(db_path, explicit_device_id=device) - except FocusResolutionError as e: - typer.secho(f"Error: {e}", fg=typer.colors.RED) - raise typer.Exit(1) from None - - db_path = resolved.db_path - if db_path is None: + query_params = json.loads(params) if params else {} + result = query_service.execute_query( + template=template_use, + params=query_params, + db_path=db_path, + device_id=device, + max_rows=max_rows, + ) + if result.rows: + typer.echo(f"Found {result.total} results, showing {result.returned}:") + for row in result.rows: + typer.echo(f" {row}") + if result.returned < result.total: + typer.echo(f" ... and {result.total - result.returned} more (use -n to show more)") + else: + typer.echo("No results found.") + except FocusFileInvalidError as e: + _error(str(e)) + except FocusNotConfiguredError: typer.secho( - "Error: No database path specified and no database configured.", - fg=typer.colors.RED, + "Error: No database path specified and no database configured.", fg=typer.colors.RED ) typer.echo( "Use 'pt-snap focus ' to set a project database, or provide db_path argument." ) - raise typer.Exit(1) - if not db_path.exists(): - typer.secho( - f"Error: Database from {resolved.source} focus not found: {db_path}", - fg=typer.colors.RED, - ) - if resolved.focus_file: - typer.echo(f"Focus file: {resolved.focus_file}") + raise typer.Exit(1) from None + except DatabaseMissingError: + try: + state = focus_service.get_focus(explicit_db_path=db_path, explicit_device_id=device) + except FocusFileInvalidError: + state = None + source = state.source if state is not None else "configured" + path = state.db_path if state is not None else db_path + typer.secho(f"Error: Database from {source} focus not found: {path}", fg=typer.colors.RED) + if state is not None and state.focus_file: + typer.echo(f"Focus file: {state.focus_file}") typer.echo( "Use 'pt-snap focus ' to set a new project database, or provide db_path argument." ) - raise typer.Exit(1) - - try: - context = Context(db_path, devices=[device] if device is not None else None) - executor = QueryExecutor( - context, template_dir=Path(__file__).parent / "query" / "templates" - ) - - query_params = {} - if params: - import json - - query_params = json.loads(params) - - # Determine device: explicit > focused > first discovered - if device is not None: - target_device = device - elif resolved.device_id is not None: - target_device = resolved.device_id - else: - device_ids = context.device_ids - if not device_ids: - typer.echo("No devices found in database.") - raise typer.Exit() - target_device = device_ids[0] - - results = executor.execute_template(template_use, query_params, device_id=target_device) - - if results: - effective_limit = max_rows if max_rows is not None and max_rows > 0 else len(results) - display = results[:effective_limit] - typer.echo(f"Found {len(results)} results, showing {len(display)}:") - for row in display: - typer.echo(f" {row}") - if effective_limit < len(results): - typer.echo(f" ... and {len(results) - effective_limit} more (use -n to show more)") - else: - typer.echo("No results found.") - - except FileNotFoundError as e: - typer.secho(f"Error: {e}", fg=typer.colors.RED) raise typer.Exit(1) from None - except Exception as e: + except InvalidDeviceError as e: + if str(e) == "No devices found in database.": + typer.echo("No devices found in database.") + raise typer.Exit() from None + _error(str(e)) + except TemplateNotFoundError as e: + typer.secho(f"Error executing query: {e}", fg=typer.colors.RED) + raise typer.Exit(1) from None + except ( + TemplateRenderError, + QueryExecutionError, + DatabaseSchemaError, + json.JSONDecodeError, + ) as e: typer.secho(f"Error executing query: {e}", fg=typer.colors.RED) raise typer.Exit(1) from None @@ -430,24 +352,19 @@ def show_config( clear: Annotated[bool, typer.Option("--clear", help="Clear all configuration")] = False, show_path: Annotated[bool, typer.Option("--path", help="Show config file path")] = False, ) -> None: - """Show or manage pt-snap configuration. - - Shows current configuration including the configured database path. - Use --clear to reset configuration. - Use --path to see where configuration is stored. - """ - config = Config() + """Show or manage pt-snap configuration.""" + focus_service = _focus_service() if show_path: - typer.echo(f"Config file: {config.config_file}") + typer.echo(f"Config file: {focus_service.get_global_config_path()}") raise typer.Exit() if clear: - config.clear() + focus_service.clear_global_focus() typer.secho("Configuration cleared.", fg=typer.colors.GREEN) raise typer.Exit() - current_config = config.show() + current_config = focus_service.show_global_config() if not current_config: typer.echo("No configuration set.") else: @@ -456,20 +373,16 @@ def show_config( typer.echo(f" {key}: {value}") -def _safe_call() -> int: - """Wrapper for the console script entry point to handle completion errors. +def _error(message: str) -> None: + typer.secho(f"Error: {message}", fg=typer.colors.RED) + raise typer.Exit(1) from None - Returns: - Exit code (0 for success, 1 for errors). - """ + +def _safe_call() -> int: try: app() return 0 except KeyError as e: - # Click's shell completion can raise KeyError when COMP_WORDS or - # COMP_LINE is not set in non-standard terminal environments. - # Exit silently — printing to stdout causes the shell to try - # executing the error message as a command. if str(e) in ("'COMP_WORDS'", "'COMP_LINE'", "'COMP_POINT'"): return 1 raise diff --git a/src/pt_snap_cli/core/__init__.py b/src/pt_snap_cli/core/__init__.py new file mode 100644 index 0000000..582530c --- /dev/null +++ b/src/pt_snap_cli/core/__init__.py @@ -0,0 +1,43 @@ +from pt_snap_cli.core.errors import ( + DatabaseMissingError, + DatabaseSchemaError, + FocusFileInvalidError, + FocusNotConfiguredError, + InvalidCategoryError, + InvalidDeviceError, + PtSnapCoreError, + QueryExecutionError, + TemplateNotFoundError, + TemplateRenderError, +) +from pt_snap_cli.core.focus_service import FocusService +from pt_snap_cli.core.models import ( + FocusState, + QueryResult, + ResolvedFocus, + TemplateInfo, + TemplateParameter, + TemplateSummary, +) +from pt_snap_cli.core.query_service import QueryService + +__all__ = [ + "PtSnapCoreError", + "FocusNotConfiguredError", + "FocusFileInvalidError", + "DatabaseMissingError", + "DatabaseSchemaError", + "InvalidDeviceError", + "InvalidCategoryError", + "TemplateNotFoundError", + "TemplateRenderError", + "QueryExecutionError", + "ResolvedFocus", + "FocusState", + "TemplateParameter", + "TemplateSummary", + "TemplateInfo", + "QueryResult", + "FocusService", + "QueryService", +] diff --git a/src/pt_snap_cli/core/errors.py b/src/pt_snap_cli/core/errors.py new file mode 100644 index 0000000..e977746 --- /dev/null +++ b/src/pt_snap_cli/core/errors.py @@ -0,0 +1,38 @@ +class PtSnapCoreError(Exception): + pass + + +class FocusNotConfiguredError(PtSnapCoreError): + pass + + +class FocusFileInvalidError(PtSnapCoreError): + pass + + +class DatabaseMissingError(PtSnapCoreError): + pass + + +class DatabaseSchemaError(PtSnapCoreError): + pass + + +class InvalidDeviceError(PtSnapCoreError): + pass + + +class InvalidCategoryError(PtSnapCoreError): + pass + + +class TemplateNotFoundError(PtSnapCoreError): + pass + + +class TemplateRenderError(PtSnapCoreError): + pass + + +class QueryExecutionError(PtSnapCoreError): + pass diff --git a/src/pt_snap_cli/core/focus_service.py b/src/pt_snap_cli/core/focus_service.py new file mode 100644 index 0000000..b1589d0 --- /dev/null +++ b/src/pt_snap_cli/core/focus_service.py @@ -0,0 +1,168 @@ +from __future__ import annotations + +import sqlite3 +from pathlib import Path +from typing import Any + +from pt_snap_cli.config import Config, FocusResolutionError +from pt_snap_cli.context import Context, DatabaseNotFoundError, SchemaVersionError +from pt_snap_cli.core.errors import ( + DatabaseMissingError, + DatabaseSchemaError, + FocusFileInvalidError, + FocusNotConfiguredError, + InvalidDeviceError, +) +from pt_snap_cli.core.models import FocusState, ResolvedFocus + + +class FocusService: + def __init__(self, config: Config | None = None) -> None: + self._config = config or Config() + + def resolve_focus( + self, + explicit_db_path: Path | str | None = None, + explicit_device_id: int | None = None, + start_dir: Path | None = None, + ) -> ResolvedFocus: + try: + resolved = self._config.resolve_focus( + explicit_db_path=explicit_db_path, + explicit_device_id=explicit_device_id, + start_dir=start_dir, + ) + except FocusResolutionError as exc: + raise FocusFileInvalidError(str(exc)) from exc + + return ResolvedFocus( + db_path=resolved.db_path, + device_id=resolved.device_id, + source=resolved.source, + focus_file=resolved.focus_file, + ) + + def get_focus( + self, + start_dir: Path | None = None, + explicit_db_path: Path | str | None = None, + explicit_device_id: int | None = None, + ) -> FocusState: + resolved = self.resolve_focus(explicit_db_path, explicit_device_id, start_dir) + available_devices: list[int] = [] + + if resolved.db_path is not None and resolved.db_path.exists(): + try: + available_devices = Context(resolved.db_path).device_ids + except (DatabaseNotFoundError, SchemaVersionError): + available_devices = [] + + return FocusState( + db_path=resolved.db_path, + device_id=resolved.device_id, + available_devices=available_devices, + source=resolved.source, + focus_file=resolved.focus_file, + ) + + def set_project_focus( + self, + db_path: Path | str, + device_id: int | None = None, + base_dir: Path | None = None, + ) -> FocusState: + db_path = Path(db_path).expanduser().resolve() + ctx = self._validated_context(db_path) + self._validate_device(ctx, device_id) + self._config.write_project_focus(db_path, base_dir=base_dir, device_id=device_id) + return FocusState( + db_path=db_path, + device_id=device_id, + available_devices=ctx.device_ids, + source="project", + focus_file=self._config.project_focus_path(base_dir), + ) + + def set_global_focus(self, db_path: Path | str, device_id: int | None = None) -> FocusState: + db_path = Path(db_path).expanduser().resolve() + ctx = self._validated_context(db_path) + self._validate_device(ctx, device_id) + self._config.current_db_path = db_path + self._config.current_device_id = device_id + return FocusState( + db_path=db_path, + device_id=device_id, + available_devices=ctx.device_ids, + source="global", + focus_file=self._config.config_file, + ) + + def set_device( + self, + device_id: int, + start_dir: Path | None = None, + scope: str = "resolved", + ) -> FocusState: + resolved = self.resolve_focus(start_dir=start_dir) + if resolved.db_path is None: + raise FocusNotConfiguredError("No database set. Use 'pt-snap focus ' first.") + + ctx = self._validated_context(resolved.db_path) + self._validate_device(ctx, device_id) + + if scope == "global" or (scope == "resolved" and resolved.source == "global"): + self._config.current_device_id = device_id + return FocusState( + db_path=resolved.db_path, + device_id=device_id, + available_devices=ctx.device_ids, + source="global", + focus_file=self._config.config_file, + ) + + focus_file = self._config.write_project_focus( + resolved.db_path, + base_dir=start_dir, + device_id=device_id, + ) + return FocusState( + db_path=resolved.db_path, + device_id=device_id, + available_devices=ctx.device_ids, + source="project", + focus_file=focus_file, + ) + + def clear_global_focus(self) -> None: + self._config.clear() + + def show_global_config(self) -> dict[str, Any]: + return self._config.show() + + def get_global_config_path(self) -> Path: + return self._config.config_file + + def validate_session_db(self, db_path: Path | str) -> FocusState: + db_path = Path(db_path).expanduser().resolve() + ctx = self._validated_context(db_path) + return FocusState( + db_path=db_path, + device_id=None, + available_devices=ctx.device_ids, + source="explicit", + focus_file=None, + ) + + def _validated_context(self, db_path: Path) -> Context: + try: + return Context(db_path) + except DatabaseNotFoundError as exc: + raise DatabaseMissingError(str(exc)) from exc + except (SchemaVersionError, sqlite3.DatabaseError) as exc: + raise DatabaseSchemaError(str(exc)) from exc + + def _validate_device(self, ctx: Context, device_id: int | None) -> None: + if device_id is None: + return + if device_id not in ctx.device_ids: + raise InvalidDeviceError(f"Device {device_id} not found. Available: {ctx.device_ids}") diff --git a/src/pt_snap_cli/core/models.py b/src/pt_snap_cli/core/models.py new file mode 100644 index 0000000..d25b50a --- /dev/null +++ b/src/pt_snap_cli/core/models.py @@ -0,0 +1,61 @@ +from __future__ import annotations + +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Literal + +FocusSource = Literal["explicit", "env", "project", "global", "none"] + + +@dataclass(frozen=True) +class ResolvedFocus: + db_path: Path | None + device_id: int | None + source: FocusSource + focus_file: Path | None = None + + @property + def is_configured(self) -> bool: + return self.db_path is not None + + +@dataclass(frozen=True) +class FocusState: + db_path: Path | None + device_id: int | None + available_devices: list[int] = field(default_factory=list) + source: FocusSource = "none" + focus_file: Path | None = None + + +@dataclass(frozen=True) +class TemplateParameter: + type: str + default: object | None + required: bool + description: str + + +@dataclass(frozen=True) +class TemplateSummary: + name: str + description: str + category: str | None + + +@dataclass(frozen=True) +class TemplateInfo: + name: str + description: str + category: str | None + devices: str | None + parameters: dict[str, TemplateParameter] + output_schema: list[dict[str, str]] | None + + +@dataclass(frozen=True) +class QueryResult: + total: int + returned: int + device_id: int | None + rows: list[dict[str, Any]] diff --git a/src/pt_snap_cli/core/query_service.py b/src/pt_snap_cli/core/query_service.py new file mode 100644 index 0000000..af4d018 --- /dev/null +++ b/src/pt_snap_cli/core/query_service.py @@ -0,0 +1,170 @@ +from __future__ import annotations + +import sqlite3 +from pathlib import Path +from typing import Any + +from pt_snap_cli.context import Context, DatabaseNotFoundError, SchemaVersionError +from pt_snap_cli.core.errors import ( + DatabaseMissingError, + DatabaseSchemaError, + FocusNotConfiguredError, + InvalidCategoryError, + InvalidDeviceError, + QueryExecutionError, + TemplateNotFoundError, + TemplateRenderError, +) +from pt_snap_cli.core.focus_service import FocusService +from pt_snap_cli.core.models import QueryResult, TemplateInfo, TemplateParameter, TemplateSummary +from pt_snap_cli.query.executor import QueryExecutionError as ExecutorQueryExecutionError +from pt_snap_cli.query.executor import QueryExecutor +from pt_snap_cli.query.executor import TemplateRenderError as ExecutorTemplateRenderError +from pt_snap_cli.query.registry import ( + discover_categories, + get_query, + get_template_info, + list_by_category_with_details, + list_queries_with_details, +) + + +class QueryService: + def __init__(self, focus_service: FocusService | None = None) -> None: + self._focus_service = focus_service or FocusService() + + def list_templates( + self, + category: str | None = None, + validate_category: bool = True, + ) -> list[TemplateSummary]: + if category is not None and validate_category: + categories = discover_categories() + if category not in categories: + raise InvalidCategoryError( + f"Invalid category '{category}'. Must be one of: {', '.join(categories)}" + ) + + template_rows = ( + list_by_category_with_details(category) + if category is not None + else list_queries_with_details() + ) + return [ + TemplateSummary( + name=row["name"], + description=row["description"], + category=( + get_query(row["name"]).category + if get_query(row["name"]) is not None + else category + ), + ) + for row in template_rows + ] + + def get_template_info(self, name: str) -> TemplateInfo: + template = get_query(name) + if template is None: + raise TemplateNotFoundError(f"Template '{name}' not found") + + info = get_template_info(name) + if info is None: + raise TemplateNotFoundError(f"Template '{name}' not found") + + devices = info["devices"] + if isinstance(devices, list): + devices = ", ".join(devices) + + return TemplateInfo( + name=info["name"], + description=info["description"], + category=template.category, + devices=devices, + parameters={ + param_name: TemplateParameter( + type=param_details["type"], + default=param_details["default"], + required=param_details["required"], + description=param_details["description"], + ) + for param_name, param_details in info["parameters"].items() + }, + output_schema=info["output_schema"], + ) + + def execute_query( + self, + template: str, + params: dict[str, Any] | None = None, + db_path: Path | str | None = None, + device_id: int | None = None, + start_dir: Path | None = None, + max_rows: int | None = None, + ) -> QueryResult: + resolved = self._focus_service.resolve_focus( + explicit_db_path=db_path, + explicit_device_id=device_id, + start_dir=start_dir, + ) + if resolved.db_path is None: + raise FocusNotConfiguredError("No database path specified and no database configured.") + + ctx = self._validated_context(resolved.db_path) + target_device = self._resolve_device_id(ctx, resolved.device_id, device_id) + executor = QueryExecutor( + ctx, template_dir=Path(__file__).parent.parent / "query" / "templates" + ) + + try: + rows = executor.execute_template(template, params or {}, device_id=target_device) + except ExecutorTemplateRenderError as exc: + raise TemplateRenderError(str(exc)) from exc + except ExecutorQueryExecutionError as exc: + if get_query(template) is None: + raise TemplateNotFoundError(f"Template '{template}' not found") from exc + raise QueryExecutionError(str(exc)) from exc + + if max_rows is None or max_rows <= 0: + limited_rows = rows + else: + limited_rows = rows[:max_rows] + + return QueryResult( + total=len(rows), + returned=len(limited_rows), + device_id=target_device, + rows=limited_rows, + ) + + def _resolve_device_id( + self, + ctx: Context, + focused_device_id: int | None, + explicit_device_id: int | None, + ) -> int | None: + if explicit_device_id is not None: + if explicit_device_id not in ctx.device_ids: + raise InvalidDeviceError( + f"Device {explicit_device_id} not found. Available: {ctx.device_ids}" + ) + return explicit_device_id + + if focused_device_id is not None: + if focused_device_id not in ctx.device_ids: + raise InvalidDeviceError( + f"Device {focused_device_id} not found. Available: {ctx.device_ids}" + ) + return focused_device_id + + if not ctx.device_ids: + raise InvalidDeviceError("No devices found in database.") + return ctx.device_ids[0] + + def _validated_context(self, db_path: Path) -> Context: + try: + return Context(db_path) + except DatabaseNotFoundError as exc: + raise DatabaseMissingError(str(exc)) from exc + except (SchemaVersionError, sqlite3.DatabaseError) as exc: + raise DatabaseSchemaError(str(exc)) from exc diff --git a/src/pt_snap_cli/mcp/server.py b/src/pt_snap_cli/mcp/server.py index 5d74c0f..5dfe9e2 100644 --- a/src/pt_snap_cli/mcp/server.py +++ b/src/pt_snap_cli/mcp/server.py @@ -16,7 +16,6 @@ @mcp.tool() def get_focus() -> dict[str, Any]: - """Get the current analysis focus (database path and device).""" state = _analyzer.get_focus() return { "db_path": state.db_path, @@ -28,10 +27,6 @@ def get_focus() -> dict[str, Any]: @mcp.tool() def set_focus(db_path: str | None = None, device_id: int | None = None) -> dict[str, Any]: - """Set the analysis focus to a specific database and optional device. - - Use this before running queries to point to the correct snapshot file. - """ state = _analyzer.set_focus(db_path, device_id) return { "db_path": state.db_path, @@ -42,20 +37,11 @@ def set_focus(db_path: str | None = None, device_id: int | None = None) -> dict[ @mcp.tool() def list_templates(category: str | None = None) -> list[dict[str, Any]]: - """List available query templates, optionally filtered by category. - - Common categories include 'basic' for simple queries and 'analysis' - for advanced memory analysis templates. - """ return _analyzer.list_templates(category) @mcp.tool() def get_template_info(template_name: str) -> dict[str, Any]: - """Get detailed information about a query template including parameters and output schema. - - Use this to understand what parameters a template accepts before calling execute_query. - """ info = _analyzer.get_template_info(template_name) if info is None: return {"error": f"Template '{template_name}' not found"} @@ -69,22 +55,11 @@ def execute_query( device_id: int | None = None, max_rows: int = 100, ) -> dict[str, Any]: - """Execute a query template against the focused database. - - Args: - template: Template name (e.g., 'leak_detection', 'callstack_analysis'). - Use list_templates to discover available templates. - params: Query parameters as a dict. Use get_template_info to see - what parameters each template accepts. - device_id: Device ID to query (uses focused device if not specified). - max_rows: Maximum rows to return (0 for unlimited, default: 100). - """ return _analyzer.execute_query(template, params, device_id, max_rows) @mcp.resource("focus://current") def focus_resource() -> dict[str, Any]: - """Current analysis focus state.""" state = _analyzer.get_focus() return { "db_path": state.db_path, @@ -99,7 +74,6 @@ def analyze_memory_leaks( db_path: str, device_id: int = 0, ) -> str: - """Generate a prompt template for analyzing memory leaks in a PyTorch snapshot.""" return ( f"Analyze the PyTorch memory snapshot at '{db_path}' for device {device_id}. " f"First, set focus to the database, then run the leak_detection template. " @@ -108,7 +82,6 @@ def analyze_memory_leaks( def main() -> None: - """Entry point for the MCP server.""" mcp.run() diff --git a/tests/core/test_focus_service.py b/tests/core/test_focus_service.py new file mode 100644 index 0000000..f9d8eb2 --- /dev/null +++ b/tests/core/test_focus_service.py @@ -0,0 +1,104 @@ +import json +import sqlite3 +from pathlib import Path +from unittest.mock import patch + +import pytest + +from pt_snap_cli.config import Config +from pt_snap_cli.core import ( + DatabaseMissingError, + FocusNotConfiguredError, + FocusService, + InvalidDeviceError, +) + + +@pytest.fixture(autouse=True) +def mock_home(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): + monkeypatch.chdir(tmp_path) + monkeypatch.delenv("PT_SNAP_DB_PATH", raising=False) + with patch.object(Path, "home", return_value=tmp_path): + yield + + +@pytest.fixture +def sample_db(tmp_path: Path) -> Path: + db_path = tmp_path / "sample.db" + conn = sqlite3.connect(str(db_path)) + conn.execute("CREATE TABLE dictionary (`table` TEXT, `column` TEXT, `key` TEXT, `value` TEXT)") + conn.execute("CREATE TABLE trace_entry_0 (id INTEGER PRIMARY KEY, size INTEGER)") + conn.execute("CREATE TABLE trace_entry_1 (id INTEGER PRIMARY KEY, size INTEGER)") + conn.commit() + conn.close() + return db_path + + +class TestFocusService: + def test_get_focus_uses_project_focus(self, sample_db: Path) -> None: + config = Config() + config.write_project_focus(sample_db, device_id=0) + + state = FocusService(config).get_focus() + + assert state.db_path == sample_db.resolve() + assert state.device_id == 0 + assert state.source == "project" + assert state.available_devices == [0, 1] + + def test_get_focus_with_missing_db_keeps_state(self, tmp_path: Path) -> None: + focus_dir = tmp_path / ".pt-snap" + focus_dir.mkdir() + (focus_dir / "focus.json").write_text( + json.dumps({"db_path": "/missing.db", "device_id": 0}) + ) + + state = FocusService().get_focus() + + assert state.db_path == Path("/missing.db") + assert state.device_id == 0 + assert state.available_devices == [] + + def test_set_project_focus_with_device_zero(self, sample_db: Path) -> None: + state = FocusService().set_project_focus(sample_db, device_id=0) + + assert state.device_id == 0 + assert state.available_devices == [0, 1] + focus_data = json.loads((Path.cwd() / ".pt-snap" / "focus.json").read_text()) + assert focus_data["device_id"] == 0 + + def test_set_device_updates_project_focus(self, sample_db: Path) -> None: + config = Config() + config.write_project_focus(sample_db) + + state = FocusService(config).set_device(0) + + assert state.device_id == 0 + focus_data = json.loads((Path.cwd() / ".pt-snap" / "focus.json").read_text()) + assert focus_data["device_id"] == 0 + + def test_set_device_without_focus_fails(self) -> None: + with pytest.raises(FocusNotConfiguredError): + FocusService().set_device(0) + + def test_set_device_with_missing_db_fails(self, tmp_path: Path) -> None: + focus_dir = tmp_path / ".pt-snap" + focus_dir.mkdir() + (focus_dir / "focus.json").write_text(json.dumps({"db_path": "/missing.db"})) + + with pytest.raises(DatabaseMissingError): + FocusService().set_device(0) + + def test_set_device_invalid_device_fails(self, sample_db: Path) -> None: + config = Config() + config.write_project_focus(sample_db) + + with pytest.raises(InvalidDeviceError): + FocusService(config).set_device(99) + + def test_validate_session_db_returns_devices(self, sample_db: Path) -> None: + state = FocusService().validate_session_db(sample_db) + + assert state.db_path == sample_db.resolve() + assert state.available_devices == [0, 1] + assert not (Path.cwd() / ".pt-snap" / "focus.json").exists() diff --git a/tests/core/test_query_service.py b/tests/core/test_query_service.py new file mode 100644 index 0000000..edefdda --- /dev/null +++ b/tests/core/test_query_service.py @@ -0,0 +1,123 @@ +import sqlite3 +from pathlib import Path +from unittest.mock import patch + +import pytest + +from pt_snap_cli.config import Config +from pt_snap_cli.core import ( + FocusNotConfiguredError, + InvalidCategoryError, + InvalidDeviceError, + QueryService, + TemplateNotFoundError, +) +from pt_snap_cli.query.config import QueryTemplate +from pt_snap_cli.query.registry import QueryRegistry, register_query + + +@pytest.fixture(autouse=True) +def mock_home(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): + monkeypatch.chdir(tmp_path) + monkeypatch.delenv("PT_SNAP_DB_PATH", raising=False) + with patch.object(Path, "home", return_value=tmp_path): + QueryRegistry.reset() + yield + QueryRegistry.reset() + + +@pytest.fixture +def sample_db(tmp_path: Path) -> Path: + db_path = tmp_path / "sample.db" + conn = sqlite3.connect(str(db_path)) + conn.execute("CREATE TABLE dictionary (`table` TEXT, `column` TEXT, `key` TEXT, `value` TEXT)") + conn.execute("CREATE TABLE trace_entry_0 (id INTEGER PRIMARY KEY, size INTEGER)") + conn.execute("CREATE TABLE trace_entry_1 (id INTEGER PRIMARY KEY, size INTEGER)") + conn.execute("INSERT INTO trace_entry_0 (size) VALUES (10), (20)") + conn.commit() + conn.close() + return db_path + + +class TestQueryService: + def test_list_templates_invalid_category(self) -> None: + with pytest.raises(InvalidCategoryError): + QueryService().list_templates("does-not-exist") + + def test_get_template_info_missing(self) -> None: + with pytest.raises(TemplateNotFoundError): + QueryService().get_template_info("missing") + + def test_execute_query_requires_focus(self) -> None: + with pytest.raises(FocusNotConfiguredError): + QueryService().execute_query("leak_detection") + + def test_execute_query_uses_focused_device_zero(self, sample_db: Path) -> None: + config = Config() + config.write_project_focus(sample_db, device_id=0) + register_query( + QueryTemplate( + name="size_query", description="Test", query="SELECT size FROM trace_entry_0" + ) + ) + + result = QueryService().execute_query("size_query") + + assert result.device_id == 0 + assert result.total == 2 + assert result.returned == 2 + + def test_execute_query_explicit_device_zero_wins(self, sample_db: Path) -> None: + config = Config() + config.write_project_focus(sample_db, device_id=1) + register_query( + QueryTemplate( + name="size_query", description="Test", query="SELECT size FROM trace_entry_0" + ) + ) + + result = QueryService().execute_query("size_query", device_id=0) + + assert result.device_id == 0 + + def test_execute_query_max_rows_zero_is_unlimited(self, sample_db: Path) -> None: + config = Config() + config.write_project_focus(sample_db) + register_query( + QueryTemplate( + name="size_query", description="Test", query="SELECT size FROM trace_entry_0" + ) + ) + + result = QueryService().execute_query("size_query", max_rows=0) + + assert result.total == 2 + assert result.returned == 2 + assert len(result.rows) == 2 + + def test_execute_query_max_rows_positive_limits_rows(self, sample_db: Path) -> None: + config = Config() + config.write_project_focus(sample_db) + register_query( + QueryTemplate( + name="size_query", description="Test", query="SELECT size FROM trace_entry_0" + ) + ) + + result = QueryService().execute_query("size_query", max_rows=1) + + assert result.total == 2 + assert result.returned == 1 + assert len(result.rows) == 1 + + def test_execute_query_invalid_device(self, sample_db: Path) -> None: + config = Config() + config.write_project_focus(sample_db) + register_query( + QueryTemplate( + name="size_query", description="Test", query="SELECT size FROM trace_entry_0" + ) + ) + + with pytest.raises(InvalidDeviceError): + QueryService().execute_query("size_query", device_id=99) diff --git a/tests/test_cli.py b/tests/test_cli.py index 8162424..b946139 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -610,6 +610,44 @@ def test_query_with_device(self, sample_db: Path) -> None: ) assert result.exit_code in [0, 1] + def test_query_uses_focused_device_zero(self, sample_db: Path) -> None: + """Test query respects focused device 0.""" + focus_dir = Path.cwd() / ".pt-snap" + focus_dir.mkdir() + (focus_dir / "focus.json").write_text( + json.dumps({"db_path": str(sample_db), "device_id": 0}) + ) + register_query( + QueryTemplate( + name="size_query_device_zero", + description="Test", + query="SELECT size FROM trace_entry_0", + ) + ) + + result = runner.invoke(app, ["query", "--template-use", "size_query_device_zero"]) + + assert result.exit_code == 0 + assert "'size': 1024" in result.stdout + + def test_query_max_rows_zero_is_unlimited(self, sample_db: Path) -> None: + """Test -n 0 shows all rows.""" + register_query( + QueryTemplate( + name="two_rows", + description="Test", + query="SELECT 1 AS value UNION ALL SELECT 2 AS value", + ) + ) + + result = runner.invoke( + app, + ["query", str(sample_db), "--template-use", "two_rows", "-n", "0"], + ) + + assert result.exit_code == 0 + assert "Found 2 results, showing 2:" in result.stdout + def test_query_with_params(self, sample_db: Path) -> None: """Test 'query' command with --params option.""" template = QueryTemplate(