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
4 changes: 0 additions & 4 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,6 @@ dev = [
"build>=1.0.0",
"basedpyright>=1.39.3",
]
rag = [
"chromadb>=0.4.0",
"langchain>=0.1.0",
]

[project.scripts]
pt-snap = "pt_snap_cli.cli:_safe_call"
Expand Down
10 changes: 6 additions & 4 deletions src/pt_snap_cli/core/query_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,11 +157,13 @@ def execute_query(
)

def _get_executor(self, ctx: Context) -> QueryExecutor:
"""Reuse the executor while its cached database context remains valid."""
"""Reuse the executor while its cached database context remains valid.

Packaged templates are served by the registry, so the executor needs no
template directory of its own.
"""
if self._executor is None or self._executor_context is not ctx:
self._executor = QueryExecutor(
ctx, template_dir=Path(__file__).parent.parent / "query" / "templates"
)
self._executor = QueryExecutor(ctx)
self._executor_context = ctx
return self._executor

Expand Down
2 changes: 1 addition & 1 deletion src/pt_snap_cli/query/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
- Run `pytest tests/test_cli.py` when template listing/info/output behavior changes.

### Common Patterns
- Registry lookup is global and package templates load at import time.
- Registry lookup is global and package templates load at import time. It is the only loader for packaged templates: `QueryExecutor` has no template directory, and its `_configs` holds only templates attached at runtime through `load_config()` / `register_template()`, which take precedence over registry entries of the same name.
- `StrictUndefined` is used during template rendering so missing template variables fail loudly.
- Template categories are inferred from directory structure when not explicitly declared in YAML.
- `QueryService` translates executor errors to `core.errors` and owns cached Context/QueryExecutor reuse.
Expand Down
33 changes: 9 additions & 24 deletions src/pt_snap_cli/query/executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

import re
import sqlite3
import warnings
from pathlib import Path
from typing import Any

Expand Down Expand Up @@ -35,21 +34,22 @@ class TemplateRenderError(Exception):


class QueryExecutor:
"""Executes SQL queries with template rendering support."""
"""Executes SQL queries with template rendering support.

def __init__(
self,
context: Context,
template_dir: str | Path | None = None,
):
Packaged templates are owned by :mod:`pt_snap_cli.query.registry`, which
loads them recursively (one category per subdirectory) at import time.
``_configs`` only holds templates attached to this executor at runtime via
:meth:`load_config` or :meth:`register_template`; lookups consult those
first and then fall back to the registry.
"""

def __init__(self, context: Context):
"""Initialize query executor.

Args:
context: Database context for executing queries.
template_dir: Optional directory containing YAML template files.
"""
self._context = context
self._template_dir = Path(template_dir) if template_dir else None
self._configs: dict[str, QueryConfig] = {}
self._env = Environment(
undefined=StrictUndefined,
Expand All @@ -60,9 +60,6 @@ def __init__(
# identical template bodies on every query.
self._compiled_cache: dict[tuple[str, str], Template] = {}

if self._template_dir and self._template_dir.exists():
self._load_templates()

def _compiled_template(self, template: QueryTemplate, sql: str | None = None) -> Template:
"""Return the cached compiled Jinja template for ``sql``.

Expand Down Expand Up @@ -160,18 +157,6 @@ def _execution_error(self, error: sqlite3.OperationalError) -> QueryExecutionErr
)
return QueryExecutionError(f"Query execution failed: {error}")

def _load_templates(self) -> None:
"""Load all YAML templates from template directory."""
if not self._template_dir:
return

for yaml_file in self._template_dir.glob("*.yaml"):
try:
config = QueryConfig.load_yaml(yaml_file)
self._configs[yaml_file.stem] = config
except Exception as e:
warnings.warn(f"Failed to load query template from {yaml_file}: {e}", stacklevel=2)

def render(
self,
template: QueryTemplate,
Expand Down
26 changes: 26 additions & 0 deletions tests/query/test_executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -303,6 +303,32 @@ def test_list_templates(self):

assert "test_query" in executor.list_templates()

def test_packaged_templates_resolve_through_registry_only(self):
"""Regression for issue #121: the executor owns no template directory.

Packaged templates live in category subdirectories and are loaded by
the registry; a freshly constructed executor must find them through the
registry fallback while holding no configs of its own.
"""
from pt_snap_cli.query.registry import _load_all_templates

_load_all_templates()
executor = QueryExecutor(context=None)

assert executor._configs == {}
assert executor._find_template("leak_detection") is not None
assert "leak_detection" in executor.list_templates()

def test_runtime_registered_template_shadows_registry(self):
from pt_snap_cli.query.registry import _load_all_templates

_load_all_templates()
executor = QueryExecutor(context=None)
override = QueryTemplate(name="leak_detection", query="SELECT 'override'")
executor.register_template(override)

assert executor._find_template("leak_detection") is override

def test_execute_on_all_devices(self):
"""Test execute_on_all_devices runs template on each device."""
mock_context = _make_mock_context(device_ids=[0, 1])
Expand Down
Loading