Repository navigation
feat(query): reject undeclared parameters and bound SQL-fragment parameters with choices - #126
Merged
Merged
Conversation
This was referenced Sep 6, 2026
6 of 7 tasks
…meters with choices QueryTemplate.validate_params() passed any undeclared key straight into the Jinja2 render context, so a misspelled filter such as `min_sze` was silently ignored and the query returned unfiltered rows. Separately, `str` parameters were interpolated into SQL verbatim; `order_by` / `order_dir` in the allocation, block, event, and active_blocks_at_event templates therefore accepted arbitrary fragments (including subqueries) and surfaced invalid values as raw SQLite syntax errors. The database is opened read-only and sqlite3 executes one statement at a time, so this was a robustness and agent-safety gap rather than a write path, but the MCP `execute_query` tool exposes those parameters to prompt-driven callers. - QueryParameter gains an optional `choices` list. Values are checked after type conversion; `str` choices match case-insensitively and return the declared spelling. Defaults must be one of the choices, enforced at load. - validate_params() raises ValueError listing every unknown name and the accepted parameters instead of passing them through. - The four packaged templates with ORDER BY inputs declare `choices` drawn from their output columns and `[ASC, DESC]`. - `choices` flows through registry.get_template_info, TemplateParameter, QueryService, SnapshotAnalyzer/MCP, and the CLI `--template-info` line (`[choices: ...]`). - Tests cover the parameter rules, a registry invariant that packaged order_by/order_dir parameters declare choices within output_schema, CLI error output, and CLI/MCP contract parity for both error kinds. - User guides (en/zh) document parameter validation; query AGENTS.md files record the new template requirements. Fixes #120
codeasier
commented
Sep 18, 2026
codeasier
left a comment
Owner
Author
There was a problem hiding this comment.
交叉评审结果(3 位独立评审员 + 父会话逐条核验)
核心改动核验成立:未知参数拒绝是 fail-closed 的,且在 CLI/API/MCP 统一归一化为 TemplateRenderError;order_by/order_dir 的 choices 与各模板 output_schema 一致;executor 注入的上下文(device_id / 表名 / limit)在校验之后应用;所有第一方调用方(ReportService、skills、docs 示例、既有测试)均只传声明过的参数。
无 critical/high/medium 发现,以下 4 条均为 Low(打磨项,非阻塞),详见行内评论:
- 缺省值路径绕过
choices约束与规范化(query/config.py) - 非法
choices实际是警告后跳过,而非 PR 描述所称的 "fails at template load"(query/config.py+query/registry.py:316-323) - 契约测试新增的
[choices: ...]解析分支从未被实际覆盖(test_contract_cli_mcp.py) --template-info的 Example Usage 生成器可能输出非法示例(cli.py)
备注:_match_choice 以 None 兼作"未匹配"哨兵(纯理论问题);打包模板不变量测试只覆盖字面名 order_by/order_dir,比 AGENTS.md 规则略窄。
Default values with choices now use the declared spelling, --template-info examples pick a real choice, and the CLI/MCP contract uses allocation so the choices parser is actually compared.
codeasier
force-pushed
the
feat/issue-120-template-param-validation
branch
from
September 18, 2026 13:14
5c58ee5 to
2e41fbe
Compare
This was referenced Sep 18, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
📝 Description
Two gaps in template parameter validation (
src/pt_snap_cli/query/config.py):validate_params()copied any unknown key into the render context, so a misspelled filter ({"min_sze": 1024}) produced an unfiltered result set with no diagnostic.strparameters were interpolated into SQL verbatim.order_by/order_dirinallocation,block,event, andactive_blocks_at_eventaccepted arbitrary fragments — a subquery inorder_byexecuted successfully, and an invalidorder_dirsurfaced as a raw SQLitesyntax error.The database is opened
mode=roandsqlite3executes a single statement, so this was not a write path. It is a robustness and agent-safety fix: the MCPexecute_querytool exposes these parameters to prompt-driven callers, and "silently wrong results" is the worst failure mode for a diagnostic tool.Changes
QueryParameter.choices(optional list). Checked after type conversion;strchoices match case-insensitively and return the declared spelling (desc→DESC). A default that is not one of the choices, or an empty/non-listchoices, fails at template load.QueryTemplate.validate_params()raisesValueErrornaming every unknown parameter and the accepted set, e.g.Unknown parameter(s) for template 'leak_detection': min_sze (accepted: min_size, limit).QueryExecutor.render()already wraps this intoTemplateRenderError, so CLI/API/MCP semantics stay aligned.order_bychoices are each template's own output columns;order_diris[ASC, DESC].active_blocks_at_eventalready whitelisted inside Jinja (falling back tosizesilently) — it now reports invalid input instead of falling back.choicesis exposed end-to-end:registry.get_template_info→TemplateParameter→QueryService→SnapshotAnalyzer.get_template_info/ MCP → CLI--template-info(order_by: str (optional) [choices: id, allocated, active, reserved] [default: id]).docs/en/querying.mdanddocs/zh/querying.md;query/AGENTS.mdandquery/templates/AGENTS.mdrecord the new template rules.Before / after on a real fixture database
Compatibility
Callers that relied on unknown keys being ignored now get an error. I audited every
--paramsexample inskills/*/SKILL.md,docs/, andReportService; all pass only declared parameters.tests/test_cli.py::test_query_with_paramsalready tolerated either outcome (exit_code in [0, 1]) and is unchanged.🔗 Related Issue
Fixes #120
🧪 Testing
New tests (19):
QueryParameterchoices semantics and load-time checks,validate_paramsunknown-name rejection,from_dictreadingchoices, a registry invariant that every packagedorder_by/order_dirdeclareschoiceswithinoutput_schema, CLI error output and--template-inforendering, and two CLI/MCP contract tests asserting identical error text for unknown parameters and out-of-choices values. The contract test's CLI parser learned the[choices: ...]token socli_info == mcp_infostays an exact comparison.Full suite (macOS, Python 3.13.11):
788 passed, 1 xfailed.ruff check .andblack --check .clean.Per
AGENTS.mdchange routing for templates, the YAML,config.py,registry.py,executor.py(no change needed — it already normalizesValueErrortoTemplateRenderError),core/query_service.py, CLI/MCP presentation, and focused tests were reviewed together.✅ Checklist
Snapshot Runtime Provenance
Snapshot provenance decision: no-update
Snapshot provenance no-update reason: This PR changes the query subsystem, core models, CLI/API presentation, templates, docs, and tests; no files under src/pt_snap_cli/snapshot/ are touched.