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
20 changes: 17 additions & 3 deletions src/pt_snap_cli/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,14 @@
import typer

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, ContextResolutionError
from pt_snap_cli.context import Context

app = typer.Typer(
name="pt-snap",
help="PyTorch Memory Snapshot Analysis Tool",
add_completion=False,
add_completion=True,
context_settings={"help_option_names": ["-h", "--help"]},
)

Expand Down Expand Up @@ -112,10 +113,21 @@ def query_database(
Path | None, typer.Argument(help="Path to database file (optional if configured)")
] = None,
template_use: Annotated[
str | None, typer.Option("--template-use", help="Query template name to execute")
str | None,
typer.Option(
"--template-use",
help="Query template name to execute",
autocompletion=complete_template_names,
),
] = None,
params: Annotated[str | None, typer.Option(help="Query parameters as JSON string")] = None,
device: Annotated[int | None, typer.Option(help="Device ID to query")] = None,
device: Annotated[
int | None,
typer.Option(
help="Device ID to query",
autocompletion=complete_device_ids,
),
] = None,
list_templates: Annotated[
bool, typer.Option("--list", help="List all available query templates")
] = False,
Expand All @@ -124,13 +136,15 @@ def query_database(
typer.Option(
"--category",
help="Filter templates by category (basic, statistical, business)",
autocompletion=complete_categories,
),
] = None,
template_info: Annotated[
str | None,
typer.Option(
"--template-info",
help="Show detailed information about a template (including parameters and output schema)",
autocompletion=complete_template_names,
),
] = None,
) -> None:
Expand Down
70 changes: 70 additions & 0 deletions src/pt_snap_cli/completion.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
"""Shell completion functions for CLI options."""

from __future__ import annotations

import json
import os
from pathlib import Path

from pt_snap_cli.config import CURRENT_DB_KEY, Config


def complete_template_names() -> list[str]:
"""Return all registered query template names for shell completion."""
from pt_snap_cli.query.registry import list_queries

return sorted(list_queries())


def complete_categories() -> list[str]:
"""Return valid category names for shell completion."""
return ["basic", "statistical", "business"]


def _resolve_db_for_completion() -> Path | None:
"""Resolve the database path using the same priority as the CLI.

Priority: env var > project context > global config.
"""
env_path = os.environ.get("PT_SNAP_DB_PATH")
if env_path:
return Path(env_path).expanduser()

project_context = Config.find_project_context_path()
if project_context:
try:
with open(project_context) as f:
data = json.load(f)
db_path = data.get(CURRENT_DB_KEY)
if db_path:
return Path(db_path).expanduser()
except (json.JSONDecodeError, OSError):
pass

global_path = Config().current_db_path
return global_path


def complete_device_ids() -> list[str]:
"""Return device IDs from the resolved database for shell completion."""
import sqlite3

db_path = _resolve_db_for_completion()
if db_path is None or not db_path.exists():
return []

try:
uri = f"file:{db_path}?mode=ro"
with sqlite3.connect(uri, uri=True) as conn:
cursor = conn.cursor()
cursor.execute(
"SELECT name FROM sqlite_master WHERE type='table' AND name LIKE 'trace_entry_%'"
)
device_ids = []
for row in cursor.fetchall():
table_name = row[0]
device_id = table_name.split("_")[-1]
device_ids.append(device_id)
return sorted(device_ids, key=int)
except Exception:
return []
150 changes: 150 additions & 0 deletions tests/test_completion.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
"""Tests for shell completion functions."""

import json
import sqlite3
from pathlib import Path

import pytest

from pt_snap_cli.completion import (
complete_categories,
complete_device_ids,
complete_template_names,
)
from pt_snap_cli.config import (
CURRENT_DB_KEY,
PROJECT_CONTEXT_DIR,
PROJECT_CONTEXT_FILE,
)
from pt_snap_cli.query.config import QueryTemplate
from pt_snap_cli.query.registry import QueryRegistry, register_query


@pytest.fixture(autouse=True)
def reset_registry():
"""Reset query registry before each test."""
QueryRegistry.reset()
yield
QueryRegistry.reset()


def _create_sample_db(db_path: Path) -> Path:
"""Create a sample SQLite database with device tables."""
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, action TEXT
)
""")
conn.execute("""
CREATE TABLE trace_entry_1 (
id INTEGER PRIMARY KEY, action TEXT
)
""")
conn.commit()
conn.close()
return db_path


class TestCompleteTemplateNames:
def test_returns_registered_templates(self):
register_query(QueryTemplate(name="alpha_z_test", query="SELECT 1"))

result = complete_template_names()
assert "alpha_z_test" in result

def test_returns_sorted(self):
register_query(QueryTemplate(name="zebra_test", query="SELECT 1"))
register_query(QueryTemplate(name="apple_test", query="SELECT 1"))
after = complete_template_names()

# Verify the result is sorted and contains our new entries
assert after == sorted(after)
assert "apple_test" in after
assert "zebra_test" in after


class TestCompleteCategories:
def test_returns_three_categories(self):
result = complete_categories()
assert result == ["basic", "statistical", "business"]

def test_order_is_fixed(self):
assert complete_categories() == ["basic", "statistical", "business"]


class TestCompleteDeviceIds:
def test_returns_device_ids_from_db(self, tmp_path: Path):
db_path = _create_sample_db(tmp_path / "test.db")
import os

old_env = os.environ.get("PT_SNAP_DB_PATH")
os.environ["PT_SNAP_DB_PATH"] = str(db_path)
try:
result = complete_device_ids()
assert result == ["0", "1"]
finally:
if old_env is None:
os.environ.pop("PT_SNAP_DB_PATH", None)
else:
os.environ["PT_SNAP_DB_PATH"] = old_env

def test_returns_empty_for_no_db(self):
result = complete_device_ids()
# Without any DB configured, should return empty list
assert result == []

def test_returns_empty_for_invalid_db(self, tmp_path: Path):
import os

invalid_file = tmp_path / "not_a_db.txt"
invalid_file.write_text("not a database")
old_env = os.environ.get("PT_SNAP_DB_PATH")
os.environ["PT_SNAP_DB_PATH"] = str(invalid_file)
try:
result = complete_device_ids()
assert result == []
finally:
if old_env is None:
os.environ.pop("PT_SNAP_DB_PATH", None)
else:
os.environ["PT_SNAP_DB_PATH"] = old_env

def test_uses_project_context(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
db_path = _create_sample_db(tmp_path / "test.db")
context_dir = tmp_path / PROJECT_CONTEXT_DIR
context_dir.mkdir()
context_file = context_dir / PROJECT_CONTEXT_FILE
context_file.write_text(json.dumps({CURRENT_DB_KEY: str(db_path)}))
monkeypatch.chdir(tmp_path)

result = complete_device_ids()
assert result == ["0", "1"]

def test_sorted_by_integer_value(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
"""Device IDs should be sorted numerically, not lexicographically."""
import os

db_path = tmp_path / "test.db"
conn = sqlite3.connect(str(db_path))
conn.execute("CREATE TABLE dictionary (k TEXT, v TEXT)")
for dev in [0, 1, 2, 10]:
conn.execute(f"CREATE TABLE trace_entry_{dev} (id INTEGER PRIMARY KEY)")
conn.commit()
conn.close()

old_env = os.environ.get("PT_SNAP_DB_PATH")
os.environ["PT_SNAP_DB_PATH"] = str(db_path)
try:
result = complete_device_ids()
assert result == ["0", "1", "2", "10"]
finally:
if old_env is None:
os.environ.pop("PT_SNAP_DB_PATH", None)
else:
os.environ["PT_SNAP_DB_PATH"] = old_env
Loading