diff --git a/.env.example b/.env.example index d951e5f..4fce65d 100644 --- a/.env.example +++ b/.env.example @@ -68,6 +68,8 @@ DATABASE_ALLOWLIST= # Comma-separated directories that may receive generated HTML reports. # Defaults to REPORT_OUTPUT_DIR. REPORT_ROOT_ALLOWLIST= +# Expired report access is denied. Cleanup quarantines files for recovery. +REPORT_RETENTION_DAYS=30 # Standard-library console + file logging LOG_LEVEL=INFO diff --git a/CHANGELOG.md b/CHANGELOG.md index b0d0d87..53ad8fa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,15 @@ and does not yet claim semantic-versioning stability. ### Added +- Multi-measure analysis, fact-grain aggregation, ratio components and event-time + comparison with explicit coverage, units and additivity contracts. +- Reconciled change diagnostics with independent totals, residuals and evidence. +- Full-result evaluation contracts, physical-source checks and repeated paired + experiments with immutable audit and resume tools. +- Keyword skill prefiltering and bounded content-version prompt caches. +- Local Studio publication state, editable measures and domain/version-bound + result replay; report expiry with recoverable quarantine. + - Mandatory, reviewable semantic layers for data-asset publication and queries. - Atomic data-and-semantic publication with rollback on contract failure. - Semantic scaffolding, incremental model building, drift baselines, and weekly audits. @@ -59,6 +68,15 @@ and does not yet claim semantic-versioning stability. ### Fixed +- Omitted measures and filters, incorrect comparison periods and unknown terminal + outcomes being delivered as successful answers. +- Inactive CTE aggregates and unrelated grains satisfying metric checks; incorrect + output labels, identifier transformations and weakened NULL predicates. +- Invalid or duplicate candidates consuming preview budgets and cancellation + allowing later SQL previews. +- Studio reporting unpublished sources as ready, accepting unsupported upload + formats and displaying stale results after a domain switch. + - Correct answers were scored wrong when the model returned extra columns or an equivalent shape; correctness is now decided by semantic result equivalence. - A reflection step that asked for clarification discarded the answer and the run's diff --git a/README.md b/README.md index c28c6a0..71b9254 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ policy enforcement, bounded recovery, and production-friendly delivery interface ![Python](https://img.shields.io/badge/Python-3.11%20%7C%203.12-3776AB?logo=python&logoColor=white) ![SQLite](https://img.shields.io/badge/SQLite-read--only-003B57?logo=sqlite&logoColor=white) ![SQLGlot](https://img.shields.io/badge/SQL%20policy-SQLGlot-6B4FBB) -![Tests](https://img.shields.io/badge/tests-928%20passing-2EA44F) +![Tests](https://img.shields.io/badge/tests-1080%20passed%2C%2025%20skipped-2EA44F) ![Offline acceptance](https://img.shields.io/badge/acceptance-13%2F13-7C3AED) @@ -31,34 +31,7 @@ semantic contract, and ask questions inside the same governance boundary. QueryForge combines that workflow with natural-language-to-SQL, AST-level security, read-only execution, bounded recovery, and complete run artifacts. -> QueryForge currently targets SQLite and controlled environments. It is a -> portfolio-grade reference architecture, not a multi-tenant analytics service. - -### Measured behaviour - -The governance layer is deterministic, so it is tested exhaustively offline; the -model layer is not, so its numbers are reported separately and with their sample -size. Both are reproducible from this repository. - -| What | Result | How | -| --- | --- | --- | -| Offline test suite | 928 passing, 25 skipped | `./init.sh` | -| Offline acceptance gate | 13/13 checks | `make check` | -| Deterministic agent benchmark | 23/23 tasks (`dev` + `regression` splits; the 9-task `holdout` split is requested explicitly) | `python scripts/benchmark_agent.py --tier 1 --gate` | -| Real-model NL2SQL accuracy | **0.875** semantic correctness, 1.0 execution success | 40 cases, single run, `deepseek-v4-flash` | - -Two honest qualifications on that last row, because they matter more than the -number: - -- It is **one run of 40 cases**. Differences of ±0.03 have been observed across - *identical* code, so this figure cannot resolve small changes. -- It covers the anime sample domain only. It is evidence that the pipeline works - end to end on a real model, not a general accuracy claim. - -Tier-1's 23/23 measures the *engineering* chain (governance, execution, evidence, -budgeting, failure classification), not model capability: a fixture supplies the -SQL. See [NL2SQL evaluation](docs/nl2sql_evaluation.md) for the method and the -frozen baselines. +> Studio serves local single-user workflows with read-only SQLite analysis by default. ## Product Tour @@ -99,34 +72,18 @@ delivery loop: | Integrate with other tools | Expose CLI, REST/SSE, MCP, gateway, JSON, charts, and HTML reports | | Start from raw data | Build governed SQLite assets from CSV, Parquet, and paginated JSON APIs | -## Highlights - -- **Defense in depth** — candidates are checked before execution and revalidated - at the database boundary. -- **Semantic contracts** — YAML models describe business metrics, entities, - relationships, cardinality, ownership, SLA, sensitivity, and quality rules. -- **Adaptive workflow** — simple questions stay fast; complex questions can - activate a bounded tool loop. -- **Read-only by default** — normal analysis opens SQLite databases in read-only - mode and rejects write or administrative SQL. -- **Multiple delivery surfaces** — use the same application service through the - CLI, REST/SSE, MCP, or a webhook gateway. -- **Reproducible evaluation** — the repository ships a 32-task deterministic agent - benchmark over three independent schemas and a 120-case, three-domain NL2SQL - gold set, with the frozen real-model baselines recorded in the docs. - ## Quick Start ### 1. Install -Requirements: **Python 3.11 or 3.12** and SQLite. +Requirements: **Python 3.11 or 3.12**; Studio uses **Node.js 22**. ```bash -python3.11 -m venv .venv +python3.12 -m venv .venv source .venv/bin/activate python -m pip install --upgrade pip python -m pip install -e . -cp .env.example .env +cp -n .env.example .env ``` ### 2. Configure a model @@ -135,9 +92,8 @@ Set one provider in `.env`. OpenAI-compatible, Claude, Gemini, Qwen, DeepSeek, and GLM configurations are included. ```dotenv -LLM_PROVIDER=openai -OPENAI_API_KEY=your-api-key -OPENAI_MODEL=gpt-4.1-mini +LLM_PROVIDER=deepseek +DEEPSEEK_API_KEY=your-api-key ``` Provider defaults and environment-variable mappings live in [`models.yml`](models.yml). @@ -164,15 +120,13 @@ queryforge \ ### Explore QueryForge Studio -The repository includes a complete visual workspace for creating and switching -data domains, onboarding domain-owned data, reviewing the required semantic -layer, asking governed questions, inspecting SQL and Trust Trace evidence, and -auditing domain-scoped run history. +Create a domain, upload CSV/Parquet, review semantics and publish. Then query, +inspect SQL and Trust Trace, or replay saved results bound to their data version. ```bash # Terminal 1: QueryForge API -python -m pip install -e ".[api]" -queryforge --serve-api +python -m pip install -e ".[api,assets]" +queryforge --serve-api --api-host 127.0.0.1 --api-port 8000 # Terminal 2: QueryForge Studio make web-install @@ -211,6 +165,7 @@ SQL candidate → dangerous-function checks → recursive CTE and cross-join checks → table, join, and LIMIT budgets + → measure, filter and active-output checks → governed preview → execution-boundary revalidation ``` @@ -250,28 +205,29 @@ metrics: sensitivity: internal ``` -Models can declare entities, dimensions, metrics, grain, relationships, join -paths, fan-out constraints, operational metadata, and physical quality rules. -QueryForge requires a validated model by default; it auto-discovers a model beside -the database and rejects schema-only analysis unless the caller explicitly selects -the diagnostic escape hatch. +Models define entities, dimensions, measures, grain, relationships and quality +rules. Queries require a validated model by default and auto-discover nearby YAML. +Independent facts aggregate before joining; ratios use declared components, and +each measure follows its event time, unit and reviewed coverage. Change diagnostics +return category contributions, independently reconciled totals and evidence. -In Studio, semantic construction is domain-first and gated: +Studio onboarding follows: ```text Create/select domain - → upload domain-owned sources - → profile physical schema - → confirm entity identity and grain - → define dimensions, measures, metrics, and time - → review relationships, cardinality, and Join Paths - → classify sensitivity, ownership, policy, and quality - → validate 100% of blocking checks - → publish data + semantics atomically + → upload CSV/Parquet + → review entity, grain, dimensions and measures + → confirm owner and sensitivity + → validate physical data and semantic contracts + → publish data + semantics ``` -Technical names are treated as evidence, not business truth. A new domain starts -empty and never inherits the Anime sample's entities or metrics. +New domains start with an empty contract. Studio edits single-entity dimensions +and measures; complete relationships, time and units are authored in YAML. +Queries require successful physical publication. Skill prefiltering and +content-version caches reduce unused context; repair and candidate previews have +explicit budgets. History preserves the original domain and data version, while +expired reports can be quarantined for recovery. Build or incrementally refresh one: @@ -424,7 +380,7 @@ queryforge/ evaluation/gold/ # Multi-domain NL2SQL evaluation cases evaluation/tasks/ # Deterministic agent-benchmark tasks (dev/regression/holdout) sample_data/ # Ready-to-run SQLite datasets and semantic models -web/ # QueryForge Studio and hosted persistence adapters +web/ # QueryForge Studio and local D1/R2 storage scripts/ # Build, benchmark, evaluation, and acceptance tools tests/ # Unit, integration, boundary, and acceptance tests docs/ # Architecture and feature documentation @@ -434,56 +390,17 @@ docs/ # Architecture and feature documentation Dependencies flow inward from interfaces and application code toward domain, infrastructure, and core contracts. -## Quality and Evaluation - -Run the complete offline quality gate: +## Development Checks ```bash -./init.sh # environment + 928-test suite + repository state -make check # repository hygiene + 13 offline acceptance checks +./init.sh # environment and offline tests +make check # repository hygiene and full acceptance +make semantic-check # semantic-model drift +make web-check # Studio lint, types, build and tests ``` -Live model evaluation reports execution success, semantic equivalence, policy -precision/recall, latency, measured token usage, and projection tolerance: - -```bash -python scripts/evaluate_sql.py \ - --cases evaluation/gold/nl2sql_multidomain.jsonl \ - --model-provider openai \ - --output .queryforge/evaluations/openai.json -``` - -CI runs the offline acceptance gate (including the deterministic agent benchmark) -on Python 3.11 and 3.12, plus an integration job that requires the optional -transport dependencies. Real-model evaluation is a manual workflow -(`.github/workflows/model-eval.yml`) because it spends money. - -## What is verified (and what is not) - -Every claim in this section is reproducible from the repository. The point of the -table is the third column: what has *not* been shown is stated as plainly as what has. - -| Capability | How you can check it | Status | -| --- | --- | --- | -| Full offline test suite | `./init.sh` — **928 tests, 25 skipped, 0 failures** | verified | -| Repository + integration gate | `make check` (`scripts/run_acceptance.py --full`, 13/13 checks) | verified | -| End-to-end demos (upload → publish → query; semantic catch; multi-step analysis; transports/refusal/recovery) | `make demo` — five narrated, asserting scripts under `docs/demo/`, offline and key-free | verified | -| Deterministic agent benchmark (32 gold tasks over 3 independent schemas, ablation, effect gate) | `python scripts/benchmark_agent.py --tier 1 --gate` | verified (23/23 — the `dev` + `regression` splits; the 9-task `holdout` split must be requested with `--split holdout`) | -| Optional-dependency integration tier | `python scripts/benchmark_agent.py --tier 2 --gate` — a missing dependency **fails** the tier | verified with `.[api,mcp]` installed | -| Real-model NL2SQL evaluation | `python scripts/evaluate_sql.py --cases evaluation/gold/nl2sql_multidomain.jsonl --model-provider

--model ` | **0.875 semantic correctness on 40 anime cases, one run, `deepseek-v4-flash`** — see the caveats above | -| Automatic skill selection is worth its cost | `--skill-mode auto` vs `--skill-mode off` | **not established** — it costs +139% p50 latency and +44% output tokens with no measured accuracy benefit | -| PostgreSQL backend | `pip install '.[postgres]'`, then `PostgresConnector` | **implemented, not verified** against a live server, and not exported from the package API | - -The demos and tier-1 are offline and deterministic: no model call, no network, no -API key. The agent benchmark's tier 1 supplies the SQL as a fixture, so its 23/23 -measures the engineering chain — **not model accuracy**. Real-model numbers must -come from a tier-3 run with credentials and are reported separately. - -Deployment level: **controlled environment, single tenant, read-only data access**. -SQLite is the default backend; DuckDB and PostgreSQL adapters exist behind optional -extras (see [Database adapters](docs/database_adapters.md)). The system is not -hardened for arbitrary untrusted multi-tenant input; the honest blank spots are -general-domain model accuracy and the PostgreSQL backend. +Evaluation separates deterministic governance checks from real-model behaviour. +See the [evaluation guide](docs/nl2sql_evaluation.md) for methods, results and limits. ## Documentation @@ -510,37 +427,20 @@ general-domain model accuracy and the PostgreSQL backend. - [Code of conduct](CODE_OF_CONDUCT.md) - [Changelog](CHANGELOG.md) -The source tree is ready for GitHub review and CI. The repository owner still needs -to select and add a `LICENSE` before public release; no license has been assumed on -their behalf. - -## Scope and Security - -QueryForge's guarantees apply to its configured SQLite execution boundary. The -project does **not** currently include: - -- production authentication, authorization, tenant isolation, or rate limiting; -- durable distributed workflow recovery or token-level cancellation; -- MySQL, warehouse, lakehouse, or streaming-system adapters (a PostgreSQL - connector exists but is neither exported from the package API nor verified - against a live server); -- provider-normalized billing or a trained-model lifecycle. +No open-source license has been declared. -Keep REST and MCP transports inside a controlled environment. Do not commit -provider secrets, generated run state, or local databases containing sensitive data. +## Deployment and Security -Network transports can be hardened without code changes: +Studio binds locally and enforces same-origin requests. Analysis permits read-only +SQL. REST/MCP serve controlled environments; local credentials belong in the +ignored `.env`. -- `QUERYFORGE_API_KEY` — when set, REST/Gateway endpoints (except `/health`) - require `Authorization: Bearer ` or `X-API-Key: `. -- `DATABASE_ALLOWLIST` / `REPORT_ROOT_ALLOWLIST` — comma-separated directories - that confine caller-supplied `database`/`semantic_model_path`/`sql_policy_path` - and report output paths. Without them, network transports fall back to the - project root plus the default database directory. +- `QUERYFORGE_API_KEY`: enable REST/Gateway request authentication. +- `DATABASE_ALLOWLIST` / `REPORT_ROOT_ALLOWLIST`: restrict data and report roots. +- `REPORT_RETENTION_DAYS`: set report access lifetime; the default is 30 days. -`POST /ask/stream` delivers progress events followed by one terminal -`final_result` event carrying the serialized answer (or an `error`); clients -that disconnect cancel the run cooperatively at the next node boundary. +SSE disconnects cancel cooperatively at execution boundaries. Domain history +preserves its original data version. See [configuration](docs/configuration.md). ## Roadmap diff --git a/README.zh-CN.md b/README.zh-CN.md index fd7b970..de4489d 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -14,7 +14,7 @@ ![Python](https://img.shields.io/badge/Python-3.11%20%7C%203.12-3776AB?logo=python&logoColor=white) ![SQLite](https://img.shields.io/badge/SQLite-只读执行-003B57?logo=sqlite&logoColor=white) ![SQLGlot](https://img.shields.io/badge/SQL%20治理-SQLGlot-6B4FBB) -![Tests](https://img.shields.io/badge/tests-928%20passing-2EA44F) +![Tests](https://img.shields.io/badge/tests-1080%20passed%2C%2025%20skipped-2EA44F) ![Offline acceptance](https://img.shields.io/badge/acceptance-13%2F13-7C3AED) @@ -28,30 +28,7 @@ QueryForge 是一个本地优先、以数据域为第一入口的 AI 数据分 示例域),再在该域内上传数据、评审语义契约和发起分析。项目把这套域级工作流与 NL2SQL、AST 级安全策略、只读执行、有界修复和完整运行产物串成闭环。 -> QueryForge 当前专注 SQLite 和受控环境,是面向作品展示与架构验证的参考项目, -> 不是可直接公网部署的多租户分析服务。 - -### 实测表现 - -治理层是确定性的,因此可以离线穷尽测试;模型层不是,所以它的数字单独汇报,并且必须 -同时给出样本量。以下两项都可从本仓库复现。 - -| 项目 | 结果 | 复现方式 | -| --- | --- | --- | -| 离线测试套件 | 928 通过,25 跳过 | `./init.sh` | -| 离线验收门禁 | 13/13 项 | `make check` | -| 确定性 Agent 基准 | 23/23 任务(`dev` + `regression` 分片;9 条 `holdout` 需显式请求) | `python scripts/benchmark_agent.py --tier 1 --gate` | -| 真实模型 NL2SQL 准确率 | **语义正确率 0.875**,执行成功率 1.0 | 40 个用例,单次运行,`deepseek-v4-flash` | - -最后一行有两点必须说清楚,它们比数字本身更重要: - -- 这是 **40 个用例的单次运行**。在**完全相同的代码**上曾观察到 ±0.03 的波动,因此这个 - 数字无法分辨小幅变化。 -- 它只覆盖 anime 示例域。它能证明整条链路在真实模型上跑得通,**不构成通用准确率承诺**。 - -Tier-1 的 23/23 衡量的是*工程链路*(治理、执行、证据、预算、失败分类),**不是**模型能力: -SQL 由测试夹具直接提供。方法与冻结基线见 -[NL2SQL 评测](docs/nl2sql_evaluation.md)。 +> Studio 面向本地单用户使用,默认以只读方式分析 SQLite 数据。 ## 产品界面 @@ -91,29 +68,18 @@ SQL 由测试夹具直接提供。方法与冻结基线见 | 如何接入其他应用 | 提供 CLI、REST/SSE、MCP、Gateway、图表和 HTML 报告 | | 原始数据如何进入分析 | 从 CSV、Parquet 和分页 JSON API 构建受治理 SQLite 数据资产 | -## 核心亮点 - -- **纵深防御**:SQL 在执行前接受治理,并在数据库执行边界再次校验。 -- **语义契约**:YAML 模型描述业务指标、实体、关系、基数、owner、SLA、 - 敏感级别和质量规则。 -- **自适应工作流**:简单问题保持轻量;复杂问题可启用有界 Tool Loop。 -- **默认只读**:普通分析以只读方式打开 SQLite,并拒绝写操作和管理类 SQL。 -- **统一多端交付**:同一应用服务可通过 CLI、REST/SSE、MCP 和 Webhook Gateway 使用。 -- **可复现评测**:仓库内置覆盖三套独立 Schema 的 32 条确定性 Agent 基准任务、覆盖三个 - 业务域的 120 条 NL2SQL 金标集,并在文档中记录冻结的真实模型基线。 - ## 快速开始 ### 1. 安装 -环境要求:**Python 3.11 或 3.12**、SQLite。 +环境要求:**Python 3.11 或 3.12**;Studio 使用 **Node.js 22**。 ```bash -python3.11 -m venv .venv +python3.12 -m venv .venv source .venv/bin/activate python -m pip install --upgrade pip python -m pip install -e . -cp .env.example .env +cp -n .env.example .env ``` ### 2. 配置模型 @@ -122,9 +88,8 @@ cp .env.example .env Qwen、DeepSeek 和 GLM 的配置。 ```dotenv -LLM_PROVIDER=qwen -QWEN_API_KEY=your-api-key -QWEN_MODEL=qwen-plus +LLM_PROVIDER=deepseek +DEEPSEEK_API_KEY=your-api-key ``` Provider 默认值和环境变量映射见 [`models.yml`](models.yml)。 @@ -151,14 +116,13 @@ queryforge \ ### 体验 QueryForge Studio -仓库现在包含一个完整的可视化工作台:可以创建和切换数据域、在域内接入数据、评审 -强制语义层、提出受治理的自然语言问题、检查 SQL 与 Trust Trace 证据,并审计域内 -历史运行。 +在工作台中创建数据域、上传 CSV/Parquet、审核语义并发布,然后查询、检查 SQL 和 +Trust Trace,或回放绑定原数据版本的留存结果。 ```bash # 终端 1:QueryForge API -python -m pip install -e ".[api]" -queryforge --serve-api +python -m pip install -e ".[api,assets]" +queryforge --serve-api --api-host 127.0.0.1 --api-port 8000 # 终端 2:QueryForge Studio make web-install @@ -195,6 +159,7 @@ SQL candidate → 危险函数检查 → 递归 CTE 与 Cross Join 检查 → 表、Join 和 LIMIT 预算 + → 指标、筛选与有效输出核验 → 受治理预览 → 执行边界二次校验 ``` @@ -233,26 +198,24 @@ metrics: sensitivity: internal ``` -模型可声明实体、维度、指标、粒度、关系、Join Path、fan-out 约束、运营元数据和 -物理质量规则。QueryForge 现在默认强制使用经过校验的语义模型,并自动发现数据库旁边 -的模型;除非显式启用诊断逃生口,否则不允许只依赖裸 Schema 查询。 +模型定义实体、维度、指标、粒度、关系和质量规则。查询默认要求经过校验的语义模型, +并自动发现数据库旁的 YAML。跨事实指标先独立聚合再连接,比例按分子分母重算, +各指标使用自己的事件时间、单位和覆盖边界。变化诊断提供分类贡献、独立总量对账和证据。 -Studio 中的语义层构建是「域优先 + 强门禁」流程: +Studio 的数据接入流程: ```text 创建/选择数据域 - → 上传该域数据 - → Profiling 物理结构 - → 确认实体身份和行粒度 - → 定义维度、度量、指标和时间口径 - → 评审关系、基数和 Join Path - → 标注敏感级别、Owner、策略和质量规则 - → 通过全部阻断性检查 - → 数据 + 语义原子发布 + → 上传 CSV/Parquet + → 审核实体、粒度、维度和指标 + → 确认 Owner 与敏感级别 + → 校验物理数据与语义合同 + → 发布数据 + 语义 ``` -技术字段名只作为推断证据,不能替代业务定义。新建域从空白契约开始,绝不会继承 -Anime 示例域的实体或指标。 +新域从空白契约开始。Studio 提供单实体维度/指标编辑,完整关系、时间和单位在 YAML +中编写;物理发布成功后才能查询。默认技能预筛选和内容版本缓存减少无效上下文,修复与 +候选预览受预算约束。历史回放保留原域和数据版本,报告过期后可隔离清理。 创建或增量更新语义层: @@ -400,7 +363,7 @@ queryforge/ evaluation/gold/ # 多业务域 NL2SQL 评测集 evaluation/tasks/ # 确定性 Agent 基准任务(dev/regression/holdout) sample_data/ # 可直接运行的 SQLite 数据集和语义模型 -web/ # QueryForge Studio 与托管持久化适配器 +web/ # QueryForge Studio 与本地 D1/R2 存储 scripts/ # 构建、基准、评测和验收工具 tests/ # 单元、集成、边界和验收测试 docs/ # 架构与功能文档 @@ -409,52 +372,17 @@ docs/ # 架构与功能文档 依赖从接口层和应用层向领域、基础设施与核心契约单向流动。 -## 质量与评测 - -执行完整离线质量门禁: +## 开发与检查 ```bash -./init.sh # 环境检查 + 928 个测试 + 仓库状态 -make check # 仓库卫生检查 + 13 项离线验收 +./init.sh # 环境与离线测试 +make check # 仓库检查与完整验收 +make semantic-check # 语义模型漂移 +make web-check # Studio lint、类型、构建与测试 ``` -在线模型评测覆盖执行成功率、语义等价率、策略 precision/recall、延迟、实测 token 用量和 -投影容忍度: - -```bash -python scripts/evaluate_sql.py \ - --cases evaluation/gold/nl2sql_multidomain.jsonl \ - --model-provider qwen \ - --output .queryforge/evaluations/qwen.json -``` - -CI 会在 Python 3.11 和 3.12 上执行离线验收(含确定性 Agent Benchmark),另有一个需要 -可选传输依赖的集成任务。真实模型评测是手动触发的 workflow -(`.github/workflows/model-eval.yml`),因为它会产生实际费用。 - -## 已验证的能力(以及未验证的部分) - -本节每条声明都能从仓库复现。这张表的价值在第三列:**没被验证的东西**和已验证的东西 -一样写清楚。 - -| 能力 | 怎么验证 | 状态 | -| --- | --- | --- | -| 完整离线测试套件 | `./init.sh` —— **928 个测试,25 skip,0 失败** | 已验证 | -| 仓库 + 集成门禁 | `make check`(`scripts/run_acceptance.py --full`,13/13 项通过) | 已验证 | -| 端到端 Demo(上传→发布→查询;语义校验抓错;多步分析;跨传输/拒绝/恢复) | `make demo` —— `docs/demo/` 下五个带断言的叙事脚本,离线且免 key | 已验证 | -| 确定性 Agent Benchmark(32 个金标任务、3 个独立 schema、消融、效果门禁) | `python scripts/benchmark_agent.py --tier 1 --gate` | 已验证(23/23 —— 即 `dev` + `regression` 分片;9 条 `holdout` 需用 `--split holdout` 显式请求) | -| 可选依赖集成层 | `python scripts/benchmark_agent.py --tier 2 --gate` —— 依赖缺失**判定失败**而非跳过 | 已装 `.[api,mcp]` 后通过 | -| 真实模型 NL2SQL 评测 | `python scripts/evaluate_sql.py --cases evaluation/gold/nl2sql_multidomain.jsonl --model-provider

--model ` | **40 个 anime 用例、单次运行、`deepseek-v4-flash` 下语义正确率 0.875** —— 限制见文首说明 | -| 自动技能选择是否值得其开销 | `--skill-mode auto` 对比 `--skill-mode off` | **未确立** —— 它带来 p50 延迟 +139%、输出 token +44%,而准确率收益未被测出 | -| PostgreSQL 后端 | `pip install '.[postgres]'` 后使用 `PostgresConnector` | **已实现、未验证**:未在真实服务器上验证,且未从包 API 导出 | - -Demo 与 tier 1 全部离线、确定性(无模型调用、无网络、无需 API key)。Agent Benchmark 的 -tier 1 由金标提供 SQL,所以 23/23 衡量的是**工程链路**(治理、执行、证据、预算、失败分类), -**不是模型准确率**。真实模型数字必须来自带凭证的 tier 3 运行,并单独报告。 - -部署等级:**受控环境、单租户、只读数据访问**。默认后端为 SQLite,另有可选的 DuckDB 与 -PostgreSQL 适配器(见 [数据库适配器](docs/database_adapters.md))。系统未针对任意不可信的 -多租户输入做加固;两处诚实的空白是通用领域的模型准确率与 PostgreSQL 后端。 +评测区分确定性治理测试和真实模型表现,方法、结果与限制见 +[评测文档](docs/nl2sql_evaluation.md)。 ## 项目文档 @@ -481,32 +409,19 @@ PostgreSQL 适配器(见 [数据库适配器](docs/database_adapters.md))。 - [行为准则](CODE_OF_CONDUCT.md) - [变更记录](CHANGELOG.md) -代码结构、CI 和协作模板已经具备 GitHub 发布条件。公开发布前仍需由仓库所有者选择并 -添加 `LICENSE`;本次整理没有擅自替你作出许可证法律选择。 - -## 范围与安全边界 - -QueryForge 的安全保证适用于其配置后的 SQLite 执行边界。项目目前**不包含**: - -- 生产级认证授权、多租户隔离和限流; -- 持久化分布式工作流恢复或 token 级取消; -- MySQL、数仓、湖仓和流处理系统适配器(PostgreSQL 连接器已存在,但既未从包 API 导出, - 也未在真实服务器上验证); -- 跨 Provider 统一计费,或训练模型的完整生命周期。 +仓库尚未声明开源许可证。 -请将 REST 和 MCP 接口部署在受控环境中,不要提交 Provider 密钥、运行状态, -以及包含敏感数据的本地数据库。 +## 部署与安全 -网络传输层无需改代码即可加固: +Studio 监听本地地址并限制同源请求;普通分析仅允许只读 SQL。REST/MCP 用于受控环境, +本地密钥放在被忽略的 `.env` 中。 -- `QUERYFORGE_API_KEY` — 设置后,REST/Gateway 端点(`/health` 除外)要求 - `Authorization: Bearer ` 或 `X-API-Key: `。 -- `DATABASE_ALLOWLIST` / `REPORT_ROOT_ALLOWLIST` — 逗号分隔的目录列表,用于约束 - 调用方传入的 `database` / `semantic_model_path` / `sql_policy_path` 以及报告输出 - 路径。未配置时,网络传输层回退为「项目根目录 + 默认数据库所在目录」。 +- `QUERYFORGE_API_KEY`:启用 REST/Gateway 请求认证。 +- `DATABASE_ALLOWLIST` / `REPORT_ROOT_ALLOWLIST`:限制数据和报告目录。 +- `REPORT_RETENTION_DAYS`:设置报告访问有效期,默认30天。 -`POST /ask/stream` 会先发送进度事件,最后以一个携带序列化答案(或 `error`)的 -终态 `final_result` 事件收尾;客户端断开连接后,运行会在下一个节点边界协作式取消。 +SSE 客户端断开后在执行边界协作式取消;域内历史快照绑定原数据版本。部署配置见 +[配置参考](docs/configuration.md)。 ## Roadmap diff --git a/docs/README.md b/docs/README.md index 96f554e..08b1157 100644 --- a/docs/README.md +++ b/docs/README.md @@ -19,6 +19,8 @@ Start with whatever matches what you are trying to do. - [Agent team architecture](agent_team_architecture.md) — entry routing, orchestration, workflow - [Database adapters](database_adapters.md) — SQLite default; DuckDB and PostgreSQL optional +- [Data Agent optimization roadmap](optimization_roadmap.md) — phased tasks, acceptance criteria and verification evidence +- [Four-stage optimization results](optimization_results.md) — delivered capabilities, measured changes and remaining acceptance ## Data diff --git a/docs/api_reference.md b/docs/api_reference.md index 09bd186..cd884ff 100644 --- a/docs/api_reference.md +++ b/docs/api_reference.md @@ -6,7 +6,7 @@ Start the optional REST server: queryforge --serve-api --api-host 127.0.0.1 --api-port 8000 ``` -All request bodies use the `AskRequest` contract. The common fields are `question`, +The NL2SQL request bodies use the `AskRequest` contract. The common fields are `question`, `database`, `semantic_model_path`, `sql_policy_path`, `skills`, session options, Tool Loop, parallel candidates, Subject Tree and report options. @@ -22,7 +22,11 @@ normal analytical clients should never set it. | `/ask` | POST | Execute the full governed NL2SQL workflow | | `/ask/stream` | POST | SSE progress events; no SQL, prompts, or result rows in events | | `/plan` | POST | Generate and preflight a plan without executing SQL | +| `/analyze` | POST | Execute a deterministic governed analysis plan (`AnalyzeRequest`) | +| `/analyze/runs/{run_id}` | GET | Inspect a durable analysis run | +| `/analyze/runs/{run_id}/cancel` | POST | Cancel a durable analysis run | | `/report/{run_id}` | GET | Download static HTML from the configured report directory | +| `/reports/expire` | POST | Preview expired reports; `dry_run: false` quarantines HTML/manifest pairs for recovery | | `/gateway/webhook` | POST | Gateway adapter with a stable user/channel session | Example: @@ -39,3 +43,79 @@ then retrieve it from `/report/`. Errors caused by invalid inputs return `400`; workflow, policy, or execution failures return `422`. SQL policy denials include a named `SQL_SECURITY_ERROR` and occur before SQLite execution. + +Reports expire by HTML file modification time (30 days by default). Expired or +unsafe report paths return `404`; symlinked HTML/manifests cannot be served or +overwritten. `POST /reports/expire` defaults to `{"dry_run":true}`. An explicit +`{"dry_run":false}` moves expired pairs into the configured report directory's +`.expired/_/` directory; it does not delete evidence. To recover, +copy the pair back, which starts a new retention period. This operation uses the +configured root only and shares the existing API authorization boundary. + +Loopback API requests with a foreign browser `Origin` or `Sec-Fetch-Site: +cross-site` are rejected before protected endpoints run. Local CLI requests +without an Origin remain supported; Studio uses its guarded same-origin proxy. + +Studio history stores an immutable result snapshot with the run id, domain and +data version. `GET /api/studio/runs?domain_id=...&run_id=...` replays saved results +without calling a model or querying the current data version. Cross-domain ids +return `404`, ids already assigned to another domain return `409`, and expired +or unretained snapshots return `410`. Snapshots are limited to 2 MiB and expire +after 30 days. They are submitted by the trusted local Studio client and are +not signed evidence for a multi-user deployment. + +`/analyze` (or CLI `--analyze`) aggregates each metric population independently, +then joins the aggregate results at a governed common grain. This supports different +facts and different default filters without joining raw fact rows. Scalar responses retain `answer.metric` / `answer.value` +and add `answer.metrics`, `answer.values` and `answer.columns`; grouped results carry all +requested metric columns in `answer.rows`. + +Explicit literal filters such as `where item_id = 1`, `for category = 'a'`, +`IN`, `BETWEEN`, `IS NULL`, and boolean combinations are bound to declared base-entity +columns and checked in the compiled SQL. Cross-fact filters must name a qualified +conformed dimension allowed by every metric, for example `where user.region = 'APAC'`. +Functions, subqueries, unknown columns and +unparseable filters return `needs_clarification`, before query execution. + +Daily, weekly (Monday start), monthly, quarterly and yearly comparisons use dated calendar buckets and +the requested baseline. `mom` / `qoq` identify monthly / quarterly grain; an ambiguous +baseline requires clarification. Missing baselines and a series reaching its query +limit cannot be substituted with another period and reported as success. A bounded +replan to a different dimension retains evidence but returns `blocked` for the +original request. The query automatically includes required baseline periods. +Multi-metric time analysis requires a shared time dimension, timezone and calendar; +each metric uses its own event-time field. `answer.comparisons` contains a comparison +for every metric in a trend response. +A dated comparison with governed category dimensions uses the diagnostic template: +independent period totals → per-category results → period comparison → reconciled +contribution → anomaly scan → evidence-backed answer. `answer.diagnosis` exposes +`comparison`, `contributions` and `anomalies` by metric, quality checks, +period completeness and evidence ids. Bucket keys are JSON arrays preserving NULL +and multiple dimension values. Time bucket columns have stable semantic reference +names such as `calendar.month`. + +Both current and baseline category sums must match independently queried totals; +a zero change residual alone cannot prove that joins preserved the population. +Non-additive metrics/dimensions and capped queries are refused. A missing category +period becomes zero only with enforced complete coverage. Opposing drivers remain +visible when total change is zero, with undefined percentage shares. Decomposition +is arithmetic attribution and carries no causal claim. A two-period query has +insufficient history for anomaly detection; it returns that state and an explicit +limitation instead of claiming no anomaly. + +`answer.metric_contracts` exposes units, additivity, event roles and population filters. +Declared ratios return numerator/denominator audit columns and `answer.ratio_components`; +ratios and distinct counts are recomputed at each grain and are never summed into +bucket totals. Missing fact groups and zero denominators produce an explicit incomplete +result instead of an invented zero. Actual join-key uniqueness and contracted event-date +validity are checked through DatabaseTool before the metric query. + +`answer.period_completeness` is `complete` only when all requested periods meet enforced +authored ingestion coverage bounds; otherwise it is `unverified`, with a limitation +for time analysis. Enforced contracts block clipped or missing periods and windows outside +coverage. UTC/fixed offsets and fiscal start months are supported; named DST zones require +a backend with those semantics and are rejected by the current SQLite contract. + +Clients must inspect the payload `status`: `/analyze` returns HTTP `400` for +`needs_clarification` / `blocked`, and can return HTTP `200` with `partial` for usable +intermediate evidence and an unmet analysis requirement. diff --git a/docs/configuration.md b/docs/configuration.md index 6b02cbb..06966a6 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -27,11 +27,30 @@ where a corresponding option exists. | `REPORT_MAX_ROWS` | `50` | Maximum rows embedded in report tables | | `REPORT_MAX_CHARTS` | `3` | Maximum rule-selected report charts | | `REPORT_OUTPUT_DIR` | `.queryforge/reports` | HTML and manifest destination | +| `REPORT_RETENTION_DAYS` | `30` | Report access expires after this many days; configuration bounded to 1–3650 | Conversation memory is opt-in per request: pass `session_id` or `new_session`. Tool Loop, parallel candidates and Subject Tree are disabled/minimal by default; structured reasoning is optional in model output and never blocks a compatible response. +## Local prompt-only skills + +`skill.yml` can declare `selection_keywords: ["quality", "null", "质量"]`. +Automatic selection keeps enabled defaults and offers optional skills only when +a keyword matches the question (case-insensitive substring). An empty list never +offers that optional skill; omitting the field preserves the legacy catalogue. +An explicit subject catalogue overrides this prefilter, and manual selection is +unchanged. With no eligible optional skill, routing uses defaults without a model +call while the reported mode remains `auto`. Keywords should cover the languages +and terms used by the deployment; this is a heuristic, not semantic relevance proof. + +Metadata parsing is cached by actual file bytes (at most 128 entries). Rendered +prompt context uses a 32-entry LRU keyed by directory, node, available metadata and +loaded instruction content. Changed content with unchanged mtime invalidates the +cache; deleted files fail closed. These caches contain prompt-only definitions, +not SQL results or user/domain data. Candidate count defaults remain unchanged; +invalid and duplicate candidates do not consume the bounded SQL preview budget. + ## MCP | Variable | Default | Purpose | diff --git a/docs/demo/run_demo_c.py b/docs/demo/run_demo_c.py index cff82cc..a2cb0dc 100644 --- a/docs/demo/run_demo_c.py +++ b/docs/demo/run_demo_c.py @@ -104,7 +104,7 @@ def main() -> int: f"delta={comparison.get('delta')}", ) check( - "ORDER BY dim_date.month_number" in str(metric_payload.get("sql") or ""), + "ORDER BY STRFTIME('%Y-%m'" in str(metric_payload.get("sql") or ""), "the time series is ordered chronologically, not alphabetically", str(metric_payload.get("sql"))[-70:], ) @@ -116,9 +116,9 @@ def main() -> int: oracle = { name: round(float(value), 6) for name, value in _sql( - "SELECT d.month_name, SUM(w.watch_seconds)/3600.0 FROM fact_watch_session w " + "SELECT printf('%04d-%02d', d.year, d.month_number), SUM(w.watch_seconds)/3600.0 FROM fact_watch_session w " "JOIN dim_date d ON d.date_key = w.watch_date_key " - "WHERE w.watch_date_key BETWEEN 20240101 AND 20241231 GROUP BY d.month_name" + "WHERE w.watch_date_key BETWEEN 20231201 AND 20241231 GROUP BY d.year, d.month_number" ) } check( diff --git a/docs/demo/run_demo_e.py b/docs/demo/run_demo_e.py index 83330c8..8424c39 100644 --- a/docs/demo/run_demo_e.py +++ b/docs/demo/run_demo_e.py @@ -22,6 +22,7 @@ from __future__ import annotations import sqlite3 +import json import sys import tempfile from dataclasses import replace @@ -94,7 +95,7 @@ def main() -> int: result = demo_analysis(scenario_root, paid_last=paid) contribution = result["contribution"] paid_row = next( - row for row in contribution["contributions"] if row["category"] == "paid" + row for row in contribution["contributions"] if json.loads(row["category"]) == ["paid"] ) check( contribution["total_delta"] == expected_delta diff --git a/docs/demo/scenarios_api_and_repair.py b/docs/demo/scenarios_api_and_repair.py index a380868..b2b85a3 100644 --- a/docs/demo/scenarios_api_and_repair.py +++ b/docs/demo/scenarios_api_and_repair.py @@ -1,14 +1,14 @@ """Scenario library for the API/repair/growth demos (step 17, Demo E). These scenarios drive the *real* HTTP handlers, the real workflow repair loop and a -reviewed analysis plan, all offline with a scripted model. `docs/demo/run_demo_e.py` +governed diagnostic template, all offline with a scripted model for repair. `docs/demo/run_demo_e.py` narrates and asserts them; this module holds the scenario code so the demo entry point stays readable. Originally `scripts/demo_data_agent.py`; folded into `docs/demo/` so step 17 has a single documented demo surface (the duplicate was flagged in review). -This uses scripted SQL generation and an explicitly reviewed analytical plan. +This uses scripted SQL generation for repair and deterministic governed diagnostics. It makes no claim about live-model accuracy or autonomous root-cause inference. """ from __future__ import annotations @@ -30,7 +30,6 @@ from queryforge.core.config import Config from queryforge.core.schemas.models import SqlTask from queryforge.domain.domains import DomainResolver -from queryforge.orchestration.planner import AnalysisPlan, PlanStep from queryforge.workflow.workflow_runner import WorkflowRunner from scripts.benchmark_runners import ScriptedModel # repo script, kept for the scripted model @@ -99,7 +98,7 @@ def generate_json(self,prompt): def demo_analysis(root: Path, *, paid_last: int = 20) -> dict: - """Three months, two channels. The reviewed plan recomputes all values from rows.""" + """Three months, two channels; independent totals reconcile the computed drivers.""" database=root/'growth.sqlite' with sqlite3.connect(database) as c: c.execute('CREATE TABLE users(id INTEGER PRIMARY KEY, month TEXT, channel TEXT)') @@ -107,31 +106,21 @@ def demo_analysis(root: Path, *, paid_last: int = 20) -> dict: for month,paid in [('2024-01',60),('2024-02',40),('2024-03',paid_last)]: for channel,n in [('paid',paid),('organic',40)]: start=len(rows) - rows.extend((start+i+1,month,channel) for i in range(n)) + rows.extend((start+i+1,month+'-01',channel) for i in range(n)) c.executemany('INSERT INTO users VALUES (?,?,?)',rows) semantic=dict(version=1,name='growth',entities=[dict(name='user',table='users',entity_type='fact',expected_columns=['id','month','channel'],primary_key=['id'],grain=['id'], dimensions=[dict(name='month',column='month'),dict(name='channel',column='channel')])], metrics=[dict(name='new_users',description='New users registered in each month',entity='user',aggregation='count',expression='COUNT(users.id)',synonyms=['new users'], - allowed_dimensions=['user.month','user.channel'])]) + allowed_dimensions=['user.month','user.channel'], time_field='users.month', + analysis={'unit':'users','additivity':'additive','time':{'role':'registration', + 'coverage_start':'2024-01-01','complete_through':'2024-03-31','require_complete_periods':True}})]) path=root/'growth.yml';path.write_text(yaml.safe_dump(semantic)) config=replace(config_at(root),database_path=str(database),semantic_model_path=str(path)) planner=AnalysisPlannerService(config_loader=lambda:config) clarification=planner.analyze('分析用户增长下降的原因') assert clarification['status']=='needs_clarification',clarification - def query(id,sql,deps): - return PlanStep(id=id,action='query_metric',inputs={'metric':'new_users','sql':sql},depends_on=deps,expected_evidence=['metric_value']) - steps=[PlanStep(id='resolve',action='resolve_metric',inputs={'term':'new_users'},expected_evidence=['metric_resolution']), - PlanStep(id='quality',action='check_data_quality',inputs={'table_name':'users','checks':['grain_unique','null_rate']},depends_on=['resolve'],expected_evidence=['data_quality'],validation={'block_on_error':True}), - query('trend',"SELECT month,COUNT(*) AS new_users FROM users GROUP BY month ORDER BY month",['quality']), - PlanStep(id='compare',action='compare_periods',depends_on=['trend'],expected_evidence=['period_comparison']), - query('channels',"SELECT channel,COUNT(*) AS new_users FROM users WHERE month='2024-03' GROUP BY channel ORDER BY channel",['compare']), - PlanStep(id='drill',action='drill_down',depends_on=['channels'],expected_evidence=['drill_down']), - query('pairs',"SELECT channel,SUM(CASE WHEN month='2024-02' THEN 1 ELSE 0 END) AS baseline,SUM(CASE WHEN month='2024-03' THEN 1 ELSE 0 END) AS current FROM users GROUP BY channel ORDER BY channel",['drill']), - PlanStep(id='contribution',action='calculate_contribution',depends_on=['pairs'],expected_evidence=['contribution']), - PlanStep(id='answer',action='compose_answer',depends_on=['contribution'],inputs={'require_evidence':['metric_resolution','data_quality','metric_value','period_comparison','drill_down','contribution']})] - plan=AnalysisPlan(question='new users',steps=steps) - payload=planner.analyze('new users',plan=plan,run_id='growth-demo') + payload=planner.analyze('Explain new users monthly for March 2024 month over month by channel',run_id='growth-demo') assert payload['status']=='succeeded',payload contribution=next(e['payload'] for e in payload['evidence'] if e['kind']=='contribution') - return dict(mode='reviewed_plan_real_sql_analysis',clarification=clarification, + return dict(mode='governed_diagnostic_independent_totals',clarification=clarification, expected_delta=paid_last-40,contribution=contribution,trace=payload) diff --git a/docs/nl2sql_evaluation.md b/docs/nl2sql_evaluation.md index 5ec2b0c..b22ddc7 100644 --- a/docs/nl2sql_evaluation.md +++ b/docs/nl2sql_evaluation.md @@ -32,7 +32,7 @@ single-database JSONL files. Case-level `database`, `semantic_model`, and Query cases include `id`, `domain`, `category`, `question`, `database`, `expected_sql`, and optional `semantic_model`, `sql_policy`, `follow_up_context`, -and `candidate_selection`. Rejection cases use: +and `candidate_selection`. Query cases can also declare `result_contract` (below). Rejection cases use: ```json { @@ -83,13 +83,18 @@ generated output). Result comparison is deterministic and declared: -- Row order is ignored (multiset comparison); duplicate rows are preserved — - the comparison never deduplicates with a set. -- Column order is tolerated when the column name sets match. -- NULL compares equal to NULL only. -- Integral floats compare equal to ints; non-integral floats are rounded to 10 - decimals (float-noise tolerance); non-finite floats compare as - `"Infinity"` / `"-Infinity"` / `"NaN"`. +- All reference projection columns are required by default. Matching one shared + column cannot excuse a missing measure. Auxiliary reference columns require + explicit `required_columns`; extra output columns require `allow_extra_columns`. +- Named columns align their cell positions. Unordered outer rows are multisets + preserving duplicates; explicit `row_order: ordered` or a reference `ORDER BY` + requires row order. Cells inside a row are never treated as a multiset. +- Empty output is allowed only by the task's empty policy. A failed, blocked or + partial run cannot receive a correct-result verdict even with matching values. +- NULL and booleans are distinct from numbers. Non-finite numbers fail. Finite + numbers use relative and absolute tolerance of 1e-9 in the NL2SQL comparator. +- Legacy equal-width projections with completely different aliases retain + positional matching only without an explicit contract. - `oracle_latency_ms` (time to execute the expected SQL) is recorded per case and reported alongside service latency (`average_service_latency_ms` / `average_oracle_latency_ms`). @@ -131,6 +136,8 @@ indicator of relative expense, never as an invoice. `evaluation/reports/` is gitignored, so raw evaluator output has no versioned carrier. The numbers below are the tracked record; each row names the report file it came from. +**The following live-model numbers are historical under the previous comparison policy.** +The phase-3 required-projection/order rules have not yet been evaluated with a real model. **A baseline is only current if its versions are unchanged** — change the model, the gold set, the semantic model, the SQL policy, or the comparison rules, and these become historical. @@ -179,3 +186,409 @@ python -m unittest -q tests.test_evaluate_sql Review SQL and category changes as data-contract changes. Do not alter expected SQL solely to make a model score higher; use semantic result equivalence to accommodate legitimate query rewrites. + +## Phase-3 task contracts and paired experiments (2026-10-11) + +Task-level `result_contract` is shared by the agent-task and NL2SQL evaluators: + +```json +{ + "required_columns": ["calendar.month", "sales_channel", "net_revenue"], + "allow_extra_columns": false, + "row_order": "ordered", + "empty": "forbid", + "columns_path": "answer.columns", + "rows_path": "answer.rows" +} +``` + +For NL2SQL query cases, omit the paths (defaults are `columns` / `rows`). +A task's `expected_values` supplies the rows and column names. Agent-task numeric +values keep their existing relative tolerance and exact-zero behavior. The new +`values_absolute_tolerance` adds a bounded, per-path absolute tolerance only when +explicitly declared: diagnostic reconciliation residuals use 1e-9 to absorb +floating-point summation noise; other existing task assertions are unchanged. + +`evaluation/diagnostics/` adds three planner tasks outside the existing frozen +32-task set. Independent base-table SQL in `scripts/freeze_diagnostic_tasks.py` +freezes both grouped values and separate period totals. Reproduce the three tasks: + +```bash +LOG_LEVEL=CRITICAL .venv/bin/python -B scripts/benchmark_agent.py --tier 1 \ + --tasks-dir evaluation/diagnostics --split dev --split regression --split holdout --gate \ + --report /tmp/queryforge_phase3_diagnostics.json +``` + +Dataset IDs, templates, questions and optional retrieval corpora are audited +before execution. Physical table/column/key/FK fingerprints enforce schema +isolation even if two dataset IDs point to copies of the same schema; each task +must match its dataset's `split_scope`. Dev uses anime, regression uses retail, +and holdout uses support. These small synthetic schemas establish test coverage, +not population generalization. + +The paired harness compares one mechanism at a time on identical tasks: + +```bash +# Offline control-flow QA; neither command calls a real model. +LOG_LEVEL=CRITICAL .venv/bin/python -B scripts/run_paired_benchmark.py --tier 1 \ + --feature candidates --repeat 5 --report /tmp/queryforge_phase3_paired_candidates.json +LOG_LEVEL=CRITICAL .venv/bin/python -B scripts/run_paired_benchmark.py --tier 1 \ + --feature skills --parallel-candidates 1 --repeat 5 --report /tmp/queryforge_phase3_paired_skills.json + +# Reviewable live-model manifest only; zero API calls. +LOG_LEVEL=CRITICAL .venv/bin/python -B scripts/run_paired_benchmark.py --tier 3 \ + --provider deepseek --model deepseek-v4-flash --feature candidates --repeat 5 \ + --dry-run --report /tmp/queryforge_phase3_live_candidates_manifest.json +``` + +Candidate experiments compare 1 vs 2 with skills held at auto; skill experiments +compare off vs auto with candidate count fixed. History and vector retrieval are +disabled, each execution uses fresh state, and A/B order alternates within each +task. The manifest records every task/repeat/order and all controls. Reports pin +source, public model/skill assets, database bytes, semantic/policy contracts, gold, +thresholds and runtime versions; a version change during execution invalidates +completion. The general benchmark also accepts `--parallel-candidates` and +`--skill-mode` for explicit controlled runs. + +The paired report keeps raw traces, deterministic task verdicts and failure +classes. A pair with an account/transport failure or a known provider signature +mismatch is excluded from both arms' accuracy denominator and listed separately; +such a run is incomplete and exits non-zero. Repeats remain inside their task +cluster for a seeded 2,000-sample percentile bootstrap. Reported means weight +tasks equally. Measured-token and measured/priced-cost pairs have their own +sample counts; unknown values remain null. A versioned `--prices` JSON is needed +for cost accounting. No price table was supplied in phase-3 offline checks. + +Offline evidence is frozen in the [optimization roadmap](optimization_roadmap.md). +Live experiments require explicit approval and a funded account under AGENTS.md; +remove `--dry-run` only after approval. Each current manifest selects 23 workflow +tasks across three schemas, five repeats and two arms: 230 case executions per +experiment. These are case executions, not an upper bound on provider calls or +spend; selection, repair and follow-up turns can call the provider again. The +provider/model and budget remain a human decision. No live-model gain is claimed. + +### Frozen phase-3 offline paired evidence + +The two offline commands above were run on 2026-10-11 against the original +32-task set (23 workflow tasks qualify for these experiments). Both reports +passed their offline execution gate and had no version changes during execution. + +| Experiment | Unique tasks / repeats | Evaluable pairs / total | Successful executions | Accuracy delta / task-cluster 95% interval | Measured token / cost delta | +| --- | --- | --- | --- | --- | --- | +| candidates 1→2, skills=auto | 23 / 5 | 115 / 115 | 230 / 230 | 0 / [0,0] | null / null | +| skills off→auto, candidates=1 | 23 / 5 | 115 / 115 | 230 / 230 | 0 / [0,0] | null / null | + +Both excluded-environment and excluded-provider-contract pair counts are zero. +These values validate the scripted pipeline only. ScriptedModel returns the +reference SQL; the zero-width interval cannot establish model equivalence or +mechanism effectiveness. No live-model token, cost or latency gain was measured. + +The reports' shared input/version fingerprints are frozen below. Runtime: +Python3.12.11, SQLite3.50.4, SQLGlot28.10.1, Pydantic2.13.4. The worktree is dirty +because the three-phase implementation is not committed; the source hash includes +new Python files, and the public model/skill assets have a separate digest. + +```json +{ + "source_sha256": "32a2b6244d8fa5b737d7fd6a476fb33c323cddc5c28a35d641ddadf320ebe937", + "assets_sha256": "06ad2b4d54be3939d1e6bed8641c72b18fcb7192d9e88d07967e5cc86801d2b3", + "datasets_sha256": { + "anime_streaming": "e5c53343b0d3cee46cbc02610353c60e2b909fd61c1e1fee16c222771e7ecfb8", + "retail_orders": "04a18a5d5bc8118eae21b88a4159c1857f3caf86d5b0eb527e41a395f855543f", + "support_tickets": "95829871b3525ed67256cfa7297c01c11d4ade01cacfe6a0436769b89e6065ad" + }, + "contracts_sha256": { + "anime_streaming": { + "semantic_model": "fa6d790e860c2481104fe2bab3a18f3d0809e1bcb20c6f09d9be339b782d1124", + "sql_policy": "a6817e5927206348ba833acc886ae8fdacd452f585ed1d489a3c86ecd1d00a01" + }, + "retail_orders": { + "semantic_model": "46238e583ffb49136286b0566a032eddfbf6981b4f51376a0c44a309d995b167", + "sql_policy": "70ca076acf9ef843cc71d60b2661689abe2f803e9afc75f8e47402d9e726b27a" + }, + "support_tickets": { + "semantic_model": "66ca8903dd1406214dbd17239be34c86d88d8996fd1d679d6da41714ba575c9c", + "sql_policy": "003e02d935e1d5f5059dabf0b3606b7444e7ab1cdbbbf0f7c1be0aa0cd5c625f" + } + }, + "gold_sha256": "ed76321afcaf6f5e5c45bb79f1af590e24b291b220b57602e90b7ffc558ef95b", + "threshold_sha256": "44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a", + "git_head": "d1e1e4f8ef95dfdf16bf7206ddcb797fa881eb4a", + "dirty": true +} +``` + +## Authorized DeepSeek live pairs, explicit tasks v1 (2026-10-11) + +The two authorized paid experiments are complete: each used 23 tasks across +three physically distinct schemas, five repeats and two arms (230 executions, +115 pairs). Candidate count compares 1→2 with skills=auto; skill selection +compares off→auto with candidate count=1. A/B order, questions, reference SQL, +databases, model parameters and code/assets/contracts stayed fixed within and +across these runs. Provider/model: `deepseek` / `deepseek-flash`, discovered as +DeepSeek-V4.1-Flash. The official [model documentation](https://api-docs.deepseek.com/quick_start/pricing/) +explains that the old v4 Flash name routes to V4.1. These results are not directly +comparable with the historical single-run 0.875 result above. + +The first six-execution preflight used the original control-flow questions and +was stopped after question/oracle disagreement: device/country lists did not +request reference count columns, and user totals allowed different meanings. +Those executions are excluded from both experiments. Preflight account-balance +observations are kept in private local records rather than published here. + +The separate [live-v1 corpus](../evaluation/live_tasks/README.md) explicitly +requests projections, labels and ordering while preserving original reference +SQL and databases. The original 32 tasks and thresholds are unchanged. Its +scripted preflight (`--tier 1 --repeat 2`, both features) passed 76/92 executions +per experiment. Four task families activated existing metric-gate/routing +failures; they remained in the live denominator. Scripted results describe +pipeline control flow, not model capability. + +### Original results and separately audited scores + +| Scoring / experiment | Baseline | Treatment | Delta | Task-cluster 95% interval | +| --- | ---: | ---: | ---: | --- | +| Frozen live-v1: candidates 1→2 | 79.1304% | 73.0435% | -6.0870 pp | [-13.9130, 0.0000] pp | +| Frozen live-v1: skills off→auto | 79.1304% | 76.5217% | -2.6087 pp | [-6.0870, 0.0000] pp | +| Additional source contract: candidates 1→2 | 77.3913% | 71.3043% | -6.0870 pp | [-13.9130, 0.0000] pp | +| Additional source contract: skills off→auto | 77.3913% | 73.9130% | -3.4783 pp | [-7.8261, 0.0000] pp | + +Each arm's denominator is 115 executions. Original passes: candidates 91→84, +skills 91→88. Source-audited passes: candidates 89→82, skills 89→85. All 460 original +verdicts were reproduced exactly; none was overwritten. The nine newly rejected +passes read only `dim_date` for earliest/latest receipt keys. Fixture calendar +and receipt extremes happen to match. Replaying all 354 originally passing SQL +queries through DatabaseTool reproduced both stored and reference rows 354/354; +database bytes and original SQL-policy hashes matched. Matching rows alone +therefore cannot prove source intent or full SQL semantics. + +A separate post-hoc sensitivity analysis removes one confirmed ambiguous +ranking question, `live_retail_orders_regression_4`. Its wording says “outlet”, +but `store_format=Outlet` is an actual subtype. Filtering those four stores is a +reasonable reading; the reference ranks all 24 stores. Neither arm passed this +task in either experiment. This question is a gold-design fault, not evidence +of a model failure. The primary results above retain it; no threshold was +relaxed and every original record remains available. + +| Source audit + ambiguity exclusion | Baseline | Treatment | Delta | Task-cluster 95% interval | +| --- | ---: | ---: | ---: | --- | +| Candidates 1→2 (89/110→82/110) | 80.9091% | 74.5455% | -6.3636 pp | [-13.6364, 0.0000] pp | +| Skills off→auto (89/110→85/110) | 80.9091% | 77.2727% | -3.6364 pp | [-8.1818, 0.0000] pp | + +This sensitivity analysis has 22 tasks×5 repeats=110 pairs per experiment. +Intervals use 2,000 seeded percentile bootstrap samples (seed 17), resampling +whole tasks and keeping repeats inside each task. Both intervals include zero; +these experiments establish no accuracy improvement from either mechanism. +The small curated fixtures do not establish population generalization. + +### Latency, reported tokens and priced response usage + +The following means use the same22-task sensitivity subset. Means give each +task equal weight. Differences are treatment minus baseline. Token totals include +provider-reported completion/reasoning tokens; estimated failed-call tokens +are not measurements. + +| Measurement | Eligible pairs | Baseline mean | Treatment mean | Delta | Task-cluster 95% interval | +| --- | ---: | ---: | ---: | ---: | --- | +| Candidate wall seconds | 110 | 21.916467 | 24.072792 | 2.156325 | [-1.558006, 5.212513] | +| Skill wall seconds | 110 | 12.704076 | 23.689620 | 10.985543 | [7.812725, 15.157997] | +| Candidate measured tokens | 110 | 18498.700000 | 31011.018182 | 12512.318182 | [10884.390909, 14244.090909] | +| Skill measured tokens | 109 | 15075.893182 | 18621.406818 | 3545.513636 | [2682.572727, 4446.863636] | +| Candidate priced CNY/execution | 110 | 0.021003696 | 0.025221900 | 0.004218205 | [0.000849219, 0.007312811] | +| Skill priced CNY/execution | 109 | 0.012204155 | 0.020640890 | 0.008436735 | [0.006202863, 0.010821593] | + +Candidates consumed 67.6389% more tokens and 20.0832% more priced CNY on this +subset, with no demonstrated quality gain; the wall-time delta interval spans +zero. Automatic skills consumed 23.5178% more measured tokens and 69.1300% more +priced CNY, and increased mean wall time 86.4726% (12.7041→23.6896 seconds). +Token/cost differences have positive intervals. These are measurements of this +configuration and shared provider-cache conditions, not a cold-cache tariff or +production-wide effect. The all23-task summaries remain in the audit JSON: +wall 21.6822→23.9587 seconds and tokens 18,225.1565→30,594.8783 for candidates; +wall 12.7801→23.4247 seconds and tokens 14,913.35→18,359.0761 for skills. +Full-corpus priced CNY means are 0.020759338→0.025081139 (115 pairs), and +0.012220516→0.020401366 (114 pairs), respectively. + +Numeric provider responses reconcile exactly: candidates 913 responses, +5,614,304 reported tokens; skills 647 responses,3,835,434 reported tokens. +One skill-treatment execution (`live_retail_orders_regression_6`, repeat 3) +timed out during reflection after four completed model calls. Its 35,164 reported +tokens reconcile against reported model spans; the fifth call has unknown usage. +The original evaluator marks the mixed trace as estimated and measured_tokens=0. +That failed outcome is retained, not retried or dropped from quality/latency. +Consequently skill token/cost summaries omit its pair (109 sensitivity pairs, +114 full-corpus pairs); the whole experiment's total cost remains null. Reported +responses can be priced independently, without pretending the failed call was +free. This exception also shows that zero environment-exclusion counts do not +mean no transport incident: the frozen classifier retained this timeout as +`runner_error`. + +The numeric observer paused after 175 executions. A guarded resume reused those +175 records verbatim and called the model only for the remaining 55. The original +incomplete report is preserved alongside the completed `*_resumed.json` report. +Offline resume QA reproduced 175/175 existing verdicts/records and every control +before continuing; a separate scripted CLI check retained 2 cases and ran only +2 pending cases (4/4 passed, zero provider responses). + +The standard USD cost field remains null. The frozen [CNY price table](../evaluation/deepseek_flash_cny_2026_10_11.json) +uses separately measured cached input, uncached input and output at CNY 0.02/1/4 +per million, from the [official price page](https://api-docs.deepseek.com/zh-cn/quick_start/pricing/) +checked on 2026-10-11. The Sunday off-peak window is pinned in UTC. Candidate +reported-response cost is CNY 5.27165492; skill reported-response subtotal is +CNY 3.79053536, excluding the unknown call. Their subtotal is CNY 9.06219028, +not a complete invoice. Private account balances are omitted from this public +record. No exchange-rate conversion was used. + +### Changes implemented after both paid runs + +`required_sql_tables` is an optional independent evaluator contract. SQLGlot +walks active physical sources through SELECTs, CTEs, scalar subqueries and unions; +unused CTEs and aliases do not satisfy it. Unsupported shapes/namespaces, +recursive CTEs, malformed constraints or missing SQL fail closed. A counterfactual +SQLite fixture extends the calendar without extending receipts and confirms +that the previous equal extrema were accidental. This checks necessary source +coverage, not joins, filters, active metric expressions or logical equivalence. +It changes the evaluation contract, not the production SQL execution boundary. + +[live-v2](../evaluation/live_tasks_v2/README.md) adds only source-scoring metadata; +model questions and reference results are identical to v1. Re-scoring is marked +post-hoc and preserves original verdicts. [live-v3](../evaluation/live_tasks_v3/README.md) +clarifies “all stores, regardless of store_format” for future runs. No new model +responses were generated against v3, and the auditor rejects using a changed +question to retroactively grade v1 outputs. + +The follow-up runner previously omitted the frozen today_provider: 20 candidate +follow-up turns reported 2026-10-11 despite the manifest's 2024-12-31 control. +The affected question counts all recorded receipts without a relative window; +its oracle is unaffected, but the date control was inaccurate. The runner now +passes the existing frozen-date factory, retry and vector controls through +AgentService. A real scripted two-turn regression verifies 2024-12-31 in every +turn. This fix happened after both experiments and does not rewrite their traces. + +There are 30 added regressions (13 SQL-source,16 source/audit/gold,1 follow-up), +including tampered verdict/usage rejection, unknown cost, question-change +rejection and report immutability. The 184-test focused suite passes. The source +checker, usage audit and DatabaseTool replay made zero new model calls. + +Several strict-contract failures require care: regional amount results in the +candidate experiment had correct cells but wrong requested column labels (10/10 +cases), which is delivery-contract failure, not numeric error. Generic customer +satisfaction and SLA language binds extra aggregation obligations, and independent +receipt/line counts encounter grain gates. Correct final rows can still fail a +whole-run tool-validity contract after earlier failed attempts. These scores are +end-to-end governance/delivery results, not pure model SQL-generation accuracy. +Prioritize precise request-to-metric binding and output-column contracts before +adding calls; use measured triggers for skills/candidates rather than enabling +more work for every task. Runtime changes for those issues remain future work. + +### Reproduction commands and frozen versions + +The [archived observers](../evaluation/observers/README.md) contain the exact +numeric observer and resume instrument used, with hashes in the execution +reports. Run from the repository root with fresh report prefixes. The following +are the paid protocol, not commands to run as part of offline verification: + +```bash +LOG_LEVEL=CRITICAL .venv/bin/python -B evaluation/observers/paired_usage_v1.py \ + --tier 3 --provider deepseek --model deepseek-flash --tasks-dir evaluation/live_tasks \ + --feature candidates --repeat 5 \ + --report evaluation/reports/phase3_deepseek_flash_candidates_live_v1.json +LOG_LEVEL=CRITICAL .venv/bin/python -B evaluation/observers/paired_usage_v1.py \ + --tier 3 --provider deepseek --model deepseek-flash --tasks-dir evaluation/live_tasks \ + --feature skills --parallel-candidates 1 --repeat 5 \ + --report evaluation/reports/phase3_deepseek_flash_skills_live_v1.json +LOG_LEVEL=CRITICAL .venv/bin/python -B evaluation/observers/paired_resume_v1.py \ + evaluation/reports/phase3_deepseek_flash_skills_live_v1.json \ + --tier 3 --provider deepseek --model deepseek-flash --tasks-dir evaluation/live_tasks \ + --feature skills --parallel-candidates 1 --repeat 5 \ + --report evaluation/reports/phase3_deepseek_flash_skills_live_v1_resumed.json +``` + +Actual execution used byte-identical instruments in `/private/tmp`; the archive +allows inspection. The paid runtime's Python/project source is also preserved +locally in the ignored `evaluation/reports/phase3_deepseek_flash_execution_source_v1.tar.gz`, +whose members reproduce the source fingerprint below (archive SHA +`bd8cb7e168143f649678dd1bd784c051e1057f1b99489cbeab3369a703dee373`). +Source/assets/data/contracts/gold were identical across the original and resumed +segments. Runtime: Python3.12.11, SQLite3.50.4, SQLGlot28.10.1, Pydantic2.13.4. +The dirty worktree reflects the uncommitted three-phase implementation. + +```json +{ + "source_sha256": "baa285d35e8813723e4ccff418b12d4f81f52aaf58f6c90558f2457a3f713001", + "assets_sha256": "06ad2b4d54be3939d1e6bed8641c72b18fcb7192d9e88d07967e5cc86801d2b3", + "datasets_sha256": { + "anime_streaming": "e5c53343b0d3cee46cbc02610353c60e2b909fd61c1e1fee16c222771e7ecfb8", + "retail_orders": "04a18a5d5bc8118eae21b88a4159c1857f3caf86d5b0eb527e41a395f855543f", + "support_tickets": "95829871b3525ed67256cfa7297c01c11d4ade01cacfe6a0436769b89e6065ad" + }, + "contracts_sha256": { + "anime_streaming": { + "semantic_model": "fa6d790e860c2481104fe2bab3a18f3d0809e1bcb20c6f09d9be339b782d1124", + "sql_policy": "a6817e5927206348ba833acc886ae8fdacd452f585ed1d489a3c86ecd1d00a01" + }, + "retail_orders": { + "semantic_model": "46238e583ffb49136286b0566a032eddfbf6981b4f51376a0c44a309d995b167", + "sql_policy": "70ca076acf9ef843cc71d60b2661689abe2f803e9afc75f8e47402d9e726b27a" + }, + "support_tickets": { + "semantic_model": "66ca8903dd1406214dbd17239be34c86d88d8996fd1d679d6da41714ba575c9c", + "sql_policy": "003e02d935e1d5f5059dabf0b3606b7444e7ab1cdbbbf0f7c1be0aa0cd5c625f" + } + }, + "gold_sha256": "03e024632732f1b5bc6186ce25c5b24ea51d1d773af8a3e69c8df6b6ca8b0778", + "threshold_sha256": "44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a", + "git_head": "d1e1e4f8ef95dfdf16bf7206ddcb797fa881eb4a", + "dirty": true +} +``` + +Offline audit commands, executed after development, use a fresh output path: + +```bash +.venv/bin/python -B scripts/freeze_live_tasks.py --check +.venv/bin/python -B scripts/freeze_live_tasks.py --source-contract --check +.venv/bin/python -B scripts/freeze_live_tasks.py --correct-questions --check +LOG_LEVEL=CRITICAL .venv/bin/python -B scripts/audit_paired_benchmark.py \ + evaluation/reports/phase3_deepseek_flash_candidates_live_v1.json \ + --reference-tasks-dir evaluation/live_tasks --tasks-dir evaluation/live_tasks_v2 \ + --usage evaluation/reports/phase3_deepseek_flash_candidates_live_v1.provider_usage.jsonl \ + --prices evaluation/deepseek_flash_cny_2026_10_11.json \ + --exclude-task live_retail_orders_regression_4 \ + --exclusion-reason 'The term outlet overlaps the concrete store_format=Outlet, while the frozen reference ranks all store formats.' \ + --report evaluation/reports/phase3_deepseek_flash_candidates_live_v1.source_v2.json +# Same auditor arguments for the skill report, using skills_live_v1_resumed in all three paths. +LOG_LEVEL=CRITICAL .venv/bin/python -B evaluation/observers/engine_replay_v1.py \ + evaluation/reports/phase3_deepseek_flash_candidates_live_v1.json \ + --report evaluation/reports/phase3_deepseek_flash_candidates_live_v1.engine_audit_checked.json +# Same replay for skills_live_v1_resumed: 179/179 passing queries matched. +``` + +Both source audits recomputed 230 cases, with zero verdict/reported-token mismatches. +Scoring is versioned separately from the preserved execution provenance: + +```json +{ + "script_sha256": "22502440c9473e8c0f1ef36dfbb52da8786b1d0fab4f6d822a2fa7cd4407208d", + "evaluator_sha256": "a6c68efb33b0be5dd0cc2a319eedef829aa7d8c70ffa1a394c519e01b091835a", + "gold_sha256": "fec4d0b0713cac8d74178874bdf3b559bb92ba4a710fcf0660af6448730de5b0", + "price_sha256": "4791edfc2b167cad3ad7bf305c17dc8050b59da727394a895225c7a9224e26d0", + "versions": { + "python": "3.12.11", + "sqlite": "3.50.4", + "sqlglot": "28.10.1", + "pydantic": "2.13.4" + } +} +``` + +Full original/raw and supplementary JSON files are gitignored. The numbers, +commands and versions in this tracked section are the durable evaluation record. + +Final post-development verification (2026-10-11): `./init.sh` exited 0 with +1,078 tests in 95.934 seconds, 25 skipped and zero failures. `make check` exited 0: +repository checks and 13/13 offline acceptance checks passed, including 1,078 tests +in 98.705 seconds (25 skipped, zero failures). The fresh three-split tier-1 gate +passed 32/32; the fresh diagnostic gate passed 3/3. Both use ScriptedModel and +unchanged thresholds. `git diff --check` passed. Exact commands and logs are +recorded in the [roadmap's final verification](optimization_roadmap.md#补充开发最终验收). diff --git a/docs/optimization_results.md b/docs/optimization_results.md new file mode 100644 index 0000000..164da94 --- /dev/null +++ b/docs/optimization_results.md @@ -0,0 +1,66 @@ +# 四阶段优化成果汇总 + +本轮优化围绕回答正确性、业务语义、诊断与评测、效率与本地产品化推进。 +README 介绍当前产品,阶段实现、实验和验收细节保存在本文及 +[完整优化记录](optimization_roadmap.md)。 + +## 优化了什么 + +| 阶段 | 主要变化 | 已核验的效果 | +| --- | --- | --- | +| 1:回答正确性 | 保留多个指标和明确筛选;按指定日历期间比较;核验完整交付;未知终态失败关闭 | 两个请求指标同时交付;遗漏筛选返回60的用例正确返回10;同比按去年同月得到200%;替代维度不能冒充完成原请求 | +| 2:业务语义 | 各事实独立聚合再连接;比例按分子分母重算;指标绑定自己的时间、单位与覆盖合同 | 跨事实 a/b 分组金额分别40/20、费用12/3;总体比例140/3≈46.6667,不误算成60;零分母、重复键和缺失期间明确拒绝或部分交付 | +| 3:诊断与评测 | 分类期间变化分解与独立总量对账;严格输出/排序/空结果合同;三 schema 留出;重复配对、来源审计与断点恢复 | 原全分片门禁32/32、新诊断3/3;补充来源检查拒绝9次只查日历表的误通过;354条已通过SQL经DatabaseTool重放,数值匹配且数据库字节不变 | +| 4:效率与本地产品化 | 最终有效输出血缘和请求绑定;技能预筛选与版本缓存;候选预算/取消;真实发布状态;域/版本快照与产物生命周期 | 同一23题离线合同全通过,调用72→51;24项真实本地HTTP/SQLite闭环通过;浏览器查询返回3,历史回放模型调用24→24 | + +SQL 执行仍只经过 DatabaseTool;AST、业务语义、证据和终态由确定性代码裁定, +分析数据库默认只读。Studio 的部署范围为本地单用户。 + +## 提升了多少 + +| 指标 | 优化前 | 优化后 | 变化及解释 | +| --- | ---: | ---: | --- | +| Python 测试数量 | 928 | 1105 | 新增177项,+19.07%;覆盖增加不等于模型准确率提高 | +| Python 通过数量 | 903,另25跳过 | 1080,另25跳过 | 新增177项通过,0失败;四阶段分别新增31/49/70/27项 | +| Studio 行为测试 | 24 | 31 | 新增7项,+29.17%;lint、类型和生产构建通过 | +| 同一23题的离线模型调用 | 72 | 51 | 少21次,−29.17%;包含多轮任务,均为ScriptedModel | +| 同一23题的本地估算token | 299851 | 276994 | 少22857,−7.62%;没有真实模型实测token或账单提升结论 | +| 同一23题的任务合同 | 23/23 | 23/23 | 工程控制流未退化;夹具提供参考SQL,不衡量模型能力 | + +这些离线观察使用相同任务、数据、合同、金标和阈值。候选数均为1(前版本为离线 +默认,后版本显式固定),技能自动模式;版本同时含后续正确性修复,不能当作单因素 +随机消融。原始控制、指纹和数字见 +[冻结记录](../evaluation/phase4_local_acceptance_2026_10_11.json)。 + +## 真实 DeepSeek 结果 + +两组已授权实验共460次执行,每组23题×5次重复×2个实验条件。补充来源核验,并将 +一条歧义题作为独立敏感性分析剔除后,每个条件有22题×5次重复: + +| 实验 | 基线 | 实验条件 | 变化 | +| --- | ---: | ---: | --- | +| 候选数1→2,技能auto | 89/110,80.91% | 82/110,74.55% | −6.36个百分点,任务聚类95%区间[−13.64,0] | +| 技能off→auto,候选1 | 89/110,80.91% | 85/110,77.27% | −3.64个百分点,任务聚类95%区间[−8.18,0] | + +两种机制均未证明质量提升。候选组实测token增加67.64%;技能组增加23.52% +(完整用量109对,超时调用用量未知的1对单独报告)。因此保留单候选默认,并收紧 +技能路由。该评测衡量完整交付合同,不能称为纯SQL生成准确率。 + +没有在相同控制下测量“四阶段之前→当前代码”的真实模型准确率,所以不能给出 +总体准确率提高多少的百分比。历史40题单次0.875结果也不能与上述重复配对直接比较。 +完整分母、原始/后验口径、费用与限制见[真实评测记录](nl2sql_evaluation.md#authorized-deepseek-live-pairs-explicit-tasks-v1-2026-10-11)。 + +## 当前验收与剩余项 + +- `./init.sh`:1105项,1080通过、25跳过、0失败。 +- `make check`:仓库检查及13/13离线验收通过。 +- `make semantic-check`:86/86通过,no_change。 +- `make web-check`:lint、类型、生产构建和31/31测试通过。 +- 三组离线任务:原门禁32/32、诊断3/3、v3任务23/23,阈值未放宽。 +- `scripts/check_local_studio.py`:24/24真实本地HTTP/SQLite闭环,0真实模型调用。 + +HTTP闭环包含CSV/Parquet发布、count=3、sum=60、非法/未审核/未发布数据拒绝、 +DELETE拒绝、域/路径隔离、外来Origin拒绝、SSE连续事件与断开取消、快照回放、 +报告过期与可恢复隔离。浏览器查询和回放已验证;原生文件选择器“打开”禁用, +完整浏览器上传点击流程仍待复验。当前预筛选版本的真实DeepSeek质量、延迟及实测 +费用未重测,需要另行授权的付费评测。复现命令见完整优化记录和[Studio指南](studio.md)。 diff --git a/docs/optimization_roadmap.md b/docs/optimization_roadmap.md new file mode 100644 index 0000000..9adc37d --- /dev/null +++ b/docs/optimization_roadmap.md @@ -0,0 +1,416 @@ +# Data Agent 优化任务与验证记录 + +审查基线:`d1e1e4f`。本计划沿用 DatabaseTool、PlanValidator、SQLPolicyEngine、 +EvidenceStore 和运行日志,不引入第二条 SQL 执行路径。 + +| 阶段 | 任务 | 完成条件 | 状态 | +| --- | --- | --- | --- | +| 1:回答正确性 | 多指标不遗漏;明确过滤进入查询;同比/环比使用指定期间;未知终态失败关闭;请求与结果交付核验 | 原审查案例有回归测试;不支持的组合明确澄清;CLI/REST、证据、预算和恢复回归通过;`./init.sh` 与 `make check` 通过 | 已完成(2026-10-09) | +| 2:分析语义 | 跨事实指标按粒度聚合;比例分子分母;时间角色、单位、可加性;期间覆盖与完整性 | 多粒度、缺失期间、零分母和跨事实独立数据 oracle 验证;语义漂移门禁通过 | 已完成(2026-10-10) | +| 3:业务诊断与评测 | 完成变化→分解→质量核验→证据交付;任务级必需列和排序验收;独立 schema 留出;重复配对实验 | 真实业务诊断离线验收;评测不容忍必需指标遗漏;模型实验报告样本量、区间与失败分母 | 开发、真实 DeepSeek 配对评测与离线审计完成(2026-10-11);结果和最终验收见下文 | +| 4:效率与本地产品化 | 请求与指标绑定;技能预筛选、有界候选与内容版本缓存;拆分请求/血缘/产物职责;真实 Studio 行为与产物生命周期 | 同输入离线合同及调用量对比;上传→发布→查询→拒绝→取消→回放;本地来源、域/版本隔离和过期控制 | 核心开发与自动验收完成(2026-10-11);仅本地单用户,浏览器上传完整点击验收待复验,真实模型效率未重测 | + +## 第一阶段范围 + +- 支持相同实体、默认过滤和时间口径的多指标汇总与分类结果;不同口径的组合 + 明确要求澄清,不选取首个指标冒充完成。 +- 支持基表列与字面量构成的明确过滤(比较、AND/OR、IN、BETWEEN、NULL); + 不接受子查询、函数、注释、多语句或无法解析的自然语言过滤。 +- 明确同比/环比按日历期间匹配;缺少指定基准时报告部分结果,不替换成其他期间。 +- 在现有查询和回答节点核对请求指标、过滤、维度、时间窗口与比较要求;显式失败的状态不会 + 被包装成成功。 +- 跨事实多指标、任意自然语言过滤、复杂归因与完整期间策略留给后续阶段。 + +## 分阶段任务清单 + +| 编号 | 优化任务与交付物 | 验收方式 | +| --- | --- | --- | +| 1.1 | 请求解析保留多个指标;编译同口径聚合;交付所有指标列及证据 | 汇总、分类、缺失列与不兼容口径的独立数据用例 | +| 1.2 | 字面量过滤绑定语义列;核验 SQL 中的必需谓词;隔离引号里的时间/分组词 | 正常过滤、空切片、未知列、子查询、注释、过滤被遗漏或 OR 放宽的用例 | +| 1.3 | 日期/日期键按日、月、季、年聚合;日历基准精确配对 | 同月同比、月内多日聚合、跨年环比、缺失期间与结果上限用例 | +| 1.4 | 未知终态失败关闭;交付约束进入日志指纹;替代维度不能完成原请求 | 终态测试、调用方自定义计划、原样恢复、CLI/REST、全量离线回归 | +| 2.1 | 跨事实多指标先按目标粒度聚合,再连接;定义合法维度与可加性 | 多事实、多对多和比例指标 oracle;拒绝 fan-out 与错误分母 | +| 2.2 | 显式时间角色、单位、时区和期间完整性;比较查询自动纳入所需基准窗口 | 跨时间角色、缺失/不完整期间、闰日、周和财务日历用例 | +| 2.3 | 将上述口径写入语义合同、作者校验和漂移检查 | 合同兼容性测试、样例模型迁移与 `make semantic-check` | +| 3.1 | 变化诊断串联期间比较、贡献分解、异常与质量解释;逐项输出证据和限制 | 真实业务形状的离线案例,分解合计和残差可复核 | +| 3.2 | 评测明确必需输出列、排序、空结果和任务完成要求;修复只比共同列的问题 | 故意删除一个指标、乱序或改口径时,评测必须失败 | +| 3.3 | 多 schema 留出;固定候选数、技能配置与输入;重复配对实验 | 追踪数据集/代码/配置版本,报告样本量、区间、环境错误及付费支出 | +| 4.0 | 根据真实失败样本收紧请求→指标绑定、有效表达式与输出列合同 | 缺失CSAT计数、SLA编号列表、独立订单/明细计数和未使用聚合CTE的基表oracle、CLI/REST与错误注入 | +| 4.1 | 技能关键词预筛选、内容版本缓存与候选预览预算修复;保留单候选默认与原有修复流程 | 固定任务合同、调用量与估算 token;元数据/正文改变、预算及取消回归;真实模型质量/效率另行授权 | +| 4.2 | 拆分请求合同、输出血缘、CSV 检查、快照与报告存储职责;修复 Studio 的真实状态与交互 | HTTP 上传/发布/查询/拒绝/取消/回放;浏览器查询/回放;原生上传点击验收待复验 | +| 4.3 | 按用户确认仅支持本地单用户:loopback/同源边界、域与数据版本绑定、产物过期、可见失败 | 外来 Origin、路径覆盖、跨域回放拒绝;快照过期与报告可恢复隔离;不新增多用户登录系统 | + +阶段按 1 → 2 → 3 → 4 推进。每阶段关闭对应回归与验收后再进入下一阶段; +付费模型实验和部署架构分别按 AGENTS.md 的授权与评审要求执行。 + +## 第一阶段行为变化 + +数据 fixture:3 条记录,金额分别为 10、20、30;类别为 a、b、a。 +时间比较 fixture:2024-02-01=10,2025-01-01=20,2025-02-01=30。 + +| 原问题 | 审查时的行为 | 第一阶段结果 | +| --- | --- | --- | +| item count 和 total amount,按 category | 仅执行第一个指标,仍成功 | a=(count 2, amount 40),b=(count 1, amount 20),全部列带证据 | +| total amount where item_id = 1 | 丢弃过滤,返回 60 | 编译并核验 `items.item_id = 1`,返回 10 | +| for category a / with supplier_code 'x' | 未解析的筛选可能变成分组或全量结果 | 执行前要求明确字面量比较,`needs_clarification` | +| monthly trend year over year | 以 2025-01 的 20 为基准,得到 50% | 以 2024-02 的 10 为基准,对 2025-02 的 30 得到 200% | +| 未知或缺失结果状态 | 默认成功 | `failed`;`unsupported` / `unverified` 归为 `blocked` | +| 按品牌无数据后改按类别 | 替代查询成功后,整个原请求成功 | 替代证据保留,原请求因维度未满足而 `blocked` | + +兼容性说明:月度比较标签改为 `YYYY-MM`,避免跨年月份合并。现有单指标字段保留, +多指标添加 `metrics`、`values`、`columns`。查询达到结果上限时保守拒绝“最新期间” +结论;自动扩展比较窗口与期间完整性策略在阶段 2 实现。本阶段只扩展 SQLite 的 +确定性分析路径,不据此声称真实模型准确率提升。 + +## 验证证据 + +2026-10-09,基于 `d1e1e4f` 的第一阶段工作区变更。环境:Python 3.12.11、 +SQLite 3.50.4、SQLGlot 28.10.1、Pydantic 2.13.4。 + +| 检查 | 命令 | 实际结果 | +| --- | --- | --- | +| 开发前基线 | `./init.sh` | 928 项,903 通过,25 skip,0 失败 | +| 新增专项回归 | `LOG_LEVEL=CRITICAL .venv/bin/python -B -m unittest tests.test_analysis_intent_regressions -q` | 30/30 通过;包含实际 SQLite、CLI、REST、自定义计划和恢复执行 | +| 开发后全量验证 | `./init.sh` | 959 项,934 通过,25 skip,0 失败,退出码 0 | +| 仓库与完整离线验收 | `make check` | 仓库检查通过;13/13 验收通过;内含的全量测试同样为 959 项、25 skip、0 失败;退出码 0 | +| 语义漂移检查 | `make semantic-check` | 82/82 通过,0 blocking failures,`no_change` | +| 差异格式 | `git diff --check` | 退出码 0 | + +新增测试总计 31 项(30 项请求正确性回归、1 项不可验证终态回归)。 +测试以 fixture 的独立期望值和样例库的独立 SQL 结果核对数值,未调用真实模型, +未进行付费 tier-3 评测。上述测试计数已同步到版本控制内的 README;评测器严格列 +校验、多 schema 泛化及真实模型效果仍按阶段 3 验收。 + +## 第二阶段交付(2026-10-10) + +第二阶段在第一阶段工作区上增量开发,沿用原执行、预算、证据和恢复机制。 + +| 任务 | 实现与闭环 | +| --- | --- | +| 2.1 跨事实与比例 | 每个指标在自己的事实表、过滤和时间口径上独立聚合,再通过去重键域连接;连接键实际唯一性和其他事实粒度经 DatabaseTool 核验。比例显式声明 SUM/COUNT 分子分母,按每个目标粒度重算,输出审计列;AST 同时核验分母、缩放和数值除法,AVG 等价需证明相同 NULL 口径。零分母、缺失事实组和不可相加的总计拒绝交付成功。 | +| 2.2 时间与覆盖 | 声明单位、可加性、事件角色、UTC/固定时差和财务起始月;周一为周起点;基准窗口自动纳入查询;每个请求指标单独比较。完整性按已审核的入库覆盖边界执行,拒绝不完整/缺失期间、缺失当前期间、窗口截断和非法日期。无覆盖契约时明确标记未验证。 | +| 2.3 契约与漂移 | 向后兼容的可选分析契约;比例组件 AST 与物理列校验;发布与运行时校验日期;四个样例指标迁移。漂移检查先发现四个预期指标变更且 86 项合同全部通过,审查变更后更新基线,再验证 no_change。恢复指纹纳入模型内容和实际解析日期,口径或相对窗口改变后重算。 | + +独立 fixture:items 金额为 10、20、30,charges 金额为 5、7、3。 +两个事实都按品牌 a/b 连接,但不连接事实明细。 + +| 场景 | 实测结果 | +| --- | --- | +| 跨事实按品牌查询 | a=(item amount 40, charges 12),b=(20, 3),无明细 fan-out | +| 不同默认过滤 | count=3;amount 在 amount>10 的独立口径下=50,保留各自口径元数据 | +| 比例的不同粒度 | 金额 10、100、30;a=(分子40/分母2)=20,b=100;总体=140/3≈46.6667,避免简单平均成60 | +| 2025-02 明确同比 | 自动补入 2024-02;amount 30 对 10,变化 200%;多指标分别提供比较 | +| 周粒度跨年 | 2024-12-23=10,2024-12-30=50(含 2025-01-01),按周一起点归属 | +| 零分母、重复连接键、多对多、缺失期间、2月30日 | 显式部分/不支持/阻断,均不能成功交付 | +| 财务年度4月起始 | 季/年标签为实际期间起始日期;月末不溢出到错误期间 | +| 同版本口径变更后的恢复 | 比例 scale 从1改为100、单位变为 cents/item 后,20 重算为2000;不复用旧结果 | +| 相同自然语言相对窗口后的恢复 | 解析窗口从2025-01变成2025-02后,20重算为30;不复用旧结果 | + +样例库独立 SQL 核验(完整覆盖 2023-01-01 至 2025-12-31): + +| 指标 | 2024-02 基准 | 2025-02 当前 | 变化 | +| --- | ---: | ---: | ---: | +| watch_hours(小时) | 1115.8683333333333 | 1117.3080555555555 | +1.4397222222221444 | +| average_rating(1–10分) | 7.38747680890538 | 7.261959957850369 | −0.12551685105501154 | + +上述数值来自 `tests.test_analysis_semantics.test_bundled_cross_fact_comparison_matches_independent_sql` +中的两条独立只读 SQL,按各自事件日期键的年月分组;不复用编译器表达式或执行输出计算 oracle。 +当前实现保持 SQLite 确定性分析范围。命名 DST 时区、半可加快照的跨时间聚合、 +命名财年的自然语言窗口仍明确不支持;类别×期间诊断分解在阶段3交付。 +覆盖边界是入库方的审核承诺,不能由事实表最小/最大日期推断出来。 + +### 第二阶段验证记录 + +环境:Python 3.12.11、SQLite 3.50.4、SQLGlot 28.10.1、Pydantic 2.13.4。 +新增 `tests/test_analysis_semantics.py` 共49项测试,覆盖真实 SQLite、CLI、REST、 +发布/漂移、恢复、独立样例 oracle 及错误注入。 + +| 检查 | 命令 | 结果 | +| --- | --- | --- | +| 开发前基线 | `./init.sh` | 959项,25 skip,0失败,退出码0 | +| 第二阶段及相关语义专项 | `LOG_LEVEL=CRITICAL .venv/bin/python -m unittest tests.test_analysis_semantics tests.test_semantic_sql_validator tests.test_anime_semantic_governance -q` | 101/101通过,其中49项为第二阶段新增;退出码0 | +| 样例迁移审查 | `make semantic-check`(基线更新前) | 检出4个预期指标变更;86/86合同通过,0 blocking failures | +| 审查后基线更新 | `LOG_LEVEL=CRITICAL .venv/bin/python -B scripts/check_semantic_drift.py --database sample_data/anime_streaming/anime_streaming.sqlite --model sample_data/anime_streaming/semantic_model.yml --baseline sample_data/anime_streaming/semantic_baseline.json --report /tmp/queryforge_phase2_baseline_update.json --update-baseline` | baseline_updated,86/86合同通过 | +| 语义复核 | `make semantic-check` | no_change;86/86通过,0 blocking failures,退出码0 | +| 离线任务门禁复核 | `LOG_LEVEL=CRITICAL .venv/bin/python -B scripts/benchmark_agent.py --tier 1 --gate --report /tmp/queryforge_phase2_tier1.json` | 23/23任务通过;既有必需步骤和证据全部满足,阈值未改 | +| 最终全量 | `./init.sh` | 1008项,983通过,25 skip,0失败;退出码0 | +| 仓库与完整离线验收 | `make check` | 仓库检查通过;13/13验收通过;内含全量测试1008项、25 skip、0失败;退出码0 | +| 差异格式 | `git diff --check` | 退出码0 | + +新增测试验证治理、业务口径与控制流,不度量真实模型能力。本阶段未调用付费 API, +未运行 tier-3,也不将离线通过率解释为模型准确率提升。 + +闭环期间发现:将所有 DISTINCT 计数一律禁止分组总计,会移除零售订单数任务的 +必需 drill_down 证据。修复为可证明的例外:仅当 COUNT DISTINCT 的列恰好是 +单列事实主键/粒度,运行时完整唯一性检查通过且连接不复制记录时,才按互斥分组 +累计。跨组用户去重等业务 DISTINCT 仍不可相加;受限扫描或未知唯一性仍被拒绝。 +该修复保留既有验收定义,并新增可相加/未验证不可相加的两项回归。 + +比例错误注入还发现:严格核验数学表达式时,不能把合法的最终结果 ROUND +误判为分子分母变化。修复允许最终展示精度,仍拒绝对组件先行舍入;AVG +等价路径检查物理非空或相同 COUNT 列,拒绝可空列的 COUNT(*) 口径和分组均值再平均。 +既有样例的合法舍入与 AVG 查询恢复通过,新旧语义测试共同验证,没有放宽验收断言。 + +## 第三阶段交付(2026-10-11) + +本阶段接续前两阶段工作区,不改 SQL 执行边界、确定性门禁或只读默认值。 +离线实现与模型实验分开验收;下列开发及后续授权的 DeepSeek 实验均已完成。 + +| 任务 | 实现与闭环 | +| --- | --- | +| 3.1 业务诊断 | 有日历粒度和明确基准的分类请求自动生成诊断计划:质量核验、独立总量、期间×分类明细、精确比较、贡献分解、异常扫描、证据交付。每个指标单独对账;当前和基准两期的分类绝对总量都必须匹配独立查询,不仅验证差值。输出 `answer.diagnosis`,保留单位、口径、完整性、质量检查和证据 id;贡献是算术分解,不是因果证明。 | +| 3.2 严格交付验收 | 共享 `result_contract`:必需列、额外列、外层排序、空结果策略和结果路径。默认比较完整参考投影;辅助列必须显式声明。列名对齐后逐位置比较行内数值,保留重复行;NL2SQL 必须运行成功才算结果正确。使用漏指标、值换位、排序丢失、重复/空行、失败终态和非有限数值错误注入。 | +| 3.3 独立留出与配对 | 物理 schema 指纹与 `split_scope` 防止仅改数据集名跨分片;保留问题/模板/语料污染检查。候选实验固定 skills=auto,技能实验固定候选数;同任务同输入重复运行,交替 A/B 顺序,每次状态隔离。按任务聚类 bootstrap,单列环境和已知 provider 协议失败,记录有效分母、原始证据、模型/技能资产、代码、数据、合同、金标和运行环境指纹;运行中版本变化不能宣告实验完成。 | + +### 可复核的业务结果 + +独立 fixture 两期分类:a=30→10,b=20→50。 + +| 场景 | 实测结果 | +| --- | --- | +| 对账与相互抵消的驱动 | 独立总量50→60,变化+10;a贡献−20、b贡献+30,贡献份额−200%和300%,残差0;份额允许超出0–100%,避免掩盖抵消关系 | +| 总变化为零 | a贡献−20、b贡献+20仍保留;总变化0,贡献份额为null,不能编造百分比 | +| 多指标诊断 | count和amount分别比较、分解和对账,最终证据支持每个指标 | +| 未知/丢失的类别 | NULL是独立桶;缺失类别期间只在完整覆盖下解释为0;连接丢失即使两期丢失相等、变化残差恰好为0,也因绝对总量不符而拒绝 | +| 有限输出、不可加、证据缺失 | 达到查询上限、比例/非可加维度、无完整性依据的空桶、删掉诊断节点的自定义计划均不能成功交付 | +| 异常历史不足 | 显式两期查询只有2点,异常状态为insufficient_data并带限制;不把“没有足够历史”解释为“没有异常” | +| 对外接口与恢复 | CLI和REST交付一致数值与证据;模拟中断后重放仍区分独立总量与明细证据,不复活已结束运行 | + +`evaluation/diagnostics/` 新增三条任务,未修改原32条任务或阈值。 +金标数值由 `scripts/freeze_diagnostic_tasks.py` 的独立只读基表 SQL 冻结; +总量 SQL 不复用分类 SQL 或运行输出。浮点残差的绝对容差显式设为1e-9, +既有任务的零值仍默认精确匹配;不是把残差不符改为通过。 + +| 独立 schema / 任务 | 基准→当前 | 变化 | 期间完整性 | +| --- | ---: | ---: | --- | +| anime / watch_hours 按设备同比(2024-02→2025-02) | 1115.8683333333333→1117.3080555555555小时 | +1.4397222222221444 | complete,已有覆盖契约 | +| retail / net_revenue 按渠道环比(2024-02→2024-03) | 12071.96→10791.91 | −1280.05(浮点舍入) | unverified,未给旧样例补造覆盖契约 | +| support / ticket_volume 按优先级环比(2024-02→2024-03) | 31→32 | +1 | unverified,未给旧样例补造覆盖契约 | + +这三条任务均通过完整投影、期间排序、独立总量、贡献残差和证据链验收。 +生成器金标与当前样例 SQL 的一致性及三条真实执行已加入单元套件。 + +### 重复配对验证的含义 + +两类离线实验各选择原金标中23条workflow任务、三个独立schema、每任务5次重复、 +两组设置:各230次执行、115对观察。两组任务通过率均为1.0,变化为0, +任务聚类bootstrap 95%区间为[0,0];环境/协议失败排除数为0,版本指纹稳定。 +这是 ScriptedModel 直接返回 reference_sql 的治理与控制流验收,**不能度量模型能力**, +零宽区间不能证明机制没有效果。没有实测模型token或价格表,token/成本变化均为null。 +离线延迟不用于评判真实模型效率。 + +复现命令、任务契约和报告解释见[评测方法](nl2sql_evaluation.md#phase-3-task-contracts-and-paired-experiments-2026-10-11)。 +原始JSON报告生成于 `/tmp/queryforge_phase3_paired_candidates.json` 和 +`/tmp/queryforge_phase3_paired_skills.json`;数字保存在本跟踪文档中。 +依赖版本:Python3.12.11、SQLite3.50.4、SQLGlot28.10.1、Pydantic2.13.4; +每个报告的manifest另含source/assets/datasets/contracts/gold的SHA-256和git状态。 + +付费实验已准备dry-run预览:沿用仓库配置的deepseek / deepseek-v4-flash, +候选1→2(skills=auto)及技能off→auto(候选数=1),各23任务×5重复×2组=230次执行。 +预览不调用API;当时模型选择、预算、账户余额和凭据配置尚待确认。 +病例执行次数不等于API调用上限,修复和多轮上下文会增加调用。 +[AGENTS.md](../AGENTS.md) 明确要求:"Tier-3 / any real API spend → ask before running." +未授权前不运行tier-3,不能宣称真实模型准确率、延迟或成本改善。 + +后续用户已授权使用 DeepSeek,并在本机配置凭据。API 核验当前模型为 +`deepseek-flash` / V4.1-Flash,账户可用。原控制流题集的首次真实预检发现题意 +与标准投影不一致,因此暂停并保留预检记录;新增独立的 `evaluation/live_tasks/` +明确请求列、排序和空结果,保留原数据、参考 SQL、32条任务和阈值。 +真实实验、使用量对账和成本口径见[实时评测记录](nl2sql_evaluation.md#authorized-deepseek-live-pairs-explicit-tasks-v1-2026-10-11)。 + +### 第三阶段验证记录 + +新增40项测试:诊断16项、输出/物理隔离/工具追踪14项、配对实验10项。 +闭环期间全量发现Demo E仍使用无独立总量证据的手写宽表计划;迁移为正式诊断模板, +保留原有“数据下降→持平→增长,结论随数据改变”的断言。演示6项复核通过。 +同时把基准工具调用计数改为逐个tool span,避免一个查询步骤内的日期/粒度核验被漏计, +并避免并发步骤共享预算计数相互重叠。三条诊断实测10/8/8次工具调用,均符合原阈值。 + +| 检查 | 命令 | 实际结果 | +| --- | --- | --- | +| 开发前基线 | `./init.sh` | 1008项、25 skip、0失败,退出码0 | +| 诊断/输出/配对/原基准专项 | `LOG_LEVEL=CRITICAL .venv/bin/python -B -m unittest tests.test_analysis_diagnostics tests.test_evaluation_contracts tests.test_paired_benchmark tests.test_agent_benchmark tests.test_agent_task_gold -q` | 61/61通过,退出码0 | +| 演示修复复核 | `LOG_LEVEL=CRITICAL .venv/bin/python -B -m unittest tests.test_demo_scripts -q` | 6/6通过,退出码0 | +| 原默认门禁 | `LOG_LEVEL=CRITICAL .venv/bin/python -B scripts/benchmark_agent.py --tier 1 --gate --report /tmp/queryforge_phase3_tier1.json` | 23/23通过,阈值未改,退出码0 | +| 独立留出与原全分片门禁 | `LOG_LEVEL=CRITICAL .venv/bin/python -B scripts/benchmark_agent.py --tier 1 --split dev --split regression --split holdout --gate --report /tmp/queryforge_phase3_all_splits.json` | 32/32通过(含9 holdout),阈值未改,退出码0 | +| 新诊断门禁 | `LOG_LEVEL=CRITICAL .venv/bin/python -B scripts/benchmark_agent.py --tier 1 --tasks-dir evaluation/diagnostics --split dev --split regression --split holdout --gate --report /tmp/queryforge_phase3_diagnostics.json` | 3/3通过;完整投影和独立总量均满足;退出码0 | +| 重复配对(候选) | `LOG_LEVEL=CRITICAL .venv/bin/python -B scripts/run_paired_benchmark.py --tier 1 --feature candidates --repeat 5 --report /tmp/queryforge_phase3_paired_candidates.json` | 115/115对,230/230执行通过;无环境/协议失败;版本稳定;退出码0 | +| 重复配对(技能) | `LOG_LEVEL=CRITICAL .venv/bin/python -B scripts/run_paired_benchmark.py --tier 1 --feature skills --parallel-candidates 1 --repeat 5 --report /tmp/queryforge_phase3_paired_skills.json` | 115/115对,230/230执行通过;无环境/协议失败;版本稳定;退出码0 | +| 语义漂移 | `make semantic-check` | 86/86通过,0 blocking failures,no_change,退出码0 | +| 最终全量 | `./init.sh` | 1048项,1023通过、25 skip、0失败,退出码0 | +| 完整仓库验收 | `make check` | 仓库检查与13/13离线验收通过;内含1048项、25 skip、0失败;退出码0 | +| 差异格式 | `git diff --check` | 退出码0 | + +单独 `--split holdout --gate` 会因原阈值要求regression分片而退出1;这是预期的完整性门禁, +不能删掉该要求以得到绿色结果。本阶段使用三分片一起运行门禁,并独立检查holdout的9/9结果。 + +### DeepSeek 真实配对评测与补充修复 + +已按用户授权使用 `deepseek-flash`(API发现名称 DeepSeek-V4.1-Flash), +完成候选1→2及技能off→auto两组实验:每组23题、3个独立schema、5次重复、230次执行。 +两组共460次执行,执行期间的代码、资产、数据、合同与金标指纹一致。 +原始分数和后验审计分开保存,没有改阈值或重跑挑选结果。 + +| 实验 | 原始合同通过率(每组115次) | 补充来源核验(每组115次) | 剔除歧义题后的来源核验(每组110次) | 最后一列差值及任务聚类95%区间 | +| --- | --- | --- | --- | --- | +| 候选1→2,技能auto | 91/115→84/115:79.13%→73.04% | 89/115→82/115:77.39%→71.30% | 89/110→82/110:80.91%→74.55% | −6.36个百分点,区间[−13.64,0] | +| 技能off→auto,候选数1 | 91/115→88/115:79.13%→76.52% | 89/115→85/115:77.39%→73.91% | 89/110→85/110:80.91%→77.27% | −3.64个百分点,区间[−8.18,0] | + +最后一列口径是单独报告的后验敏感性分析,包含22题×5次重复;每条原始记录仍保留。 +被剔除的排名题使用“outlet”,而数据中 `store_format=Outlet` 是具体类型,原金标却要求 +所有24家门店。按类型筛选四家门店有题意依据,这是金标题的问题,不能作为模型错误。 +未来v3题集明确要求所有门店、不限类型;没有用改写后的题意重判旧回答,也没有再调用模型。 + +| 效率指标(同22题子集,按任务等权) | 候选1→2 | 技能off→auto | +| --- | --- | --- | +| 平均耗时 | 21.916→24.073秒,+9.84%;差值区间包含0 | 12.704→23.690秒,+86.47%;差值区间[7.813,15.158]秒 | +| 实测token | 18498.70→31011.02,+67.64%,110对 | 15075.89→18621.41,+23.52%,109对 | +| 已知价格费用均值 | 0.021003696→0.025221900元/次,+20.08%,110对 | 0.012204155→0.020640890元/次,+69.13%,109对 | + +技能组有一次反思请求超时,原失败保留在质量与耗时分母中,没有重跑。 +先前四次成功响应的35164个token可以核对,第五次调用用量未知;整次调用的总费用为null, +不能当作免费。这一对不进入实测token与完整费用比较,所以对应分母为109对。 +数值来自缓存命中/未命中/输出分别计价,属于当前缓存条件下的估价,不能当作冷缓存成本或账单。 +候选已报告响应估价5.27165492元,技能已报告响应小计3.79053536元;合计9.06219028元, +不含未知调用。账户余额及预检余额观察保留在私密本地记录,不公开展示。 + +两种机制均未证明质量提升。区间按任务聚类抽样,重复留在任务内部,不把110对当作110条独立题目。 +这里评价的是终态、输出列、数值、证据和工具记录的完整交付合同;列名错误、已恢复的工具失败 +也可能不通过,不能称为纯SQL生成准确率或通用能力。完整命令、指纹、分母与限制见 +[冻结评测记录](nl2sql_evaluation.md#authorized-deepseek-live-pairs-explicit-tasks-v1-2026-10-11)。 + +本次补充开发均在两组付费实验结束后合入: + +| 优化成果 | 实测闭环 | +| --- | --- | +| 独立SQL来源合同 | 仅计入最终查询有效作用域的物理表,别名和未使用CTE不能冒充来源;不支持的形状失败关闭。共拒绝9次只查日历表的误通过;独立SQLite反事实数据证明日期极值相同只是样例巧合。来源覆盖是必要条件,不证明连接、过滤或完整业务语义。 | +| 可复算审计与费用 | 重算460条原始判定,0不一致;核对1560条已报告响应,0用量不一致;估算与实测、未知调用费用分开。原始报告、执行版本与后验评分版本均保留。 | +| 断点续跑 | 技能实验暂停后的175条记录原样保留,仅执行剩余55条;恢复前离线复现175/175判定并核对全部控制。独立CLI恢复验证保留2条、只执行剩余2条,4/4通过,0真实响应。 | +| SQL实际重放 | 经DatabaseTool核对全部原始通过SQL:候选175/175、技能179/179,实际行与参考值均匹配;原策略哈希与数据库字节不变。重放仍不能证明源表意图,因此同时保留独立来源检查。 | +| 多轮实验日期控制 | 修复AgentService评测分支未收到固定日期的问题,同时显式传递重试/向量控制;两轮真实Scripted回归均使用2024-12-31。原实验的该题统计全部订单,没有相对时间窗口,值不受运行日影响;原日期控制缺陷如实保留。 | +| 未来金标修正 | v1原样保留;v2只增加来源评分条件;v3只澄清门店排名题。三版各23条独立只读SQL oracle全部核验通过;更改题意不能回溯评分旧输出。 | + +新增30项回归(来源13、合同/审计/金标16、多轮日期1),第三阶段累计新增70项。 +补充审计与SQL重放均没有调用模型。专项184项通过;最终 `./init.sh` 实测1078项、 +1053通过、25跳过、0失败,退出码0(95.934秒)。 + +第四阶段优先新增4.0:收紧请求→指标绑定及有效表达式核验。缺失满意度数量不应附带平均满意度, +SLA编号列表不应强制聚合计数,独立订单/明细计数应按事实粒度核验;未使用的AVG CTE不能满足 +一个真正需要执行的平均值义务。相应闭环应覆盖基表oracle、SQL作用域、CLI/REST和错误注入。 +再进行4.1的技能预筛选与候选预算,按同输入质量、耗时、token与费用验收。上述是第三阶段 +结束时的记录,当时尚未实施第四阶段;本地第四阶段的后续交付与限制见下文。 + +### 补充开发最终验收 + +| 检查 | 复现命令 | 实际结果 | +| --- | --- | --- | +| 来源/审计/原评测专项 | `LOG_LEVEL=CRITICAL .venv/bin/python -B -m unittest tests.test_sql_source_coverage tests.test_source_contract tests.test_agent_evaluator tests.test_agent_task_gold tests.test_evaluation_contracts tests.test_paired_benchmark tests.test_agent_benchmark tests.test_analysis_diagnostics -q` | 184项通过,0失败,退出码0(5.135秒) | +| 三版金标 | `scripts/freeze_live_tasks.py --check`;同命令加 `--source-contract` / `--correct-questions`(使用 `.venv/bin/python -B`) | v1/v2/v3各23条独立oracle核验通过,均退出0 | +| 全量 | `./init.sh` | 1078项,1053通过、25跳过、0失败,退出码0(95.934秒) | +| 仓库验收 | `make check` | 仓库检查通过、13/13离线验收通过;内含1078项、25跳过、0失败,退出码0(内含测试98.705秒) | +| 原三分片门禁 | `LOG_LEVEL=CRITICAL .venv/bin/python -B scripts/benchmark_agent.py --tier 1 --split dev --split regression --split holdout --gate --report /tmp/queryforge_phase3_deepseek_final_all_splits.json` | 32/32通过,原阈值未改,退出码0 | +| 诊断门禁 | 上述命令加 `--tasks-dir evaluation/diagnostics`,报告 `/tmp/queryforge_phase3_deepseek_final_diagnostics.json` | 3/3通过,退出码0 | +| 差异格式 | `git diff --check` | 退出码0 | + +全量日志为 `/tmp/queryforge_phase3_deepseek_final_init.log` 和 +`/tmp/queryforge_phase3_deepseek_final_make_check.log`。真实运行原始JSON、来源评分JSON、 +逐调用用量、断点和DatabaseTool重放记录均在被忽略的 `evaluation/reports/` 中; +本记录及现有跟踪文件 `docs/nl2sql_evaluation.md` 保存数值、命令和依赖版本。 + +## 第四阶段:本地单用户交付(2026-10-11) + +原计划共四个阶段。用户确认“仅支持本地单用户”后,4.3 按本地边界、域/版本绑定和 +产物生命周期实施;没有增加多用户登录或云部署授权。保留 DatabaseTool 唯一 SQL 执行 +边界、确定性政策/语义/证据门禁及只读默认。代码开发和自动验收完成,完整浏览器上传 +点击验收仍待复验;不能把该项标记通过。第四阶段没有调用付费模型。 + +### 实现与独立核验 + +| 任务 | 交付与证据 | +| --- | --- | +| 4.0 请求与有效输出 | 正式返回列名与业务指标分开;核验最终列名/顺序;编号列表拒绝聚合、常量和变换。跟踪 CTE/派生列的有效血缘,未使用 AVG 或 GROUP BY 不满足口径;独立事实计数按各自作用域验证,连接 fan-out 仍拒绝。显式支持的 NULL 请求不可省略、取反或被 OR 放宽。单基表可信非空单列主键证明后才允许 COUNT(*) 等价。实际 SQLite、CLI/REST 和错误注入回归验证执行前拒绝。 | +| 4.1 调用与缓存 | 十个内置技能增加关键词预筛选;没有可选技能时直接使用默认 SQL 技能,保留 `auto` 状态。显式主题目录/手动选择兼容。缓存仅含元数据和 prompt,按真实字节/正文版本失效;同 mtime 改动、删除文件及跨节点覆盖有回归。保留默认单候选及原有修复流程;非法/重复候选不消耗预览预算,取消阻断后续生成/预览/执行。 | +| 4.2 Studio 真实状态 | 提取 CSV、来源状态、快照和本地边界模块,新增可编辑指标表达式/聚合/维度。CSV 检查真实有界样本,Parquet 交由 Python 物理发布;不虚构数据质量、行数或覆盖分数。实际 publication/data_version 才显示 Ready/Published;未知和失败状态可见。修复默认指标未限定表名、上传格式与发布器不一致、成功合同仍显示 Draft、旧域结果滞留及历史 run_id 不一致。 | +| 4.3 本地生命周期 | Studio 上游和开发监听限定 loopback;外来 Origin 拒绝。域未发布/域与路径混用均阻断。历史快照绑定 run/domain/data_version,2 MiB 上限、30 天访问,跨域404、冲突409、缺失/过期410;回放不查询、不调模型。报告默认30天后不可访问,清理先预览,执行后移入 `.expired/` 可恢复,不删除运行证据。 | + +新增 Python 测试27项(请求16、本地产品化8、候选预算/取消3),总数1078→1105;新增 +Studio 行为测试7项,总数24→31。维护热点按请求合同、输出血缘、报告存储与前端边界 +拆分,没有另造 SQL 执行器。缓存不存用户结果;快照是本地客户端提交的留存结果,不是 +针对不可信多用户的签名证明。契约编辑器只覆盖单实体维度/指标,完整关系、时间、单位仍在 +YAML 编写。关键词是启发式筛选,未命中业务同义词时仍需补充目录。 + +### 固定题集的离线效率观察 + +比较 `evaluation/live_tasks_v3` 全部23题(含一条多轮任务),数据、合同、金标、阈值和 +任务次序指纹一致,自动技能模式、固定日期2024-12-31、无向量/历史检索。 +前版本未显式传候选数,离线 runner 默认1;后版本显式1。逐题检查两次都没有候选选择 +payload,因此候选数没有混入比较。前版本已经实施主要4.0修复;后版本同时包含后续 +正确性修复和技能资产变化,这是版本观察,不能当作单因素随机消融。 + +| 指标 | 预筛选前 | 最终版本 | 解释 | +| --- | ---: | ---: | --- | +| 任务合同通过 | 23/23 | 23/23 | SQL 由 ScriptedModel 提供,只验证工程控制流与确定性门禁 | +| 模型调用次数 | 72 | 51 | 少21次,29.17%;包含多轮任务早先的一轮 | +| 末轮技能路由模型 span | 23 | 3 | 另有多轮任务早先一轮的调用计入上一行 | +| 本地估算 token | 299851 | 276994 | 少22857,7.62%;实测调用/token 均为0 | + +未对并发运行离线夹具的毫秒耗时作性能结论;没有 DeepSeek 准确率、实际延迟或账单成本 +改善的证据。阶段3付费实验没有证明候选2或全目录技能路由提升质量,因此默认单候选保留。 +真实模型复验需要新的付费授权及有余额账户,不因离线全绿而替代。 + +前版本命令: + +```bash +LOG_LEVEL=CRITICAL .venv/bin/python -B scripts/benchmark_agent.py --tier 1 --tasks-dir evaluation/live_tasks_v3 --split dev --split regression --split holdout --report /tmp/queryforge_phase4_live_v3.json --gate +``` + +最终命令: + +```bash +LOG_LEVEL=CRITICAL .venv/bin/python -B scripts/benchmark_agent.py --tier 1 --tasks-dir evaluation/live_tasks_v3 --split dev --split regression --split holdout --parallel-candidates 1 --skill-mode auto --report /tmp/queryforge_phase4_live_v3_final.json --gate +``` + +运行环境 Python3.12.11、SQLite3.50.4、SQLGlot28.10.1、Pydantic2.13.4;基于 +`d1e1e4f8ef95dfdf16bf7206ddcb797fa881eb4a` 的未提交工作区。前/后 source 指纹分别 +`83e6adde9def7439bb9823901846bbe5503c2bf3e6ac5168a531a1b589423a20` / +`37691987be54e082f14a271c07801492fede4f45b6961f1205fd290b26a26b4f`; +金标指纹 `50573fa619a41660f7f548cb38598b42dc204f92708622b5b589edf1f1c01842`。 +完整数据/合同/资产指纹、Node版本、前端字节指纹和证据摘要保存于 +[第四阶段冻结记录](../evaluation/phase4_local_acceptance_2026_10_11.json)。原始报告保留在 `/tmp/`, +上述数值与依赖已写入待提交的仓库文件,不依赖被忽略的原始 JSON 才能查阅。 + +### 闭环验收 + +| 检查 | 命令 | 实测结果 | +| --- | --- | --- | +| 开发前基线 | `./init.sh` | 1078项、25跳过、0失败,退出0 | +| 最终全量 | `./init.sh` | 1105项:1080通过、25跳过、0失败,退出0;110.680秒 | +| 仓库与离线验收 | `make check` | 仓库检查、13/13验收通过;内含1105项、25跳过、0失败,退出0 | +| 语义漂移 | `make semantic-check` | 86/86通过,0失败,no_change,退出0 | +| Studio 静态/构建/行为 | `make web-check` | eslint、tsc、生产构建与31/31测试通过,退出0 | +| 原全部分片门禁 | `LOG_LEVEL=CRITICAL .venv/bin/python -B scripts/benchmark_agent.py --tier 1 --split dev --split regression --split holdout --report /tmp/queryforge_phase4_tier1_all.json --gate` | 32/32通过,原阈值未改,退出0 | +| 诊断任务门禁 | 上一命令加 `--tasks-dir evaluation/diagnostics`,报告 `/tmp/queryforge_phase4_diagnostics.json` | 3/3通过,退出0 | +| v3 全分片门禁 | 本节上方最终命令 | 23/23通过,退出0 | +| 实际本地 HTTP/SQLite 闭环 | `.venv/bin/python -B scripts/check_local_studio.py --report /tmp/queryforge_phase4_studio_acceptance.json` | 24/24通过,0真实模型调用,退出0;夹具慢请求用于取消验收 | +| 差异格式 | `git diff --check` | 退出0 | + +HTTP checker 必须先看到显式离线模型健康标记,否则退出。真实服务启动方式见 +[Studio 验收说明](studio.md#validate-the-frontend),临时 D1/R2、发布数据库、运行日志 +均与样例库/用户存储隔离。实际3行 CSV/Parquet fixture 金额10/20/30:上传→审核→Python +发布返回可执行 data_version,查询 count=3、sum=60;非法 CSV/Parquet、未审核/未发布域、 +路径覆盖、DELETE、外来 Origin、跨域/冲突快照均拒绝,拒绝后记录仍为3。SSE 唯一终态和 +连续序列通过;生成阶段断开连接后状态落盘 cancelled,未生成执行结果产物。取消是协作式, +在途模型请求可能先完成,不能承诺立即中止该请求。过期报告404、dry-run 保留原件、实际 +清理可恢复两份文件,原运行证据保留。 + +另通过 CUA 在真实 Chrome 验证已发布域的查询:SQL 为 +`SELECT COUNT(DISTINCT record_id) AS n FROM uploaded_record`,可见结果3;随后从历史 +回放相同结果和原 data_version,模型调用计数24→24。该域由 HTTP 夹具先发布,不能将 +浏览器查询证据称为浏览器上传证据。完整上传点击流程未通过:合成 CSV 在原生选择器中 +被选中,但“打开”一直禁用;未伪造 file-input 成功。该项保留待手工复验,真实 HTTP +发布24项和浏览器查询/回放分别记录。阶段4的真实 DeepSeek 质量、延迟、实测用量也未重测。 + +最终日志:`/tmp/queryforge_phase4_final_init.log`、`/tmp/queryforge_phase4_make_check_final.log`、 +`/tmp/queryforge_phase4_web_check_final.log`、`/tmp/queryforge_phase4_studio_acceptance.log`。 +快照原始 HTTP 和浏览器记录分别为 `/tmp/queryforge_phase4_studio_acceptance.json`、 +`/tmp/queryforge_phase4_browser_acceptance.json`;核心摘要已冻结到上述仓库 JSON。 diff --git a/docs/semantic_authoring.md b/docs/semantic_authoring.md index fc370b9..1bf5ca8 100644 --- a/docs/semantic_authoring.md +++ b/docs/semantic_authoring.md @@ -72,6 +72,29 @@ QueryForge discovers automatically. If any asset, relationship, metric, or quali contract fails, the entire batch is rolled back: no uploaded rows or watermark advance remains without a semantic layer. +## Review Analysis Semantics + +For governed multi-fact analysis, declare a fact grain and safe many-to-one paths to +conformed dimensions. Every metric must allow the requested dimension. The compiler +aggregates each fact independently before joining key domains, and runtime checks must +prove target-key uniqueness and other fact grains within the existing quality budget. +Bounded or unavailable checks are unverified and block that join; an empty dimension +remains an explicit data-absence result. + +Review `analysis.unit`, additivity, the business meaning of `time_field` and its +`time.role`, UTC/fixed-offset semantics, and fiscal year start. Ratios should declare +aggregate `ratio.numerator` / `ratio.denominator` instead of duplicating a handwritten +division expression. Verify that they share the intended filtered population. +Coverage bounds must come from a reviewed ingestion guarantee; observed min/max dates +and sparse fact rows cannot establish full coverage. See [analysis contracts](semantic_contracts.md#analysis-contracts) +for the exact supported shape, authoring gates and limitations. + +The bundled sample migrates `watch_hours`, `completion_rate`, `unique_viewers`, and +`average_rating`; its deterministic generator covers 2023-01-01 through 2025-12-31. +The two ratio definitions use explicit components. Curated models remain authoritative +during incremental builds. Review the drift report before updating a baseline; never +use a baseline update to hide a failing contract. + ## Upload Contract Shape ```yaml diff --git a/docs/semantic_contracts.md b/docs/semantic_contracts.md index b229d5c..f5bedbd 100644 --- a/docs/semantic_contracts.md +++ b/docs/semantic_contracts.md @@ -57,6 +57,102 @@ a dimension. `severity: warning` records a failed result without blocking publication. The default `error` severity blocks semantic publication. +## Analysis Contracts + +Metrics may declare the following optional contract. Legacy models still load; their +unit/time role remains unknown and their period completeness is unverified. + +```yaml +metrics: + - name: completion_rate + description: Completed sessions divided by all sessions. + entity: watch_session + aggregation: ratio + ratio: + numerator: SUM(fact_watch_session.completed_flag) + denominator: COUNT(*) + scale: 1.0 + allowed_dimensions: [calendar.month, watch_session.device] + time_field: fact_watch_session.watch_date_key + analysis: + unit: fraction + additivity: non_additive + time: + role: watch_event + timezone: UTC + fiscal_year_start_month: 1 + coverage_start: "2023-01-01" + complete_through: "2025-12-31" + require_complete_periods: true +``` + +Omit `expression` when declaring `ratio`: it is derived as +`CAST(numerator AS REAL) * scale / NULLIF(denominator, 0)`. If both are supplied, +the expression must equal the canonical derived expression. Each component must be a +single `SUM`/`COUNT` over qualified base-table columns (or `COUNT(*)`), with no subquery, +nested aggregate, division, comments or extra statement. Numerator and denominator share +the metric's default/request filters, joins and time window. The compiler computes both +at the requested grain and returns `metric__numerator` / `metric__denominator` audit columns. +Zero denominators are undefined and cannot satisfy an analysis request. + +The SQL gate verifies the declared numerator, denominator, scale and floating-point +division together, so merely referencing both aggregates does not prove the ratio. +An equivalent `AVG(column) * scale` is accepted for `SUM(column)/COUNT(column)`; +with `COUNT(*)`, it additionally requires physical non-nullability of that column. +An average of preaggregated group values is unsupported. Final-value `ROUND` for +presentation is allowed, while rounding a component changes the contract and is rejected. + +`additivity` is `additive`, `non_additive`, or `semi_additive`. Ratios and distinct counts +must be non-additive. Semi-additive metrics must name `non_additive_dimensions` from their +allowed dimensions; time rollups over these dimensions are unsupported until an explicit +snapshot aggregation exists. Legacy ratio/distinct definitions receive conservative +non-additive inference. No ratio, distinct count or incompatible unit is added to another +metric's total. A missing fact population stays missing rather than becoming zero. + +An undeclared legacy `COUNT(DISTINCT primary_key)` is a row count when the single +column is exactly the entity's fact grain. It can be summed over disjoint groups +only after the runtime quality gate proves that grain unique and the compiler's +join checks prevent duplication. Business distinct counts such as users per region +retain non-additive semantics; bounded or unavailable identity checks block the total. + +`time.role` names the business event represented by the existing `time_field`; it does +not select a different field by column name. ISO timestamps may carry offsets; calendar +conversion supports UTC and explicit fixed offsets such as `+08:00`. Named DST zones +are rejected. Eight-digit date keys already represent civil dates and cannot be shifted. +Weeks begin Monday. Fiscal quarterly/yearly buckets use ISO period-start dates; other +labels remain `YYYY-MM-DD`, `YYYY-MM`, `YYYY-Qn`, or `YYYY`. Date ranges still use the +existing civil-calendar parser; fiscal buckets are not named fiscal-year range inference. +Daily leap-day year-over-year comparison has no same calendar day in a non-leap year and fails closed. +Weekly year-over-year comparison uses the Monday week containing the prior year's corresponding calendar date. + +Coverage bounds are a reviewed ingestion guarantee supplied by the data owner, not +inferred from a fact table's min/max dates or the presence of one row per period. Both +bounds must be declared together. `require_complete_periods: true` requires them and +rejects requested windows outside coverage, clipped period buckets, missing requested +buckets and missing baselines. Without enforcement, outputs describe observed data and +report `period_completeness: unverified`. The publication gate and runtime SQL boundary +also reject invalid event dates, including normalized impossible dates such as February 30. +Contracts and component definitions participate in semantic drift snapshots. + +## Active output and request obligations + +Metric obligations are bound to the measure part of a request. Formal output-label +trailers such as `Return orders and lines in that order.` are labels, rather than +additional business measures. Explicit identifier lists must project original +columns; aggregates, constants and transformed identifiers fail before SQL +execution. Formal identifier-only output contracts require the final columns and +their order, without `SELECT *`. This is a bounded English/Chinese grammar, not +arbitrary natural-language understanding. + +Runtime metric checks follow the final output's active dependencies through CTE +and derived-table projections. An unused CTE, unselected aggregate or unrelated +GROUP BY cannot prove a requested measure or grain. Independent fact counts are +checked in their own scopes; a fan-out join remains blocked. COUNT(*) can replace +a distinct fact-grain count only for a trusted non-null single-column primary key +on one physical source with no join. Other distinct-count obligations remain exact. +Explicit supported NULL requests require an AND-constrained IS NULL predicate in +the measure's active scope; omitted, negated or OR-weakened predicates fail closed. + ## Validate a Model ```bash diff --git a/docs/studio.md b/docs/studio.md index 67e57ef..1e9f05c 100644 --- a/docs/studio.md +++ b/docs/studio.md @@ -14,8 +14,8 @@ make web-install make web-dev ``` -Open . The interface uses a deterministic demo response -when the QueryForge API is offline, which is useful for exploring the product. +Open . This optimization targets local single-user use. +Demo results are labelled explicitly; a failed live request cannot become a demo success. For live execution, start the Python API in another terminal: @@ -25,17 +25,21 @@ queryforge --serve-api The Studio sends requests through its same-origin `/api/queryforge/*` proxy. Set `QUERYFORGE_API_URL` in `web/.env.local` if the API is not available at -`http://127.0.0.1:8000`. +`http://127.0.0.1:8000`. The configured upstream must remain a loopback HTTP(S) +address. The development server binds to `127.0.0.1`, disables the public worker +inspector, and rejects foreign origins on Studio routes in local mode. ## Domain-first workflow 1. Open **Data Domains**. 2. Select the bundled Anime Streaming sample or create a clean business domain. -3. Add SQLite, CSV, or Parquet files inside the active domain. -4. Profile physical schema and candidate keys. -5. Review identity, grain, dimensions, measures, time fields, and ownership. -6. Define metrics, relationships, cardinality, and safe Join Paths. -7. Classify sensitivity, apply SQL policy, and pass quality checks. +3. Add CSV or Parquet files inside the active domain; database files are rejected. +4. Inspect actual CSV columns and sampled missing values (up to 2 MiB / 1000 rows). +5. Review the starter draft's entity, grain, key, dimensions and owner. +6. Edit metric names, descriptions, count/sum/ratio aggregations and qualified + `table.column` expressions. Editing resets review and draft validation. +7. Classify sensitivity and confirm the semantic review. Draft field checks + are not physical quality or publication verdicts. 8. Publish data and semantics atomically. 9. Ask questions and inspect Trust Trace evidence within that same domain. @@ -47,27 +51,41 @@ definitions from the sample. ## Mandatory semantic onboarding -The Data Sources workflow profiles an uploaded asset, generates a conservative -semantic draft, and then stops at a human review gate. Physical column names are -evidence—not accepted business truth. Publication remains disabled until: +The upload wizard inspects a bounded CSV sample and presents an editable starter +contract. It does not infer unique keys, business grain or a dataset quality +score. Parquet schema remains unverified in the browser and is checked by the +Python publisher. The local contract editor supports one entity with named +dimensions and measures; full relationship/time/unit authoring remains in YAML. +Physical column names are evidence. Publication remains disabled until: 1. business entity identity and row grain are explicit; -2. primary keys, dimensions, measures, time semantics, and metric units are - reviewed; -3. relationship cardinality and every multi-hop Join Path are approved; -4. owner, sensitivity, policy, and data-quality contracts are complete; -5. blocking validation succeeds; and +2. primary key, dimensions and metric expressions are reviewed; +3. metric expressions refer to the publication table's qualified columns; +4. owner and sensitivity are complete; +5. draft fields are complete; and 6. the reviewer explicitly confirms the contract. The server enforces both boundaries. Calling the upload endpoint without a valid `domain_id` or without `reviewed=true` returns an error, so neither domain -selection nor semantic review can be bypassed through the UI. +selection nor semantic review can be bypassed through the UI. The Python +publisher then checks actual data, keys and semantic contracts. Only an +executable `data_version` marks a source/domain ready. Failed and unknown source +states remain visible. Published domains can query by `domain_id`; switching +domains clears prior results and is refused while a run is in progress. ## Runtime persistence -Hosted deployments use D1 for domains, source metadata, and run history and R2 -for uploaded files. The Python runtime still owns SQL planning, policy -enforcement, read-only execution, and analytical artifacts. +Local Studio uses Miniflare's D1/R2-compatible storage for domains, sources and +history. Set `STUDIO_STATE_DIR` to isolate a test instance. The Python runtime +owns SQL planning, policy enforcement, read-only execution and reports. This +phase adds no multi-user identity or cloud deployment authorization scheme. + +Run history retains result snapshots (2 MiB maximum, 30-day access). Replay is +bound to the saved domain/data version and makes no model call. Legacy history +without a snapshot and expired snapshots are unavailable rather than re-executed. +SQL errors, publication failures and history storage errors are shown to the +user. Cancellation is cooperative: an in-flight model request can finish before +the worker records `cancelled`, but the next SQL boundary remains blocked. The bundled anime dataset under `sample_data/anime_streaming/` is read-only showcase data attached to the Anime Streaming sample domain. It is not the @@ -81,3 +99,20 @@ make web-check The check covers linting, TypeScript types, production compilation, server rendering, mandatory semantic-review enforcement, and branded social assets. + +For a disposable offline end-to-end fixture, start these in separate terminals: + +```bash +.venv/bin/python -B -m tests.studio_fixture_server +STUDIO_STATE_DIR=/tmp/queryforge_phase4_studio QUERYFORGE_API_URL=http://127.0.0.1:8000 npm --prefix web run dev +.venv/bin/python -B scripts/check_local_studio.py --report /tmp/queryforge_phase4_studio_acceptance.json +``` + +The checker requires PyArrow for its genuine Parquet fixture and refuses a +backend without the explicit offline-fixture health marker before any workflow. +It verifies real Studio HTTP handlers, local D1/R2, Python publication, governed +SQLite results, refusals, SSE disconnect cancellation, replay and report expiry. +Native browser query/replay were also verified with CUA. Native file selection +could not complete because the OS dialog kept Open disabled; the entire browser +upload click sequence remains a manual acceptance item. See the roadmap for +frozen results and the distinction between HTTP and browser evidence. diff --git a/evaluation/deepseek_flash_cny_2026_10_11.json b/evaluation/deepseek_flash_cny_2026_10_11.json new file mode 100644 index 0000000..4e0636d --- /dev/null +++ b/evaluation/deepseek_flash_cny_2026_10_11.json @@ -0,0 +1,14 @@ +{ + "version": "deepseek-cny-2026-10-11-v4.1-flash-off-peak", + "currency": "CNY", + "provider": "deepseek", + "model": "deepseek-flash", + "source": "https://api-docs.deepseek.com/zh-cn/quick_start/pricing/", + "checked_on": "2026-10-11", + "valid_from_utc": "2026-10-10T16:00:00+00:00", + "valid_until_utc": "2026-10-11T16:00:00+00:00", + "input_cache_hit_per_million": 0.02, + "input_cache_miss_per_million": 1.0, + "output_per_million": 4.0, + "basis": "Measured provider usage priced for Sunday in UTC+8; an estimate, not an invoice or foreign-exchange conversion." +} diff --git a/evaluation/diagnostics/dev.jsonl b/evaluation/diagnostics/dev.jsonl new file mode 100644 index 0000000..9c3091f --- /dev/null +++ b/evaluation/diagnostics/dev.jsonl @@ -0,0 +1 @@ +{"task_id": "anime_streaming_dev_diagnostic", "split": "dev", "dataset": "anime_streaming", "template_id": "anime_streaming_diagnostic_device_type", "question": "Explain watch hours monthly for February 2025 year over year by device", "runner": "planner", "coverage": ["business_diagnosis", "time_category_grain", "independent_reconciliation", "required_projection"], "expected_outcome": "analysis", "expected_status": ["succeeded"], "allowed_tools": ["resolve_metric", "check_data_quality", "execute_sql", "compare_periods", "calculate_contribution", "detect_anomaly"], "required_steps": ["resolve_metric", "check_data_quality", "query_metric", "compare_periods", "calculate_contribution", "detect_anomaly", "compose_answer"], "required_evidence": ["metric_resolution", "data_quality", "metric_value", "metric_totals", "period_comparison", "contribution", "anomaly"], "expected_values": {"answer.columns": ["calendar.month", "device_type", "watch_hours"], "answer.rows": [["2024-02", "Console", 217.30694444444444], ["2024-02", "Mobile", 231.26888888888888], ["2024-02", "TV", 222.69833333333332], ["2024-02", "Tablet", 224.51666666666668], ["2024-02", "Web", 220.0775], ["2025-02", "Console", 212.17666666666668], ["2025-02", "Mobile", 227.78833333333333], ["2025-02", "TV", 218.99388888888888], ["2025-02", "Tablet", 226.41194444444446], ["2025-02", "Web", 231.93722222222223]], "answer.diagnosis.contributions.watch_hours.independent_baseline": 1115.8683333333333, "answer.diagnosis.contributions.watch_hours.independent_current": 1117.3080555555555, "answer.diagnosis.contributions.watch_hours.total_delta": 1.4397222222221444, "answer.diagnosis.contributions.watch_hours.residual": 0, "answer.diagnosis.contributions.watch_hours.residual_current": 0, "answer.diagnosis.contributions.watch_hours.residual_baseline": 0, "answer.diagnosis.contributions.watch_hours.residual_explained": true, "answer.diagnosis.interpretation": "arithmetic_decomposition_not_causal_attribution", "answer.diagnosis.period_completeness": "complete", "final_answer.status": "success"}, "result_contract": {"required_columns": ["calendar.month", "device_type", "watch_hours"], "columns_path": "answer.columns", "rows_path": "answer.rows", "row_order": "ordered", "empty": "forbid"}, "values_absolute_tolerance": {"answer.diagnosis.contributions.watch_hours.residual": 1e-09, "answer.diagnosis.contributions.watch_hours.residual_current": 1e-09, "answer.diagnosis.contributions.watch_hours.residual_baseline": 1e-09}, "answer_must_reference_evidence": true, "reference_sql": "SELECT printf('%04d-%02d', watch_date_key/10000, watch_date_key/100%100) AS \"calendar.month\", device_type, SUM(watch_seconds)/3600.0 AS watch_hours FROM fact_watch_session WHERE watch_date_key/100 IN (202402, 202502) GROUP BY 1,2 ORDER BY 1,2", "totals_reference_sql": "SELECT watch_date_key/100 AS period, SUM(watch_seconds)/3600.0 AS value FROM fact_watch_session WHERE watch_date_key/100 IN (202402, 202502) GROUP BY 1 ORDER BY 1", "oracle_path": "answer.rows", "max_tool_calls": 40, "notes": "Independent base-table SQL; no compiler or generated outputs are used to freeze expected values. Anomaly history has only two points and must be reported as insufficient_data."} diff --git a/evaluation/diagnostics/holdout.jsonl b/evaluation/diagnostics/holdout.jsonl new file mode 100644 index 0000000..c25305b --- /dev/null +++ b/evaluation/diagnostics/holdout.jsonl @@ -0,0 +1 @@ +{"task_id": "support_tickets_holdout_diagnostic", "split": "holdout", "dataset": "support_tickets", "template_id": "support_tickets_diagnostic_priority", "question": "Explain ticket volume monthly for March 2024 month over month by priority", "runner": "planner", "coverage": ["business_diagnosis", "time_category_grain", "independent_reconciliation", "required_projection"], "expected_outcome": "analysis", "expected_status": ["succeeded"], "allowed_tools": ["resolve_metric", "check_data_quality", "execute_sql", "compare_periods", "calculate_contribution", "detect_anomaly"], "required_steps": ["resolve_metric", "check_data_quality", "query_metric", "compare_periods", "calculate_contribution", "detect_anomaly", "compose_answer"], "required_evidence": ["metric_resolution", "data_quality", "metric_value", "metric_totals", "period_comparison", "contribution", "anomaly"], "expected_values": {"answer.columns": ["calendar.month", "priority", "ticket_volume"], "answer.rows": [["2024-02", "P1", 6], ["2024-02", "P2", 8], ["2024-02", "P3", 17], ["2024-03", "P1", 6], ["2024-03", "P2", 18], ["2024-03", "P3", 8]], "answer.diagnosis.contributions.ticket_volume.independent_baseline": 31, "answer.diagnosis.contributions.ticket_volume.independent_current": 32, "answer.diagnosis.contributions.ticket_volume.total_delta": 1, "answer.diagnosis.contributions.ticket_volume.residual": 0, "answer.diagnosis.contributions.ticket_volume.residual_current": 0, "answer.diagnosis.contributions.ticket_volume.residual_baseline": 0, "answer.diagnosis.contributions.ticket_volume.residual_explained": true, "answer.diagnosis.interpretation": "arithmetic_decomposition_not_causal_attribution", "answer.diagnosis.period_completeness": "unverified", "final_answer.status": "success"}, "result_contract": {"required_columns": ["calendar.month", "priority", "ticket_volume"], "columns_path": "answer.columns", "rows_path": "answer.rows", "row_order": "ordered", "empty": "forbid"}, "values_absolute_tolerance": {"answer.diagnosis.contributions.ticket_volume.residual": 1e-09, "answer.diagnosis.contributions.ticket_volume.residual_current": 1e-09, "answer.diagnosis.contributions.ticket_volume.residual_baseline": 1e-09}, "answer_must_reference_evidence": true, "reference_sql": "SELECT printf('%04d-%02d', created_date_key/10000, created_date_key/100%100) AS \"calendar.month\", priority, COUNT(DISTINCT ticket_id) AS ticket_volume FROM fact_ticket WHERE created_date_key/100 IN (202402, 202403) GROUP BY 1,2 ORDER BY 1,2", "totals_reference_sql": "SELECT created_date_key/100 AS period, COUNT(DISTINCT ticket_id) AS value FROM fact_ticket WHERE created_date_key/100 IN (202402, 202403) GROUP BY 1 ORDER BY 1", "oracle_path": "answer.rows", "max_tool_calls": 40, "notes": "Independent base-table SQL; no compiler or generated outputs are used to freeze expected values. Anomaly history has only two points and must be reported as insufficient_data."} diff --git a/evaluation/diagnostics/regression.jsonl b/evaluation/diagnostics/regression.jsonl new file mode 100644 index 0000000..0fdbc67 --- /dev/null +++ b/evaluation/diagnostics/regression.jsonl @@ -0,0 +1 @@ +{"task_id": "retail_orders_regression_diagnostic", "split": "regression", "dataset": "retail_orders", "template_id": "retail_orders_diagnostic_sales_channel", "question": "Explain net revenue monthly for March 2024 month over month by sales channel", "runner": "planner", "coverage": ["business_diagnosis", "time_category_grain", "independent_reconciliation", "required_projection"], "expected_outcome": "analysis", "expected_status": ["succeeded"], "allowed_tools": ["resolve_metric", "check_data_quality", "execute_sql", "compare_periods", "calculate_contribution", "detect_anomaly"], "required_steps": ["resolve_metric", "check_data_quality", "query_metric", "compare_periods", "calculate_contribution", "detect_anomaly", "compose_answer"], "required_evidence": ["metric_resolution", "data_quality", "metric_value", "metric_totals", "period_comparison", "contribution", "anomaly"], "expected_values": {"answer.columns": ["calendar.month", "sales_channel", "net_revenue"], "answer.rows": [["2024-02", "App", 3651.96], ["2024-02", "In-Store", 3735.51], ["2024-02", "Web", 4684.49], ["2024-03", "App", 3836.1], ["2024-03", "In-Store", 3640.57], ["2024-03", "Web", 3315.24]], "answer.diagnosis.contributions.net_revenue.independent_baseline": 12071.960000000001, "answer.diagnosis.contributions.net_revenue.independent_current": 10791.91, "answer.diagnosis.contributions.net_revenue.total_delta": -1280.050000000001, "answer.diagnosis.contributions.net_revenue.residual": 0, "answer.diagnosis.contributions.net_revenue.residual_current": 0, "answer.diagnosis.contributions.net_revenue.residual_baseline": 0, "answer.diagnosis.contributions.net_revenue.residual_explained": true, "answer.diagnosis.interpretation": "arithmetic_decomposition_not_causal_attribution", "answer.diagnosis.period_completeness": "unverified", "final_answer.status": "success"}, "result_contract": {"required_columns": ["calendar.month", "sales_channel", "net_revenue"], "columns_path": "answer.columns", "rows_path": "answer.rows", "row_order": "ordered", "empty": "forbid"}, "values_absolute_tolerance": {"answer.diagnosis.contributions.net_revenue.residual": 1e-09, "answer.diagnosis.contributions.net_revenue.residual_current": 1e-09, "answer.diagnosis.contributions.net_revenue.residual_baseline": 1e-09}, "answer_must_reference_evidence": true, "reference_sql": "SELECT printf('%04d-%02d', order_date_key/10000, order_date_key/100%100) AS \"calendar.month\", sales_channel, SUM(net_amount_usd) AS net_revenue FROM fact_order WHERE order_date_key/100 IN (202402, 202403) GROUP BY 1,2 ORDER BY 1,2", "totals_reference_sql": "SELECT order_date_key/100 AS period, SUM(net_amount_usd) AS value FROM fact_order WHERE order_date_key/100 IN (202402, 202403) GROUP BY 1 ORDER BY 1", "oracle_path": "answer.rows", "max_tool_calls": 40, "notes": "Independent base-table SQL; no compiler or generated outputs are used to freeze expected values. Anomaly history has only two points and must be reported as insufficient_data."} diff --git a/evaluation/live_tasks/README.md b/evaluation/live_tasks/README.md new file mode 100644 index 0000000..e04b50f --- /dev/null +++ b/evaluation/live_tasks/README.md @@ -0,0 +1,33 @@ +# Live paired tasks, v1 + +These 23 workflow tasks cover the same three schemas and unchanged reference +SQL/data as the original control-flow fixtures in `evaluation/tasks/`. The +original fixtures and thresholds remain unchanged. + +The first DeepSeek preflight exposed a question/oracle mismatch: “List playback +devices” does not ask for the count column frozen in its reference SQL. These +live questions state every requested measure, limit, ordering and column name. +Each task declares its full result projection, outer row order and empty policy. +The reference SQL is evaluator input; it is never supplied to the real model. + +```bash +.venv/bin/python -B scripts/freeze_live_tasks.py --check +LOG_LEVEL=CRITICAL .venv/bin/python -B scripts/run_paired_benchmark.py --tier 3 \ + --provider deepseek --model deepseek-flash --tasks-dir evaluation/live_tasks \ + --feature candidates --repeat 5 --dry-run --report /tmp/live-candidates-manifest.json +``` + +`freeze_live_tasks.py` independently executes the unchanged SQL read-only, +checks its values against the original frozen rows, and audits split/schema +isolation before writing. Review question and output-contract changes as gold +changes, rather than changing reference SQL to match a model's answer. + +An offline scripted run can fail these tasks: explicit business language may +activate existing metric gates or the deterministic multi-metric route. Those +refusals are product behavior to investigate; they do not justify removing a +task, relaxing a result contract or labelling the refusal a model error. +This small curated set does not establish population generalization, and its +end-to-end task pass rate is not SQL-generation accuracy alone. + +Real evaluations require an authorized, funded account. Measured usage and +cached-input pricing must be separated from estimated tokens and invoices. diff --git a/evaluation/live_tasks/dev.jsonl b/evaluation/live_tasks/dev.jsonl new file mode 100644 index 0000000..5a773b1 --- /dev/null +++ b/evaluation/live_tasks/dev.jsonl @@ -0,0 +1,6 @@ +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["simple_single_table"], "dataset": "anime_streaming", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["dim_user"], "expected_values": {"columns": ["n"], "rows": [[6000]]}, "forbidden_claims": [], "forbidden_evidence": [], "max_tool_calls": 4, "notes": "Live v1: explicit question/output contract; unchanged source reference SQL and data. Independent read-only SQLite oracle; original fixture retained.", "question": "How many user accounts are stored? Return a single column named n.", "reference_sql": "SELECT COUNT(*) AS n FROM dim_user", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "forbid", "required_columns": ["n"], "row_order": "multiset"}, "runner": "scripted_workflow", "split": "dev", "task_id": "live_anime_streaming_dev_1", "template_id": "live_v1_anime_streaming_sql_0", "values_absolute_tolerance": {}, "values_tolerance": {}} +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["simple_single_table"], "dataset": "anime_streaming", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["fact_watch_session"], "expected_values": {"columns": ["device_type", "n"], "rows": [["Console", 30000], ["Mobile", 30000], ["TV", 30000], ["Tablet", 30000], ["Web", 30000]]}, "forbidden_claims": [], "forbidden_evidence": [], "max_tool_calls": 4, "notes": "Live v1: explicit question/output contract; unchanged source reference SQL and data. Independent read-only SQLite oracle; original fixture retained.", "question": "For each playback device type, show its total number of watch sessions over all stored dates. Return device_type and n, sorted by device_type.", "reference_sql": "SELECT device_type, COUNT(*) AS n FROM fact_watch_session GROUP BY device_type ORDER BY device_type", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "forbid", "required_columns": ["device_type", "n"], "row_order": "ordered"}, "runner": "scripted_workflow", "split": "dev", "task_id": "live_anime_streaming_dev_2", "template_id": "live_v1_anime_streaming_sql_1", "values_absolute_tolerance": {}, "values_tolerance": {}} +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["simple_single_table"], "dataset": "anime_streaming", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["dim_user"], "expected_values": {"columns": ["country", "n"], "rows": [["Brazil", 750], ["Canada", 750], ["France", 750], ["Germany", 750], ["Indonesia", 750], ["Japan", 750], ["Mexico", 750], ["United States", 750]]}, "forbidden_claims": [], "forbidden_evidence": [], "max_tool_calls": 4, "notes": "Live v1: explicit question/output contract; unchanged source reference SQL and data. Independent read-only SQLite oracle; original fixture retained.", "question": "Count user accounts by country, including every country. Return country and n, sorted by country.", "reference_sql": "SELECT country, COUNT(*) AS n FROM dim_user GROUP BY country ORDER BY country", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "forbid", "required_columns": ["country", "n"], "row_order": "ordered"}, "runner": "scripted_workflow", "split": "dev", "task_id": "live_anime_streaming_dev_3", "template_id": "live_v1_anime_streaming_sql_2", "values_absolute_tolerance": {}, "values_tolerance": {}} +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["simple_single_table"], "dataset": "anime_streaming", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["dim_episode"], "expected_values": {"columns": ["n"], "rows": [[1]]}, "forbidden_claims": [], "forbidden_evidence": [], "max_tool_calls": 4, "notes": "Live v1: explicit question/output contract; unchanged source reference SQL and data. Independent read-only SQLite oracle; original fixture retained.", "question": "What is the smallest stored episode identifier? Return one column named n.", "reference_sql": "SELECT MIN(episode_id) AS n FROM dim_episode", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "forbid", "required_columns": ["n"], "row_order": "multiset"}, "runner": "scripted_workflow", "split": "dev", "task_id": "live_anime_streaming_dev_4", "template_id": "live_v1_anime_streaming_sql_3", "values_absolute_tolerance": {}, "values_tolerance": {}} +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["empty_result"], "dataset": "anime_streaming", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["dim_user"], "expected_values": {"columns": ["user_id"], "rows": []}, "forbidden_claims": [], "forbidden_evidence": [], "max_tool_calls": 4, "notes": "Live v1: explicit question/output contract; unchanged source reference SQL and data. Independent read-only SQLite oracle; original fixture retained.", "question": "Return the identifier of the user whose user identifier is -1, if any. Return only user_id.", "reference_sql": "SELECT user_id FROM dim_user WHERE user_id = -1", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "allow", "required_columns": ["user_id"], "row_order": "multiset"}, "runner": "scripted_workflow", "split": "dev", "task_id": "live_anime_streaming_dev_5", "template_id": "live_v1_anime_streaming_sql_4", "values_absolute_tolerance": {}, "values_tolerance": {}} +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["simple_single_table"], "dataset": "anime_streaming", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["dim_studio"], "expected_values": {"columns": ["n"], "rows": [[48]]}, "forbidden_claims": [], "forbidden_evidence": [], "max_tool_calls": 4, "notes": "Live v1: explicit question/output contract; unchanged source reference SQL and data. Independent read-only SQLite oracle; original fixture retained.", "question": "What is the largest stored studio identifier? Return one column named n.", "reference_sql": "SELECT MAX(studio_id) AS n FROM dim_studio", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "forbid", "required_columns": ["n"], "row_order": "multiset"}, "runner": "scripted_workflow", "split": "dev", "task_id": "live_anime_streaming_dev_6", "template_id": "live_v1_anime_streaming_sql_5", "values_absolute_tolerance": {}, "values_tolerance": {}} diff --git a/evaluation/live_tasks/holdout.jsonl b/evaluation/live_tasks/holdout.jsonl new file mode 100644 index 0000000..49db4b6 --- /dev/null +++ b/evaluation/live_tasks/holdout.jsonl @@ -0,0 +1,6 @@ +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["simple_single_table"], "dataset": "support_tickets", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["fact_ticket"], "expected_values": {"columns": ["n"], "rows": [[420]]}, "forbidden_claims": [], "forbidden_evidence": [], "holdout_fingerprint": "d03e0faa50610f19c3cbf4165e4e1aeee6658289f1904f2def21ac2e5719d995", "max_tool_calls": 4, "notes": "Live v1: explicit question/output contract; unchanged source reference SQL and data. Independent read-only SQLite oracle; original fixture retained.", "question": "How many support case records are stored? Return one column named n.", "reference_sql": "SELECT COUNT(*) AS n FROM fact_ticket", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "forbid", "required_columns": ["n"], "row_order": "multiset"}, "runner": "scripted_workflow", "split": "holdout", "task_id": "live_support_tickets_holdout_1", "template_id": "live_v1_support_tickets_sql_0", "values_absolute_tolerance": {}, "values_tolerance": {}} +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["simple_single_table"], "dataset": "support_tickets", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["fact_ticket"], "expected_values": {"columns": ["priority", "n"], "rows": [["P1", 57], ["P2", 187], ["P3", 176]]}, "forbidden_claims": [], "forbidden_evidence": [], "holdout_fingerprint": "94750863e6fc5d44b52ad2634f8b3d4a873ac9a6f7a18ae591295bfb27377d60", "max_tool_calls": 4, "notes": "Live v1: explicit question/output contract; unchanged source reference SQL and data. Independent read-only SQLite oracle; original fixture retained.", "question": "Count all stored support cases by priority. Return priority and n, sorted by priority.", "reference_sql": "SELECT priority,COUNT(*) AS n FROM fact_ticket GROUP BY priority ORDER BY priority", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "forbid", "required_columns": ["priority", "n"], "row_order": "ordered"}, "runner": "scripted_workflow", "split": "holdout", "task_id": "live_support_tickets_holdout_2", "template_id": "live_v1_support_tickets_sql_1", "values_absolute_tolerance": {}, "values_tolerance": {}} +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["multi_table_join"], "dataset": "support_tickets", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["dim_queue", "fact_ticket"], "expected_values": {"columns": ["queue_name", "n"], "rows": [["Account Chat", 43], ["Account Phone", 35], ["Billing Email", 28], ["Billing Phone", 27], ["Content Email", 25], ["Devices Chat", 37], ["Devices Email", 41], ["Devices Phone", 40], ["Payments Chat", 39], ["Payments Email", 42], ["Subscriptions Chat", 24], ["Subscriptions Email", 39]]}, "forbidden_claims": [], "forbidden_evidence": [], "holdout_fingerprint": "99ed6764e91ecc6f9dd82abad41022eb4f2afdba0f15dca180d6e669575ad00d", "max_tool_calls": 4, "notes": "Live v1: explicit question/output contract; unchanged source reference SQL and data. Independent read-only SQLite oracle; original fixture retained.", "question": "For each support queue with at least one recorded case, show the queue name and number of cases. Return queue_name and n, sorted by queue_name.", "reference_sql": "SELECT q.queue_name,COUNT(t.ticket_id) AS n FROM dim_queue q JOIN fact_ticket t ON t.queue_id=q.queue_id GROUP BY q.queue_name ORDER BY q.queue_name", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "forbid", "required_columns": ["queue_name", "n"], "row_order": "ordered"}, "runner": "scripted_workflow", "split": "holdout", "task_id": "live_support_tickets_holdout_3", "template_id": "live_v1_support_tickets_sql_2", "values_absolute_tolerance": {}, "values_tolerance": {}} +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["data_fault"], "dataset": "support_tickets", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["fact_csat_response"], "expected_values": {"columns": ["n"], "rows": [[126]]}, "forbidden_claims": [], "forbidden_evidence": [], "holdout_fingerprint": "e282d4612557cc8bc617a96b061384b5d5681c5b9272eaa6341ba9a21254c3b7", "max_tool_calls": 4, "notes": "Live v1: explicit question/output contract; unchanged source reference SQL and data. Independent read-only SQLite oracle; original fixture retained.", "question": "How many stored customer satisfaction survey responses have a NULL score? Return one column named n.", "reference_sql": "SELECT COUNT(*) AS n FROM fact_csat_response WHERE csat_score IS NULL", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "forbid", "required_columns": ["n"], "row_order": "multiset"}, "runner": "scripted_workflow", "split": "holdout", "task_id": "live_support_tickets_holdout_4", "template_id": "live_v1_support_tickets_sql_3", "values_absolute_tolerance": {}, "values_tolerance": {}} +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["empty_result"], "dataset": "support_tickets", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["fact_ticket_sla_breach"], "expected_values": {"columns": ["breach_id"], "rows": []}, "forbidden_claims": [], "forbidden_evidence": [], "holdout_fingerprint": "1ba8fb8c47ce824ea5d761077eaca74f4c9fea9e51864d927f809ce9902603fc", "max_tool_calls": 4, "notes": "Live v1: explicit question/output contract; unchanged source reference SQL and data. Independent read-only SQLite oracle; original fixture retained.", "question": "List the identifiers of all recorded SLA breaches. Return only breach_id.", "reference_sql": "SELECT breach_id FROM fact_ticket_sla_breach", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "allow", "required_columns": ["breach_id"], "row_order": "multiset"}, "runner": "scripted_workflow", "split": "holdout", "task_id": "live_support_tickets_holdout_5", "template_id": "live_v1_support_tickets_sql_4", "values_absolute_tolerance": {}, "values_tolerance": {}} +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["simple_single_table"], "dataset": "support_tickets", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["fact_ticket"], "expected_values": {"columns": ["n"], "rows": [[37]]}, "forbidden_claims": [], "forbidden_evidence": [], "holdout_fingerprint": "bb358c46c7c864f1a3e5af3e437fee498117672cb5d036c5e1a6d755c14a8c2b", "max_tool_calls": 4, "notes": "Live v1: explicit question/output contract; unchanged source reference SQL and data. Independent read-only SQLite oracle; original fixture retained.", "question": "How many support cases have been reopened? Count cases whose reopened flag is 1 and return one column named n.", "reference_sql": "SELECT SUM(reopened_flag) AS n FROM fact_ticket", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "forbid", "required_columns": ["n"], "row_order": "multiset"}, "runner": "scripted_workflow", "split": "holdout", "task_id": "live_support_tickets_holdout_6", "template_id": "live_v1_support_tickets_sql_5", "values_absolute_tolerance": {}, "values_tolerance": {}} diff --git a/evaluation/live_tasks/regression.jsonl b/evaluation/live_tasks/regression.jsonl new file mode 100644 index 0000000..24f0e76 --- /dev/null +++ b/evaluation/live_tasks/regression.jsonl @@ -0,0 +1,11 @@ +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["simple_single_table"], "dataset": "retail_orders", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["fact_order"], "expected_values": {"columns": ["n"], "rows": [[480]]}, "forbidden_claims": [], "forbidden_evidence": [], "max_tool_calls": 4, "notes": "Live v1: explicit question/output contract; unchanged source reference SQL and data. Independent read-only SQLite oracle; original fixture retained.", "question": "How many order records are stored? Return one column named n.", "reference_sql": "SELECT COUNT(*) AS n FROM fact_order", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "forbid", "required_columns": ["n"], "row_order": "multiset"}, "runner": "scripted_workflow", "split": "regression", "task_id": "live_retail_orders_regression_1", "template_id": "live_v1_retail_orders_sql_0", "values_absolute_tolerance": {}, "values_tolerance": {}} +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["time_range"], "dataset": "retail_orders", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["fact_order"], "expected_values": {"columns": ["first_day", "last_day"], "rows": [[20240101, 20241231]]}, "forbidden_claims": [], "forbidden_evidence": [], "max_tool_calls": 4, "notes": "Live v1: explicit question/output contract; unchanged source reference SQL and data. Independent read-only SQLite oracle; original fixture retained.", "question": "Show the earliest and latest recorded receipt calendar keys. Return first_day and last_day in one row.", "reference_sql": "SELECT MIN(order_date_key) AS first_day,MAX(order_date_key) AS last_day FROM fact_order", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "forbid", "required_columns": ["first_day", "last_day"], "row_order": "multiset"}, "runner": "scripted_workflow", "split": "regression", "task_id": "live_retail_orders_regression_10", "template_id": "live_v1_retail_orders_sql_9", "values_absolute_tolerance": {}, "values_tolerance": {}} +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["multi_table_join"], "dataset": "retail_orders", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["dim_store", "fact_order"], "expected_values": {"columns": ["region", "amount"], "rows": [["Central", 42336.18], ["East", 28358.58], ["South", 48709.86], ["West", 46055.53]]}, "forbidden_claims": [], "forbidden_evidence": [], "max_tool_calls": 4, "notes": "Live v1: explicit question/output contract; unchanged source reference SQL and data. Independent read-only SQLite oracle; original fixture retained.", "question": "Show the total net receipt amount in USD for each store region over all stored dates. Return region and amount, sorted by region.", "reference_sql": "SELECT s.region, SUM(o.net_amount_usd) AS amount FROM fact_order o JOIN dim_store s ON s.store_id=o.store_id GROUP BY s.region ORDER BY s.region", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "forbid", "required_columns": ["region", "amount"], "row_order": "ordered"}, "runner": "scripted_workflow", "split": "regression", "task_id": "live_retail_orders_regression_2", "template_id": "live_v1_retail_orders_sql_1", "values_absolute_tolerance": {}, "values_tolerance": {}} +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["cte"], "dataset": "retail_orders", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["fact_order_item"], "expected_values": {"columns": ["n"], "rows": [[1214]]}, "forbidden_claims": [], "forbidden_evidence": [], "max_tool_calls": 4, "notes": "Live v1: explicit question/output contract; unchanged source reference SQL and data. Independent read-only SQLite oracle; original fixture retained.", "question": "Using a CTE, count all recorded receipt line items across all orders. Return one column named n.", "reference_sql": "WITH counts AS (SELECT order_id, COUNT(*) AS n FROM fact_order_item GROUP BY order_id) SELECT SUM(n) AS n FROM counts", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "forbid", "required_columns": ["n"], "row_order": "multiset"}, "runner": "scripted_workflow", "split": "regression", "task_id": "live_retail_orders_regression_3", "template_id": "live_v1_retail_orders_sql_2", "values_absolute_tolerance": {}, "values_tolerance": {}} +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["window"], "dataset": "retail_orders", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["dim_store"], "expected_values": {"columns": ["store_id", "position"], "rows": [[1, 23], [2, 21], [3, 19], [4, 17], [5, 15], [6, 13], [7, 11], [8, 9], [9, 8], [10, 7], [11, 6], [12, 5], [13, 4], [14, 3], [15, 2], [16, 1], [17, 24], [18, 22], [19, 20], [20, 18], [21, 16], [22, 14], [23, 12], [24, 10]]}, "forbidden_claims": [], "forbidden_evidence": [], "max_tool_calls": 4, "notes": "Live v1: explicit question/output contract; unchanged source reference SQL and data. Independent read-only SQLite oracle; original fixture retained.", "question": "For every outlet, return store_id and its position using dense rank by floor area, with the largest area ranked first. Include all outlets and sort the output by store_id.", "reference_sql": "SELECT store_id, DENSE_RANK() OVER (ORDER BY floor_area_sqm DESC) AS position FROM dim_store ORDER BY store_id", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "forbid", "required_columns": ["store_id", "position"], "row_order": "ordered"}, "runner": "scripted_workflow", "split": "regression", "task_id": "live_retail_orders_regression_4", "template_id": "live_v1_retail_orders_sql_3", "values_absolute_tolerance": {}, "values_tolerance": {}} +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["time_range"], "dataset": "retail_orders", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["fact_order"], "expected_values": {"columns": ["n"], "rows": [[96]]}, "forbidden_claims": [], "forbidden_evidence": [], "max_tool_calls": 4, "notes": "Live v1: explicit question/output contract; unchanged source reference SQL and data. Independent read-only SQLite oracle; original fixture retained.", "question": "Count receipt records with order dates from January 1 through March 31, 2024 inclusive. Return one column named n.", "reference_sql": "SELECT COUNT(*) AS n FROM fact_order WHERE order_date_key >= 20240101 AND order_date_key < 20240401", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "forbid", "required_columns": ["n"], "row_order": "multiset"}, "runner": "scripted_workflow", "split": "regression", "task_id": "live_retail_orders_regression_5", "template_id": "live_v1_retail_orders_sql_4", "values_absolute_tolerance": {}, "values_tolerance": {}} +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["multi_fact"], "dataset": "retail_orders", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["fact_order", "fact_order_item"], "expected_values": {"columns": ["orders", "lines"], "rows": [[480, 1214]]}, "forbidden_claims": [], "forbidden_evidence": [], "max_tool_calls": 4, "notes": "Live v1: explicit question/output contract; unchanged source reference SQL and data. Independent read-only SQLite oracle; original fixture retained.", "question": "Count receipt records and receipt line records independently so that joining them does not inflate either count. Return orders and lines, in that order.", "reference_sql": "SELECT (SELECT COUNT(*) FROM fact_order) AS orders, (SELECT COUNT(*) FROM fact_order_item) AS lines", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "forbid", "required_columns": ["orders", "lines"], "row_order": "multiset"}, "runner": "scripted_workflow", "split": "regression", "task_id": "live_retail_orders_regression_6", "template_id": "live_v1_retail_orders_sql_5", "values_absolute_tolerance": {}, "values_tolerance": {}} +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["simple_single_table"], "dataset": "retail_orders", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["fact_order"], "expected_values": {"columns": ["order_id", "net_amount_usd"], "rows": [[14, 1099.89], [289, 1075.9], [41, 1032.51]]}, "forbidden_claims": [], "forbidden_evidence": [], "max_tool_calls": 4, "notes": "Live v1: explicit question/output contract; unchanged source reference SQL and data. Independent read-only SQLite oracle; original fixture retained.", "question": "Show the three receipts with the largest net amounts. Return order_id and net_amount_usd, sorted by net_amount_usd descending, then order_id ascending for ties.", "reference_sql": "SELECT order_id, net_amount_usd FROM fact_order ORDER BY net_amount_usd DESC, order_id LIMIT 3", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "forbid", "required_columns": ["order_id", "net_amount_usd"], "row_order": "ordered"}, "runner": "scripted_workflow", "split": "regression", "task_id": "live_retail_orders_regression_7", "template_id": "live_v1_retail_orders_sql_6", "values_absolute_tolerance": {}, "values_tolerance": {}} +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["simple_single_table"], "dataset": "retail_orders", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["fact_order"], "expected_values": {"columns": ["n"], "rows": [[4]]}, "forbidden_claims": [], "forbidden_evidence": [], "max_tool_calls": 4, "notes": "Live v1: explicit question/output contract; unchanged source reference SQL and data. Independent read-only SQLite oracle; original fixture retained.", "question": "How many distinct payment methods occur in the stored receipts? Return one column named n.", "reference_sql": "SELECT COUNT(DISTINCT payment_method) AS n FROM fact_order", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "forbid", "required_columns": ["n"], "row_order": "multiset"}, "runner": "scripted_workflow", "split": "regression", "task_id": "live_retail_orders_regression_8", "template_id": "live_v1_retail_orders_sql_7", "values_absolute_tolerance": {}, "values_tolerance": {}} +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["empty_result"], "dataset": "retail_orders", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["dim_store"], "expected_values": {"columns": ["store_id"], "rows": []}, "forbidden_claims": [], "forbidden_evidence": [], "max_tool_calls": 4, "notes": "Live v1: explicit question/output contract; unchanged source reference SQL and data. Independent read-only SQLite oracle; original fixture retained.", "question": "Return the identifier of the store whose store identifier is -100, if any. Return only store_id.", "reference_sql": "SELECT store_id FROM dim_store WHERE store_id = -100", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "allow", "required_columns": ["store_id"], "row_order": "multiset"}, "runner": "scripted_workflow", "split": "regression", "task_id": "live_retail_orders_regression_9", "template_id": "live_v1_retail_orders_sql_8", "values_absolute_tolerance": {}, "values_tolerance": {}} +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["follow_up_multi_turn"], "dataset": "retail_orders", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["fact_order"], "expected_values": {"columns": ["order_count"], "rows": [[480]]}, "follow_up_context": ["How many distinct orders are stored? Return one column named order_count."], "forbidden_claims": [], "forbidden_evidence": [], "max_tool_calls": 8, "notes": "Live v1: explicit question/output contract; unchanged source reference SQL and data. Independent read-only SQLite oracle; original fixture retained.", "question": "再查询一次刚才的订单数量,仍只返回 order_count 列。", "reference_sql": "SELECT COUNT(DISTINCT fact_order.order_id) AS order_count FROM fact_order", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "forbid", "required_columns": ["order_count"], "row_order": "multiset"}, "runner": "scripted_workflow", "split": "regression", "task_id": "live_retail_orders_regression_followup", "template_id": "live_v1_retail_followup", "values_absolute_tolerance": {}, "values_tolerance": {}} diff --git a/evaluation/live_tasks_v2/README.md b/evaluation/live_tasks_v2/README.md new file mode 100644 index 0000000..c94c752 --- /dev/null +++ b/evaluation/live_tasks_v2/README.md @@ -0,0 +1,37 @@ +# Live tasks v2: source-aware post-hoc contracts + +These are the same 23 questions, reference SQL, databases and output contracts +as [live v1](../live_tasks/README.md). No new model generation is involved. +`required_sql_tables` adds an independent physical-source coverage check to +saved traces. This rule was added after inspecting v1 model outputs; scores +under it are **post-hoc audit results**, not a prespecified new paid experiment. +The original reports and verdicts must be retained. + +The ranking question retains a known v1 ambiguity: "outlet" can denote the +specific `store_format='Outlet'`, while the reference SQL ranks all stores. +Report the full scores and a separate sensitivity analysis excluding this one +task with an explicit reason. Do not silently remove it or blame the model for +that interpretation. [Live v3](../live_tasks_v3/README.md) corrects the wording +for future generation; no v3 live results are claimed. + +```bash +.venv/bin/python -B scripts/freeze_live_tasks.py --source-contract --check +.venv/bin/python -B scripts/freeze_live_tasks.py --check +``` + +Coverage follows selected SQLGlot scopes, including active CTEs, derived tables, +scalar subqueries and set-operation branches. An unused CTE and a table alias +cannot establish a required physical table. Missing SQL and unsupported shapes +are unverified. This version supports ASCII SQLite identifiers in the main +namespace; other namespaces, recursive CTEs and source functions are unverified. + +Source coverage is necessary but insufficient for semantic correctness: it does +not prove the right filter, join, grain or metric expression. It does not change +production runtime policy or its SQL execution boundary. + +`scripts/audit_paired_benchmark.py` first reproduces every original verdict, +verifies manifest/gold completeness and reconciles numeric provider usage. +It then reports the additional source contract separately, preserves both +verdicts and records input/scoring hashes. It refuses to overwrite a report, +and has no model/network execution path. Cost is priced measured usage, with +unknown costs left null; prices must match the model and frozen time window. diff --git a/evaluation/live_tasks_v2/dev.jsonl b/evaluation/live_tasks_v2/dev.jsonl new file mode 100644 index 0000000..5d40acd --- /dev/null +++ b/evaluation/live_tasks_v2/dev.jsonl @@ -0,0 +1,6 @@ +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["simple_single_table"], "dataset": "anime_streaming", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["dim_user"], "expected_values": {"columns": ["n"], "rows": [[6000]]}, "forbidden_claims": [], "forbidden_evidence": [], "max_tool_calls": 4, "notes": "Live v2: unchanged v1 question, reference SQL, data and output contract; adds independent physical source coverage for post-hoc trace auditing.", "question": "How many user accounts are stored? Return a single column named n.", "reference_sql": "SELECT COUNT(*) AS n FROM dim_user", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_sql_tables": ["dim_user"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "forbid", "required_columns": ["n"], "row_order": "multiset"}, "runner": "scripted_workflow", "split": "dev", "task_id": "live_anime_streaming_dev_1", "template_id": "live_v2_anime_streaming_sql_0", "values_absolute_tolerance": {}, "values_tolerance": {}} +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["simple_single_table"], "dataset": "anime_streaming", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["fact_watch_session"], "expected_values": {"columns": ["device_type", "n"], "rows": [["Console", 30000], ["Mobile", 30000], ["TV", 30000], ["Tablet", 30000], ["Web", 30000]]}, "forbidden_claims": [], "forbidden_evidence": [], "max_tool_calls": 4, "notes": "Live v2: unchanged v1 question, reference SQL, data and output contract; adds independent physical source coverage for post-hoc trace auditing.", "question": "For each playback device type, show its total number of watch sessions over all stored dates. Return device_type and n, sorted by device_type.", "reference_sql": "SELECT device_type, COUNT(*) AS n FROM fact_watch_session GROUP BY device_type ORDER BY device_type", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_sql_tables": ["fact_watch_session"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "forbid", "required_columns": ["device_type", "n"], "row_order": "ordered"}, "runner": "scripted_workflow", "split": "dev", "task_id": "live_anime_streaming_dev_2", "template_id": "live_v2_anime_streaming_sql_1", "values_absolute_tolerance": {}, "values_tolerance": {}} +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["simple_single_table"], "dataset": "anime_streaming", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["dim_user"], "expected_values": {"columns": ["country", "n"], "rows": [["Brazil", 750], ["Canada", 750], ["France", 750], ["Germany", 750], ["Indonesia", 750], ["Japan", 750], ["Mexico", 750], ["United States", 750]]}, "forbidden_claims": [], "forbidden_evidence": [], "max_tool_calls": 4, "notes": "Live v2: unchanged v1 question, reference SQL, data and output contract; adds independent physical source coverage for post-hoc trace auditing.", "question": "Count user accounts by country, including every country. Return country and n, sorted by country.", "reference_sql": "SELECT country, COUNT(*) AS n FROM dim_user GROUP BY country ORDER BY country", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_sql_tables": ["dim_user"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "forbid", "required_columns": ["country", "n"], "row_order": "ordered"}, "runner": "scripted_workflow", "split": "dev", "task_id": "live_anime_streaming_dev_3", "template_id": "live_v2_anime_streaming_sql_2", "values_absolute_tolerance": {}, "values_tolerance": {}} +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["simple_single_table"], "dataset": "anime_streaming", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["dim_episode"], "expected_values": {"columns": ["n"], "rows": [[1]]}, "forbidden_claims": [], "forbidden_evidence": [], "max_tool_calls": 4, "notes": "Live v2: unchanged v1 question, reference SQL, data and output contract; adds independent physical source coverage for post-hoc trace auditing.", "question": "What is the smallest stored episode identifier? Return one column named n.", "reference_sql": "SELECT MIN(episode_id) AS n FROM dim_episode", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_sql_tables": ["dim_episode"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "forbid", "required_columns": ["n"], "row_order": "multiset"}, "runner": "scripted_workflow", "split": "dev", "task_id": "live_anime_streaming_dev_4", "template_id": "live_v2_anime_streaming_sql_3", "values_absolute_tolerance": {}, "values_tolerance": {}} +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["empty_result"], "dataset": "anime_streaming", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["dim_user"], "expected_values": {"columns": ["user_id"], "rows": []}, "forbidden_claims": [], "forbidden_evidence": [], "max_tool_calls": 4, "notes": "Live v2: unchanged v1 question, reference SQL, data and output contract; adds independent physical source coverage for post-hoc trace auditing.", "question": "Return the identifier of the user whose user identifier is -1, if any. Return only user_id.", "reference_sql": "SELECT user_id FROM dim_user WHERE user_id = -1", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_sql_tables": ["dim_user"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "allow", "required_columns": ["user_id"], "row_order": "multiset"}, "runner": "scripted_workflow", "split": "dev", "task_id": "live_anime_streaming_dev_5", "template_id": "live_v2_anime_streaming_sql_4", "values_absolute_tolerance": {}, "values_tolerance": {}} +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["simple_single_table"], "dataset": "anime_streaming", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["dim_studio"], "expected_values": {"columns": ["n"], "rows": [[48]]}, "forbidden_claims": [], "forbidden_evidence": [], "max_tool_calls": 4, "notes": "Live v2: unchanged v1 question, reference SQL, data and output contract; adds independent physical source coverage for post-hoc trace auditing.", "question": "What is the largest stored studio identifier? Return one column named n.", "reference_sql": "SELECT MAX(studio_id) AS n FROM dim_studio", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_sql_tables": ["dim_studio"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "forbid", "required_columns": ["n"], "row_order": "multiset"}, "runner": "scripted_workflow", "split": "dev", "task_id": "live_anime_streaming_dev_6", "template_id": "live_v2_anime_streaming_sql_5", "values_absolute_tolerance": {}, "values_tolerance": {}} diff --git a/evaluation/live_tasks_v2/holdout.jsonl b/evaluation/live_tasks_v2/holdout.jsonl new file mode 100644 index 0000000..0a9a747 --- /dev/null +++ b/evaluation/live_tasks_v2/holdout.jsonl @@ -0,0 +1,6 @@ +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["simple_single_table"], "dataset": "support_tickets", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["fact_ticket"], "expected_values": {"columns": ["n"], "rows": [[420]]}, "forbidden_claims": [], "forbidden_evidence": [], "holdout_fingerprint": "d03e0faa50610f19c3cbf4165e4e1aeee6658289f1904f2def21ac2e5719d995", "max_tool_calls": 4, "notes": "Live v2: unchanged v1 question, reference SQL, data and output contract; adds independent physical source coverage for post-hoc trace auditing.", "question": "How many support case records are stored? Return one column named n.", "reference_sql": "SELECT COUNT(*) AS n FROM fact_ticket", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_sql_tables": ["fact_ticket"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "forbid", "required_columns": ["n"], "row_order": "multiset"}, "runner": "scripted_workflow", "split": "holdout", "task_id": "live_support_tickets_holdout_1", "template_id": "live_v2_support_tickets_sql_0", "values_absolute_tolerance": {}, "values_tolerance": {}} +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["simple_single_table"], "dataset": "support_tickets", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["fact_ticket"], "expected_values": {"columns": ["priority", "n"], "rows": [["P1", 57], ["P2", 187], ["P3", 176]]}, "forbidden_claims": [], "forbidden_evidence": [], "holdout_fingerprint": "94750863e6fc5d44b52ad2634f8b3d4a873ac9a6f7a18ae591295bfb27377d60", "max_tool_calls": 4, "notes": "Live v2: unchanged v1 question, reference SQL, data and output contract; adds independent physical source coverage for post-hoc trace auditing.", "question": "Count all stored support cases by priority. Return priority and n, sorted by priority.", "reference_sql": "SELECT priority,COUNT(*) AS n FROM fact_ticket GROUP BY priority ORDER BY priority", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_sql_tables": ["fact_ticket"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "forbid", "required_columns": ["priority", "n"], "row_order": "ordered"}, "runner": "scripted_workflow", "split": "holdout", "task_id": "live_support_tickets_holdout_2", "template_id": "live_v2_support_tickets_sql_1", "values_absolute_tolerance": {}, "values_tolerance": {}} +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["multi_table_join"], "dataset": "support_tickets", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["dim_queue", "fact_ticket"], "expected_values": {"columns": ["queue_name", "n"], "rows": [["Account Chat", 43], ["Account Phone", 35], ["Billing Email", 28], ["Billing Phone", 27], ["Content Email", 25], ["Devices Chat", 37], ["Devices Email", 41], ["Devices Phone", 40], ["Payments Chat", 39], ["Payments Email", 42], ["Subscriptions Chat", 24], ["Subscriptions Email", 39]]}, "forbidden_claims": [], "forbidden_evidence": [], "holdout_fingerprint": "99ed6764e91ecc6f9dd82abad41022eb4f2afdba0f15dca180d6e669575ad00d", "max_tool_calls": 4, "notes": "Live v2: unchanged v1 question, reference SQL, data and output contract; adds independent physical source coverage for post-hoc trace auditing.", "question": "For each support queue with at least one recorded case, show the queue name and number of cases. Return queue_name and n, sorted by queue_name.", "reference_sql": "SELECT q.queue_name,COUNT(t.ticket_id) AS n FROM dim_queue q JOIN fact_ticket t ON t.queue_id=q.queue_id GROUP BY q.queue_name ORDER BY q.queue_name", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_sql_tables": ["dim_queue", "fact_ticket"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "forbid", "required_columns": ["queue_name", "n"], "row_order": "ordered"}, "runner": "scripted_workflow", "split": "holdout", "task_id": "live_support_tickets_holdout_3", "template_id": "live_v2_support_tickets_sql_2", "values_absolute_tolerance": {}, "values_tolerance": {}} +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["data_fault"], "dataset": "support_tickets", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["fact_csat_response"], "expected_values": {"columns": ["n"], "rows": [[126]]}, "forbidden_claims": [], "forbidden_evidence": [], "holdout_fingerprint": "e282d4612557cc8bc617a96b061384b5d5681c5b9272eaa6341ba9a21254c3b7", "max_tool_calls": 4, "notes": "Live v2: unchanged v1 question, reference SQL, data and output contract; adds independent physical source coverage for post-hoc trace auditing.", "question": "How many stored customer satisfaction survey responses have a NULL score? Return one column named n.", "reference_sql": "SELECT COUNT(*) AS n FROM fact_csat_response WHERE csat_score IS NULL", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_sql_tables": ["fact_csat_response"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "forbid", "required_columns": ["n"], "row_order": "multiset"}, "runner": "scripted_workflow", "split": "holdout", "task_id": "live_support_tickets_holdout_4", "template_id": "live_v2_support_tickets_sql_3", "values_absolute_tolerance": {}, "values_tolerance": {}} +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["empty_result"], "dataset": "support_tickets", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["fact_ticket_sla_breach"], "expected_values": {"columns": ["breach_id"], "rows": []}, "forbidden_claims": [], "forbidden_evidence": [], "holdout_fingerprint": "1ba8fb8c47ce824ea5d761077eaca74f4c9fea9e51864d927f809ce9902603fc", "max_tool_calls": 4, "notes": "Live v2: unchanged v1 question, reference SQL, data and output contract; adds independent physical source coverage for post-hoc trace auditing.", "question": "List the identifiers of all recorded SLA breaches. Return only breach_id.", "reference_sql": "SELECT breach_id FROM fact_ticket_sla_breach", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_sql_tables": ["fact_ticket_sla_breach"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "allow", "required_columns": ["breach_id"], "row_order": "multiset"}, "runner": "scripted_workflow", "split": "holdout", "task_id": "live_support_tickets_holdout_5", "template_id": "live_v2_support_tickets_sql_4", "values_absolute_tolerance": {}, "values_tolerance": {}} +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["simple_single_table"], "dataset": "support_tickets", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["fact_ticket"], "expected_values": {"columns": ["n"], "rows": [[37]]}, "forbidden_claims": [], "forbidden_evidence": [], "holdout_fingerprint": "bb358c46c7c864f1a3e5af3e437fee498117672cb5d036c5e1a6d755c14a8c2b", "max_tool_calls": 4, "notes": "Live v2: unchanged v1 question, reference SQL, data and output contract; adds independent physical source coverage for post-hoc trace auditing.", "question": "How many support cases have been reopened? Count cases whose reopened flag is 1 and return one column named n.", "reference_sql": "SELECT SUM(reopened_flag) AS n FROM fact_ticket", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_sql_tables": ["fact_ticket"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "forbid", "required_columns": ["n"], "row_order": "multiset"}, "runner": "scripted_workflow", "split": "holdout", "task_id": "live_support_tickets_holdout_6", "template_id": "live_v2_support_tickets_sql_5", "values_absolute_tolerance": {}, "values_tolerance": {}} diff --git a/evaluation/live_tasks_v2/regression.jsonl b/evaluation/live_tasks_v2/regression.jsonl new file mode 100644 index 0000000..d43b24d --- /dev/null +++ b/evaluation/live_tasks_v2/regression.jsonl @@ -0,0 +1,11 @@ +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["simple_single_table"], "dataset": "retail_orders", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["fact_order"], "expected_values": {"columns": ["n"], "rows": [[480]]}, "forbidden_claims": [], "forbidden_evidence": [], "max_tool_calls": 4, "notes": "Live v2: unchanged v1 question, reference SQL, data and output contract; adds independent physical source coverage for post-hoc trace auditing.", "question": "How many order records are stored? Return one column named n.", "reference_sql": "SELECT COUNT(*) AS n FROM fact_order", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_sql_tables": ["fact_order"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "forbid", "required_columns": ["n"], "row_order": "multiset"}, "runner": "scripted_workflow", "split": "regression", "task_id": "live_retail_orders_regression_1", "template_id": "live_v2_retail_orders_sql_0", "values_absolute_tolerance": {}, "values_tolerance": {}} +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["time_range"], "dataset": "retail_orders", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["fact_order"], "expected_values": {"columns": ["first_day", "last_day"], "rows": [[20240101, 20241231]]}, "forbidden_claims": [], "forbidden_evidence": [], "max_tool_calls": 4, "notes": "Live v2: unchanged v1 question, reference SQL, data and output contract; adds independent physical source coverage for post-hoc trace auditing.", "question": "Show the earliest and latest recorded receipt calendar keys. Return first_day and last_day in one row.", "reference_sql": "SELECT MIN(order_date_key) AS first_day,MAX(order_date_key) AS last_day FROM fact_order", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_sql_tables": ["fact_order"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "forbid", "required_columns": ["first_day", "last_day"], "row_order": "multiset"}, "runner": "scripted_workflow", "split": "regression", "task_id": "live_retail_orders_regression_10", "template_id": "live_v2_retail_orders_sql_9", "values_absolute_tolerance": {}, "values_tolerance": {}} +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["multi_table_join"], "dataset": "retail_orders", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["dim_store", "fact_order"], "expected_values": {"columns": ["region", "amount"], "rows": [["Central", 42336.18], ["East", 28358.58], ["South", 48709.86], ["West", 46055.53]]}, "forbidden_claims": [], "forbidden_evidence": [], "max_tool_calls": 4, "notes": "Live v2: unchanged v1 question, reference SQL, data and output contract; adds independent physical source coverage for post-hoc trace auditing.", "question": "Show the total net receipt amount in USD for each store region over all stored dates. Return region and amount, sorted by region.", "reference_sql": "SELECT s.region, SUM(o.net_amount_usd) AS amount FROM fact_order o JOIN dim_store s ON s.store_id=o.store_id GROUP BY s.region ORDER BY s.region", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_sql_tables": ["dim_store", "fact_order"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "forbid", "required_columns": ["region", "amount"], "row_order": "ordered"}, "runner": "scripted_workflow", "split": "regression", "task_id": "live_retail_orders_regression_2", "template_id": "live_v2_retail_orders_sql_1", "values_absolute_tolerance": {}, "values_tolerance": {}} +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["cte"], "dataset": "retail_orders", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["fact_order_item"], "expected_values": {"columns": ["n"], "rows": [[1214]]}, "forbidden_claims": [], "forbidden_evidence": [], "max_tool_calls": 4, "notes": "Live v2: unchanged v1 question, reference SQL, data and output contract; adds independent physical source coverage for post-hoc trace auditing.", "question": "Using a CTE, count all recorded receipt line items across all orders. Return one column named n.", "reference_sql": "WITH counts AS (SELECT order_id, COUNT(*) AS n FROM fact_order_item GROUP BY order_id) SELECT SUM(n) AS n FROM counts", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_sql_tables": ["fact_order_item"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "forbid", "required_columns": ["n"], "row_order": "multiset"}, "runner": "scripted_workflow", "split": "regression", "task_id": "live_retail_orders_regression_3", "template_id": "live_v2_retail_orders_sql_2", "values_absolute_tolerance": {}, "values_tolerance": {}} +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["window"], "dataset": "retail_orders", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["dim_store"], "expected_values": {"columns": ["store_id", "position"], "rows": [[1, 23], [2, 21], [3, 19], [4, 17], [5, 15], [6, 13], [7, 11], [8, 9], [9, 8], [10, 7], [11, 6], [12, 5], [13, 4], [14, 3], [15, 2], [16, 1], [17, 24], [18, 22], [19, 20], [20, 18], [21, 16], [22, 14], [23, 12], [24, 10]]}, "forbidden_claims": [], "forbidden_evidence": [], "max_tool_calls": 4, "notes": "Live v2: unchanged v1 question, reference SQL, data and output contract; adds independent physical source coverage for post-hoc trace auditing.", "question": "For every outlet, return store_id and its position using dense rank by floor area, with the largest area ranked first. Include all outlets and sort the output by store_id.", "reference_sql": "SELECT store_id, DENSE_RANK() OVER (ORDER BY floor_area_sqm DESC) AS position FROM dim_store ORDER BY store_id", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_sql_tables": ["dim_store"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "forbid", "required_columns": ["store_id", "position"], "row_order": "ordered"}, "runner": "scripted_workflow", "split": "regression", "task_id": "live_retail_orders_regression_4", "template_id": "live_v2_retail_orders_sql_3", "values_absolute_tolerance": {}, "values_tolerance": {}} +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["time_range"], "dataset": "retail_orders", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["fact_order"], "expected_values": {"columns": ["n"], "rows": [[96]]}, "forbidden_claims": [], "forbidden_evidence": [], "max_tool_calls": 4, "notes": "Live v2: unchanged v1 question, reference SQL, data and output contract; adds independent physical source coverage for post-hoc trace auditing.", "question": "Count receipt records with order dates from January 1 through March 31, 2024 inclusive. Return one column named n.", "reference_sql": "SELECT COUNT(*) AS n FROM fact_order WHERE order_date_key >= 20240101 AND order_date_key < 20240401", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_sql_tables": ["fact_order"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "forbid", "required_columns": ["n"], "row_order": "multiset"}, "runner": "scripted_workflow", "split": "regression", "task_id": "live_retail_orders_regression_5", "template_id": "live_v2_retail_orders_sql_4", "values_absolute_tolerance": {}, "values_tolerance": {}} +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["multi_fact"], "dataset": "retail_orders", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["fact_order", "fact_order_item"], "expected_values": {"columns": ["orders", "lines"], "rows": [[480, 1214]]}, "forbidden_claims": [], "forbidden_evidence": [], "max_tool_calls": 4, "notes": "Live v2: unchanged v1 question, reference SQL, data and output contract; adds independent physical source coverage for post-hoc trace auditing.", "question": "Count receipt records and receipt line records independently so that joining them does not inflate either count. Return orders and lines, in that order.", "reference_sql": "SELECT (SELECT COUNT(*) FROM fact_order) AS orders, (SELECT COUNT(*) FROM fact_order_item) AS lines", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_sql_tables": ["fact_order", "fact_order_item"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "forbid", "required_columns": ["orders", "lines"], "row_order": "multiset"}, "runner": "scripted_workflow", "split": "regression", "task_id": "live_retail_orders_regression_6", "template_id": "live_v2_retail_orders_sql_5", "values_absolute_tolerance": {}, "values_tolerance": {}} +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["simple_single_table"], "dataset": "retail_orders", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["fact_order"], "expected_values": {"columns": ["order_id", "net_amount_usd"], "rows": [[14, 1099.89], [289, 1075.9], [41, 1032.51]]}, "forbidden_claims": [], "forbidden_evidence": [], "max_tool_calls": 4, "notes": "Live v2: unchanged v1 question, reference SQL, data and output contract; adds independent physical source coverage for post-hoc trace auditing.", "question": "Show the three receipts with the largest net amounts. Return order_id and net_amount_usd, sorted by net_amount_usd descending, then order_id ascending for ties.", "reference_sql": "SELECT order_id, net_amount_usd FROM fact_order ORDER BY net_amount_usd DESC, order_id LIMIT 3", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_sql_tables": ["fact_order"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "forbid", "required_columns": ["order_id", "net_amount_usd"], "row_order": "ordered"}, "runner": "scripted_workflow", "split": "regression", "task_id": "live_retail_orders_regression_7", "template_id": "live_v2_retail_orders_sql_6", "values_absolute_tolerance": {}, "values_tolerance": {}} +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["simple_single_table"], "dataset": "retail_orders", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["fact_order"], "expected_values": {"columns": ["n"], "rows": [[4]]}, "forbidden_claims": [], "forbidden_evidence": [], "max_tool_calls": 4, "notes": "Live v2: unchanged v1 question, reference SQL, data and output contract; adds independent physical source coverage for post-hoc trace auditing.", "question": "How many distinct payment methods occur in the stored receipts? Return one column named n.", "reference_sql": "SELECT COUNT(DISTINCT payment_method) AS n FROM fact_order", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_sql_tables": ["fact_order"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "forbid", "required_columns": ["n"], "row_order": "multiset"}, "runner": "scripted_workflow", "split": "regression", "task_id": "live_retail_orders_regression_8", "template_id": "live_v2_retail_orders_sql_7", "values_absolute_tolerance": {}, "values_tolerance": {}} +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["empty_result"], "dataset": "retail_orders", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["dim_store"], "expected_values": {"columns": ["store_id"], "rows": []}, "forbidden_claims": [], "forbidden_evidence": [], "max_tool_calls": 4, "notes": "Live v2: unchanged v1 question, reference SQL, data and output contract; adds independent physical source coverage for post-hoc trace auditing.", "question": "Return the identifier of the store whose store identifier is -100, if any. Return only store_id.", "reference_sql": "SELECT store_id FROM dim_store WHERE store_id = -100", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_sql_tables": ["dim_store"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "allow", "required_columns": ["store_id"], "row_order": "multiset"}, "runner": "scripted_workflow", "split": "regression", "task_id": "live_retail_orders_regression_9", "template_id": "live_v2_retail_orders_sql_8", "values_absolute_tolerance": {}, "values_tolerance": {}} +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["follow_up_multi_turn"], "dataset": "retail_orders", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["fact_order"], "expected_values": {"columns": ["order_count"], "rows": [[480]]}, "follow_up_context": ["How many distinct orders are stored? Return one column named order_count."], "forbidden_claims": [], "forbidden_evidence": [], "max_tool_calls": 8, "notes": "Live v2: unchanged v1 question, reference SQL, data and output contract; adds independent physical source coverage for post-hoc trace auditing.", "question": "再查询一次刚才的订单数量,仍只返回 order_count 列。", "reference_sql": "SELECT COUNT(DISTINCT fact_order.order_id) AS order_count FROM fact_order", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_sql_tables": ["fact_order"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "forbid", "required_columns": ["order_count"], "row_order": "multiset"}, "runner": "scripted_workflow", "split": "regression", "task_id": "live_retail_orders_regression_followup", "template_id": "live_v2_retail_followup", "values_absolute_tolerance": {}, "values_tolerance": {}} diff --git a/evaluation/live_tasks_v3/README.md b/evaluation/live_tasks_v3/README.md new file mode 100644 index 0000000..eadf46b --- /dev/null +++ b/evaluation/live_tasks_v3/README.md @@ -0,0 +1,21 @@ +# Live tasks v3: corrected future questions + +This corpus keeps all 23 reference SQL queries, databases, required output +columns and source contracts. Only the store-ranking question changes from +v1/v2: it explicitly requests **every store regardless of store_format**. +The old word "outlet" overlapped the concrete `Outlet` format and could +reasonably imply filtering to that subset, contrary to the all-store oracle. + +```bash +.venv/bin/python -B scripts/freeze_live_tasks.py --correct-questions --check +``` + +Use this corrected corpus for future, separately authorized model runs. No v3 +model outputs were generated during the 2026-10-11 live-v1 experiments. Changing +a question cannot fix or justify regrading an old model answer. The offline +audit therefore rejects any v1/v2 question or result-contract change, retains +the original full scores, and reports a separate sensitivity analysis excluding +the ambiguous ranking task with an explicit rationale. + +As in [live v2](../live_tasks_v2/README.md), the added source rule is a necessary +check, not proof of all SQL semantics, and does not modify runtime policy. diff --git a/evaluation/live_tasks_v3/dev.jsonl b/evaluation/live_tasks_v3/dev.jsonl new file mode 100644 index 0000000..5ceba01 --- /dev/null +++ b/evaluation/live_tasks_v3/dev.jsonl @@ -0,0 +1,6 @@ +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["simple_single_table"], "dataset": "anime_streaming", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["dim_user"], "expected_values": {"columns": ["n"], "rows": [[6000]]}, "forbidden_claims": [], "forbidden_evidence": [], "max_tool_calls": 4, "notes": "Live v3: retains reference SQL, data, output and source contracts; disambiguates store ranking across every store_format. No v3 model results claimed.", "question": "How many user accounts are stored? Return a single column named n.", "reference_sql": "SELECT COUNT(*) AS n FROM dim_user", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_sql_tables": ["dim_user"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "forbid", "required_columns": ["n"], "row_order": "multiset"}, "runner": "scripted_workflow", "split": "dev", "task_id": "live_anime_streaming_dev_1", "template_id": "live_v3_anime_streaming_sql_0", "values_absolute_tolerance": {}, "values_tolerance": {}} +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["simple_single_table"], "dataset": "anime_streaming", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["fact_watch_session"], "expected_values": {"columns": ["device_type", "n"], "rows": [["Console", 30000], ["Mobile", 30000], ["TV", 30000], ["Tablet", 30000], ["Web", 30000]]}, "forbidden_claims": [], "forbidden_evidence": [], "max_tool_calls": 4, "notes": "Live v3: retains reference SQL, data, output and source contracts; disambiguates store ranking across every store_format. No v3 model results claimed.", "question": "For each playback device type, show its total number of watch sessions over all stored dates. Return device_type and n, sorted by device_type.", "reference_sql": "SELECT device_type, COUNT(*) AS n FROM fact_watch_session GROUP BY device_type ORDER BY device_type", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_sql_tables": ["fact_watch_session"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "forbid", "required_columns": ["device_type", "n"], "row_order": "ordered"}, "runner": "scripted_workflow", "split": "dev", "task_id": "live_anime_streaming_dev_2", "template_id": "live_v3_anime_streaming_sql_1", "values_absolute_tolerance": {}, "values_tolerance": {}} +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["simple_single_table"], "dataset": "anime_streaming", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["dim_user"], "expected_values": {"columns": ["country", "n"], "rows": [["Brazil", 750], ["Canada", 750], ["France", 750], ["Germany", 750], ["Indonesia", 750], ["Japan", 750], ["Mexico", 750], ["United States", 750]]}, "forbidden_claims": [], "forbidden_evidence": [], "max_tool_calls": 4, "notes": "Live v3: retains reference SQL, data, output and source contracts; disambiguates store ranking across every store_format. No v3 model results claimed.", "question": "Count user accounts by country, including every country. Return country and n, sorted by country.", "reference_sql": "SELECT country, COUNT(*) AS n FROM dim_user GROUP BY country ORDER BY country", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_sql_tables": ["dim_user"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "forbid", "required_columns": ["country", "n"], "row_order": "ordered"}, "runner": "scripted_workflow", "split": "dev", "task_id": "live_anime_streaming_dev_3", "template_id": "live_v3_anime_streaming_sql_2", "values_absolute_tolerance": {}, "values_tolerance": {}} +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["simple_single_table"], "dataset": "anime_streaming", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["dim_episode"], "expected_values": {"columns": ["n"], "rows": [[1]]}, "forbidden_claims": [], "forbidden_evidence": [], "max_tool_calls": 4, "notes": "Live v3: retains reference SQL, data, output and source contracts; disambiguates store ranking across every store_format. No v3 model results claimed.", "question": "What is the smallest stored episode identifier? Return one column named n.", "reference_sql": "SELECT MIN(episode_id) AS n FROM dim_episode", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_sql_tables": ["dim_episode"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "forbid", "required_columns": ["n"], "row_order": "multiset"}, "runner": "scripted_workflow", "split": "dev", "task_id": "live_anime_streaming_dev_4", "template_id": "live_v3_anime_streaming_sql_3", "values_absolute_tolerance": {}, "values_tolerance": {}} +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["empty_result"], "dataset": "anime_streaming", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["dim_user"], "expected_values": {"columns": ["user_id"], "rows": []}, "forbidden_claims": [], "forbidden_evidence": [], "max_tool_calls": 4, "notes": "Live v3: retains reference SQL, data, output and source contracts; disambiguates store ranking across every store_format. No v3 model results claimed.", "question": "Return the identifier of the user whose user identifier is -1, if any. Return only user_id.", "reference_sql": "SELECT user_id FROM dim_user WHERE user_id = -1", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_sql_tables": ["dim_user"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "allow", "required_columns": ["user_id"], "row_order": "multiset"}, "runner": "scripted_workflow", "split": "dev", "task_id": "live_anime_streaming_dev_5", "template_id": "live_v3_anime_streaming_sql_4", "values_absolute_tolerance": {}, "values_tolerance": {}} +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["simple_single_table"], "dataset": "anime_streaming", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["dim_studio"], "expected_values": {"columns": ["n"], "rows": [[48]]}, "forbidden_claims": [], "forbidden_evidence": [], "max_tool_calls": 4, "notes": "Live v3: retains reference SQL, data, output and source contracts; disambiguates store ranking across every store_format. No v3 model results claimed.", "question": "What is the largest stored studio identifier? Return one column named n.", "reference_sql": "SELECT MAX(studio_id) AS n FROM dim_studio", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_sql_tables": ["dim_studio"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "forbid", "required_columns": ["n"], "row_order": "multiset"}, "runner": "scripted_workflow", "split": "dev", "task_id": "live_anime_streaming_dev_6", "template_id": "live_v3_anime_streaming_sql_5", "values_absolute_tolerance": {}, "values_tolerance": {}} diff --git a/evaluation/live_tasks_v3/holdout.jsonl b/evaluation/live_tasks_v3/holdout.jsonl new file mode 100644 index 0000000..24f7ba2 --- /dev/null +++ b/evaluation/live_tasks_v3/holdout.jsonl @@ -0,0 +1,6 @@ +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["simple_single_table"], "dataset": "support_tickets", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["fact_ticket"], "expected_values": {"columns": ["n"], "rows": [[420]]}, "forbidden_claims": [], "forbidden_evidence": [], "holdout_fingerprint": "d03e0faa50610f19c3cbf4165e4e1aeee6658289f1904f2def21ac2e5719d995", "max_tool_calls": 4, "notes": "Live v3: retains reference SQL, data, output and source contracts; disambiguates store ranking across every store_format. No v3 model results claimed.", "question": "How many support case records are stored? Return one column named n.", "reference_sql": "SELECT COUNT(*) AS n FROM fact_ticket", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_sql_tables": ["fact_ticket"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "forbid", "required_columns": ["n"], "row_order": "multiset"}, "runner": "scripted_workflow", "split": "holdout", "task_id": "live_support_tickets_holdout_1", "template_id": "live_v3_support_tickets_sql_0", "values_absolute_tolerance": {}, "values_tolerance": {}} +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["simple_single_table"], "dataset": "support_tickets", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["fact_ticket"], "expected_values": {"columns": ["priority", "n"], "rows": [["P1", 57], ["P2", 187], ["P3", 176]]}, "forbidden_claims": [], "forbidden_evidence": [], "holdout_fingerprint": "94750863e6fc5d44b52ad2634f8b3d4a873ac9a6f7a18ae591295bfb27377d60", "max_tool_calls": 4, "notes": "Live v3: retains reference SQL, data, output and source contracts; disambiguates store ranking across every store_format. No v3 model results claimed.", "question": "Count all stored support cases by priority. Return priority and n, sorted by priority.", "reference_sql": "SELECT priority,COUNT(*) AS n FROM fact_ticket GROUP BY priority ORDER BY priority", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_sql_tables": ["fact_ticket"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "forbid", "required_columns": ["priority", "n"], "row_order": "ordered"}, "runner": "scripted_workflow", "split": "holdout", "task_id": "live_support_tickets_holdout_2", "template_id": "live_v3_support_tickets_sql_1", "values_absolute_tolerance": {}, "values_tolerance": {}} +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["multi_table_join"], "dataset": "support_tickets", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["dim_queue", "fact_ticket"], "expected_values": {"columns": ["queue_name", "n"], "rows": [["Account Chat", 43], ["Account Phone", 35], ["Billing Email", 28], ["Billing Phone", 27], ["Content Email", 25], ["Devices Chat", 37], ["Devices Email", 41], ["Devices Phone", 40], ["Payments Chat", 39], ["Payments Email", 42], ["Subscriptions Chat", 24], ["Subscriptions Email", 39]]}, "forbidden_claims": [], "forbidden_evidence": [], "holdout_fingerprint": "99ed6764e91ecc6f9dd82abad41022eb4f2afdba0f15dca180d6e669575ad00d", "max_tool_calls": 4, "notes": "Live v3: retains reference SQL, data, output and source contracts; disambiguates store ranking across every store_format. No v3 model results claimed.", "question": "For each support queue with at least one recorded case, show the queue name and number of cases. Return queue_name and n, sorted by queue_name.", "reference_sql": "SELECT q.queue_name,COUNT(t.ticket_id) AS n FROM dim_queue q JOIN fact_ticket t ON t.queue_id=q.queue_id GROUP BY q.queue_name ORDER BY q.queue_name", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_sql_tables": ["dim_queue", "fact_ticket"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "forbid", "required_columns": ["queue_name", "n"], "row_order": "ordered"}, "runner": "scripted_workflow", "split": "holdout", "task_id": "live_support_tickets_holdout_3", "template_id": "live_v3_support_tickets_sql_2", "values_absolute_tolerance": {}, "values_tolerance": {}} +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["data_fault"], "dataset": "support_tickets", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["fact_csat_response"], "expected_values": {"columns": ["n"], "rows": [[126]]}, "forbidden_claims": [], "forbidden_evidence": [], "holdout_fingerprint": "e282d4612557cc8bc617a96b061384b5d5681c5b9272eaa6341ba9a21254c3b7", "max_tool_calls": 4, "notes": "Live v3: retains reference SQL, data, output and source contracts; disambiguates store ranking across every store_format. No v3 model results claimed.", "question": "How many stored customer satisfaction survey responses have a NULL score? Return one column named n.", "reference_sql": "SELECT COUNT(*) AS n FROM fact_csat_response WHERE csat_score IS NULL", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_sql_tables": ["fact_csat_response"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "forbid", "required_columns": ["n"], "row_order": "multiset"}, "runner": "scripted_workflow", "split": "holdout", "task_id": "live_support_tickets_holdout_4", "template_id": "live_v3_support_tickets_sql_3", "values_absolute_tolerance": {}, "values_tolerance": {}} +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["empty_result"], "dataset": "support_tickets", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["fact_ticket_sla_breach"], "expected_values": {"columns": ["breach_id"], "rows": []}, "forbidden_claims": [], "forbidden_evidence": [], "holdout_fingerprint": "1ba8fb8c47ce824ea5d761077eaca74f4c9fea9e51864d927f809ce9902603fc", "max_tool_calls": 4, "notes": "Live v3: retains reference SQL, data, output and source contracts; disambiguates store ranking across every store_format. No v3 model results claimed.", "question": "List the identifiers of all recorded SLA breaches. Return only breach_id.", "reference_sql": "SELECT breach_id FROM fact_ticket_sla_breach", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_sql_tables": ["fact_ticket_sla_breach"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "allow", "required_columns": ["breach_id"], "row_order": "multiset"}, "runner": "scripted_workflow", "split": "holdout", "task_id": "live_support_tickets_holdout_5", "template_id": "live_v3_support_tickets_sql_4", "values_absolute_tolerance": {}, "values_tolerance": {}} +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["simple_single_table"], "dataset": "support_tickets", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["fact_ticket"], "expected_values": {"columns": ["n"], "rows": [[37]]}, "forbidden_claims": [], "forbidden_evidence": [], "holdout_fingerprint": "bb358c46c7c864f1a3e5af3e437fee498117672cb5d036c5e1a6d755c14a8c2b", "max_tool_calls": 4, "notes": "Live v3: retains reference SQL, data, output and source contracts; disambiguates store ranking across every store_format. No v3 model results claimed.", "question": "How many support cases have been reopened? Count cases whose reopened flag is 1 and return one column named n.", "reference_sql": "SELECT SUM(reopened_flag) AS n FROM fact_ticket", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_sql_tables": ["fact_ticket"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "forbid", "required_columns": ["n"], "row_order": "multiset"}, "runner": "scripted_workflow", "split": "holdout", "task_id": "live_support_tickets_holdout_6", "template_id": "live_v3_support_tickets_sql_5", "values_absolute_tolerance": {}, "values_tolerance": {}} diff --git a/evaluation/live_tasks_v3/regression.jsonl b/evaluation/live_tasks_v3/regression.jsonl new file mode 100644 index 0000000..71674d4 --- /dev/null +++ b/evaluation/live_tasks_v3/regression.jsonl @@ -0,0 +1,11 @@ +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["simple_single_table"], "dataset": "retail_orders", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["fact_order"], "expected_values": {"columns": ["n"], "rows": [[480]]}, "forbidden_claims": [], "forbidden_evidence": [], "max_tool_calls": 4, "notes": "Live v3: retains reference SQL, data, output and source contracts; disambiguates store ranking across every store_format. No v3 model results claimed.", "question": "How many order records are stored? Return one column named n.", "reference_sql": "SELECT COUNT(*) AS n FROM fact_order", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_sql_tables": ["fact_order"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "forbid", "required_columns": ["n"], "row_order": "multiset"}, "runner": "scripted_workflow", "split": "regression", "task_id": "live_retail_orders_regression_1", "template_id": "live_v3_retail_orders_sql_0", "values_absolute_tolerance": {}, "values_tolerance": {}} +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["time_range"], "dataset": "retail_orders", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["fact_order"], "expected_values": {"columns": ["first_day", "last_day"], "rows": [[20240101, 20241231]]}, "forbidden_claims": [], "forbidden_evidence": [], "max_tool_calls": 4, "notes": "Live v3: retains reference SQL, data, output and source contracts; disambiguates store ranking across every store_format. No v3 model results claimed.", "question": "Show the earliest and latest recorded receipt calendar keys. Return first_day and last_day in one row.", "reference_sql": "SELECT MIN(order_date_key) AS first_day,MAX(order_date_key) AS last_day FROM fact_order", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_sql_tables": ["fact_order"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "forbid", "required_columns": ["first_day", "last_day"], "row_order": "multiset"}, "runner": "scripted_workflow", "split": "regression", "task_id": "live_retail_orders_regression_10", "template_id": "live_v3_retail_orders_sql_9", "values_absolute_tolerance": {}, "values_tolerance": {}} +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["multi_table_join"], "dataset": "retail_orders", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["dim_store", "fact_order"], "expected_values": {"columns": ["region", "amount"], "rows": [["Central", 42336.18], ["East", 28358.58], ["South", 48709.86], ["West", 46055.53]]}, "forbidden_claims": [], "forbidden_evidence": [], "max_tool_calls": 4, "notes": "Live v3: retains reference SQL, data, output and source contracts; disambiguates store ranking across every store_format. No v3 model results claimed.", "question": "Show the total net receipt amount in USD for each store region over all stored dates. Return region and amount, sorted by region.", "reference_sql": "SELECT s.region, SUM(o.net_amount_usd) AS amount FROM fact_order o JOIN dim_store s ON s.store_id=o.store_id GROUP BY s.region ORDER BY s.region", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_sql_tables": ["dim_store", "fact_order"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "forbid", "required_columns": ["region", "amount"], "row_order": "ordered"}, "runner": "scripted_workflow", "split": "regression", "task_id": "live_retail_orders_regression_2", "template_id": "live_v3_retail_orders_sql_1", "values_absolute_tolerance": {}, "values_tolerance": {}} +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["cte"], "dataset": "retail_orders", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["fact_order_item"], "expected_values": {"columns": ["n"], "rows": [[1214]]}, "forbidden_claims": [], "forbidden_evidence": [], "max_tool_calls": 4, "notes": "Live v3: retains reference SQL, data, output and source contracts; disambiguates store ranking across every store_format. No v3 model results claimed.", "question": "Using a CTE, count all recorded receipt line items across all orders. Return one column named n.", "reference_sql": "WITH counts AS (SELECT order_id, COUNT(*) AS n FROM fact_order_item GROUP BY order_id) SELECT SUM(n) AS n FROM counts", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_sql_tables": ["fact_order_item"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "forbid", "required_columns": ["n"], "row_order": "multiset"}, "runner": "scripted_workflow", "split": "regression", "task_id": "live_retail_orders_regression_3", "template_id": "live_v3_retail_orders_sql_2", "values_absolute_tolerance": {}, "values_tolerance": {}} +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["window"], "dataset": "retail_orders", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["dim_store"], "expected_values": {"columns": ["store_id", "position"], "rows": [[1, 23], [2, 21], [3, 19], [4, 17], [5, 15], [6, 13], [7, 11], [8, 9], [9, 8], [10, 7], [11, 6], [12, 5], [13, 4], [14, 3], [15, 2], [16, 1], [17, 24], [18, 22], [19, 20], [20, 18], [21, 16], [22, 14], [23, 12], [24, 10]]}, "forbidden_claims": [], "forbidden_evidence": [], "max_tool_calls": 4, "notes": "Live v3: retains reference SQL, data, output and source contracts; disambiguates store ranking across every store_format. No v3 model results claimed.", "question": "For every store, regardless of its store_format, return store_id and its position using dense rank by floor area, with the largest area ranked first. Include all stores and sort the output by store_id.", "reference_sql": "SELECT store_id, DENSE_RANK() OVER (ORDER BY floor_area_sqm DESC) AS position FROM dim_store ORDER BY store_id", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_sql_tables": ["dim_store"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "forbid", "required_columns": ["store_id", "position"], "row_order": "ordered"}, "runner": "scripted_workflow", "split": "regression", "task_id": "live_retail_orders_regression_4", "template_id": "live_v3_retail_orders_sql_3", "values_absolute_tolerance": {}, "values_tolerance": {}} +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["time_range"], "dataset": "retail_orders", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["fact_order"], "expected_values": {"columns": ["n"], "rows": [[96]]}, "forbidden_claims": [], "forbidden_evidence": [], "max_tool_calls": 4, "notes": "Live v3: retains reference SQL, data, output and source contracts; disambiguates store ranking across every store_format. No v3 model results claimed.", "question": "Count receipt records with order dates from January 1 through March 31, 2024 inclusive. Return one column named n.", "reference_sql": "SELECT COUNT(*) AS n FROM fact_order WHERE order_date_key >= 20240101 AND order_date_key < 20240401", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_sql_tables": ["fact_order"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "forbid", "required_columns": ["n"], "row_order": "multiset"}, "runner": "scripted_workflow", "split": "regression", "task_id": "live_retail_orders_regression_5", "template_id": "live_v3_retail_orders_sql_4", "values_absolute_tolerance": {}, "values_tolerance": {}} +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["multi_fact"], "dataset": "retail_orders", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["fact_order", "fact_order_item"], "expected_values": {"columns": ["orders", "lines"], "rows": [[480, 1214]]}, "forbidden_claims": [], "forbidden_evidence": [], "max_tool_calls": 4, "notes": "Live v3: retains reference SQL, data, output and source contracts; disambiguates store ranking across every store_format. No v3 model results claimed.", "question": "Count receipt records and receipt line records independently so that joining them does not inflate either count. Return orders and lines, in that order.", "reference_sql": "SELECT (SELECT COUNT(*) FROM fact_order) AS orders, (SELECT COUNT(*) FROM fact_order_item) AS lines", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_sql_tables": ["fact_order", "fact_order_item"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "forbid", "required_columns": ["orders", "lines"], "row_order": "multiset"}, "runner": "scripted_workflow", "split": "regression", "task_id": "live_retail_orders_regression_6", "template_id": "live_v3_retail_orders_sql_5", "values_absolute_tolerance": {}, "values_tolerance": {}} +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["simple_single_table"], "dataset": "retail_orders", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["fact_order"], "expected_values": {"columns": ["order_id", "net_amount_usd"], "rows": [[14, 1099.89], [289, 1075.9], [41, 1032.51]]}, "forbidden_claims": [], "forbidden_evidence": [], "max_tool_calls": 4, "notes": "Live v3: retains reference SQL, data, output and source contracts; disambiguates store ranking across every store_format. No v3 model results claimed.", "question": "Show the three receipts with the largest net amounts. Return order_id and net_amount_usd, sorted by net_amount_usd descending, then order_id ascending for ties.", "reference_sql": "SELECT order_id, net_amount_usd FROM fact_order ORDER BY net_amount_usd DESC, order_id LIMIT 3", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_sql_tables": ["fact_order"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "forbid", "required_columns": ["order_id", "net_amount_usd"], "row_order": "ordered"}, "runner": "scripted_workflow", "split": "regression", "task_id": "live_retail_orders_regression_7", "template_id": "live_v3_retail_orders_sql_6", "values_absolute_tolerance": {}, "values_tolerance": {}} +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["simple_single_table"], "dataset": "retail_orders", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["fact_order"], "expected_values": {"columns": ["n"], "rows": [[4]]}, "forbidden_claims": [], "forbidden_evidence": [], "max_tool_calls": 4, "notes": "Live v3: retains reference SQL, data, output and source contracts; disambiguates store ranking across every store_format. No v3 model results claimed.", "question": "How many distinct payment methods occur in the stored receipts? Return one column named n.", "reference_sql": "SELECT COUNT(DISTINCT payment_method) AS n FROM fact_order", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_sql_tables": ["fact_order"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "forbid", "required_columns": ["n"], "row_order": "multiset"}, "runner": "scripted_workflow", "split": "regression", "task_id": "live_retail_orders_regression_8", "template_id": "live_v3_retail_orders_sql_7", "values_absolute_tolerance": {}, "values_tolerance": {}} +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["empty_result"], "dataset": "retail_orders", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["dim_store"], "expected_values": {"columns": ["store_id"], "rows": []}, "forbidden_claims": [], "forbidden_evidence": [], "max_tool_calls": 4, "notes": "Live v3: retains reference SQL, data, output and source contracts; disambiguates store ranking across every store_format. No v3 model results claimed.", "question": "Return the identifier of the store whose store identifier is -100, if any. Return only store_id.", "reference_sql": "SELECT store_id FROM dim_store WHERE store_id = -100", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_sql_tables": ["dim_store"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "allow", "required_columns": ["store_id"], "row_order": "multiset"}, "runner": "scripted_workflow", "split": "regression", "task_id": "live_retail_orders_regression_9", "template_id": "live_v3_retail_orders_sql_8", "values_absolute_tolerance": {}, "values_tolerance": {}} +{"acceptable_stop_reasons": [], "allowed_tools": ["execute_sql"], "answer_must_reference_evidence": false, "coverage": ["follow_up_multi_turn"], "dataset": "retail_orders", "expected_outcome": "query", "expected_status": ["success"], "expected_tables": ["fact_order"], "expected_values": {"columns": ["order_count"], "rows": [[480]]}, "follow_up_context": ["How many distinct orders are stored? Return one column named order_count."], "forbidden_claims": [], "forbidden_evidence": [], "max_tool_calls": 8, "notes": "Live v3: retains reference SQL, data, output and source contracts; disambiguates store ranking across every store_format. No v3 model results claimed.", "question": "再查询一次刚才的订单数量,仍只返回 order_count 列。", "reference_sql": "SELECT COUNT(DISTINCT fact_order.order_id) AS order_count FROM fact_order", "replaceable_steps": {}, "required_claims": [], "required_evidence": ["sql_result"], "required_sql_tables": ["fact_order"], "required_steps": [], "result_contract": {"allow_extra_columns": false, "empty": "forbid", "required_columns": ["order_count"], "row_order": "multiset"}, "runner": "scripted_workflow", "split": "regression", "task_id": "live_retail_orders_regression_followup", "template_id": "live_v3_retail_followup", "values_absolute_tolerance": {}, "values_tolerance": {}} diff --git a/evaluation/observers/README.md b/evaluation/observers/README.md new file mode 100644 index 0000000..0667875 --- /dev/null +++ b/evaluation/observers/README.md @@ -0,0 +1,58 @@ +# Frozen live-evaluation usage observer + +`paired_usage_v1.py` is the byte-identical instrument used for the authorized +DeepSeek live pairs on 2026-10-11. SHA-256: +`6ca18bc9d6a13aba25a9fdf3e7d460265fa156e00eb737691e39f9404beff7dd`. + +It wraps the existing paired harness without changing request parameters, +questions, reference results, verdicts or A/B order. It saves each execution +and numeric provider usage before proceeding. The usage hook does not collect +native provider reasoning content or credentials; checkpoints retain the normal +workflow trace. Its own hash is recorded separately +from the runtime source hash. This is a frozen CLI instrument, not an importable +library API. + +Use all arguments supported by `scripts/run_paired_benchmark.py`. For example, +an offline four-execution check: + +```bash +LOG_LEVEL=CRITICAL .venv/bin/python -B evaluation/observers/paired_usage_v1.py \ + --tier 1 --task anime_streaming_dev_1 --repeat 2 --report /tmp/observer.json +``` + +Tier 3 uses real paid APIs and requires the authorization specified in +AGENTS.md. Use a fresh output prefix; checkpoint/usage files are opened +exclusively. Raw reports remain regenerable, gitignored evidence; quoted +numbers and commands belong in tracked documentation. + +`paired_resume_v1.py` preserves the completed prefix of an interrupted report +verbatim, including failures. It checks every manifest control, schedule and +execution fingerprint before calling the provider for unfinished cases. The +original report and usage stay intact; the combined report has a fresh prefix, +copied prior numeric usage, and observer digests linking both segments. It never +retries a completed timeout or chooses which completed results to keep. + +```bash +# Same arguments as the original experiment; a fresh report path is required. +LOG_LEVEL=CRITICAL .venv/bin/python -B evaluation/observers/paired_resume_v1.py \ + /tmp/interrupted.json --tier 1 --task anime_streaming_dev_1 --repeat 2 \ + --report /tmp/resumed.json +``` + +The usage auditor reconciles mixed traces against reported model spans. A +timeout without provider usage stays unknown: its reported responses can be +priced, but total execution cost is null. The priced-response subtotal is not +a complete bill. Normal measured-token summaries retain the original accounting +and omit pairs whose full token totals are unknown. + +`engine_replay_v1.py` is a supplementary offline check of originally passing +SQL through the sanctioned DatabaseTool. It verifies the original database and +SQL-policy hashes before replay and confirms that database bytes stay unchanged. +Its own digest is recorded in the audit. This replay checks stored/reference +rows, not independent policy or full semantic correctness, and calls no model. + +```bash +LOG_LEVEL=CRITICAL .venv/bin/python -B evaluation/observers/engine_replay_v1.py \ + evaluation/reports/phase3_deepseek_flash_candidates_live_v1.json \ + --report /tmp/candidate_engine_replay.json +``` diff --git a/evaluation/observers/engine_replay_v1.py b/evaluation/observers/engine_replay_v1.py new file mode 100644 index 0000000..030bfc6 --- /dev/null +++ b/evaluation/observers/engine_replay_v1.py @@ -0,0 +1,76 @@ +"""Read-only replay of originally passing SQL through the sanctioned DatabaseTool.""" +import argparse +import hashlib +import json +from pathlib import Path +import sys + +ROOT = Path.cwd() +sys.path.insert(0, str(ROOT)) +from queryforge.domain.security.sql_policy import load_sql_policy +from queryforge.infrastructure.db.sqlite_connector import SQLiteConnector +from queryforge.infrastructure.tools.database_tool import DatabaseTool +from queryforge.evaluation import load_spec_splits +from queryforge.evaluation.results import compare_results +from scripts.benchmark_agent import load_datasets + +parser=argparse.ArgumentParser(description=__doc__) +parser.add_argument('input_report',type=Path) +parser.add_argument('--report',type=Path,required=True) +args=parser.parse_args() +if args.report.exists(): + parser.error('output exists; preserve original audit') +original=json.loads(args.input_report.read_text()) +if not original.get('summary',{}).get('complete'): + parser.error('original experiment is incomplete') +datasets=load_datasets() +specs={s.task_id:s for s in load_spec_splits(ROOT/'evaluation/live_tasks')} +def digest(path): + return hashlib.sha256(path.read_bytes()).hexdigest() +before={name:digest(ROOT/info['database']) for name,info in datasets.items()} +if before != original['manifest']['provenance']['datasets_sha256']: + parser.error('database bytes differ from the original experiment') +for name, info in datasets.items(): + expected=original['manifest']['provenance']['contracts_sha256'][name]['sql_policy'] + if digest(ROOT/info['sql_policy']) != expected: + parser.error('SQL policy differs from the original experiment') +connectors={} +tools={} +records=[] +try: + for record in original['records']: + if not record['passed']: + continue + dataset=record['dataset'] + if dataset not in tools: + connectors[dataset]=SQLiteConnector(str(ROOT/datasets[dataset]['database'])) + policy,path=load_sql_policy(ROOT/datasets[dataset]['sql_policy']) + tools[dataset]=DatabaseTool(connectors[dataset],policy,policy_source_path=path) + payload=record['raw_trace']['payload'] + spec=specs[record['task_id']] + item={k:record[k] for k in ('task_id','repeat','arm')} + try: + result=tools[dataset].execute_sql(payload['sql']) + item.update(trace_rows_match=compare_results(result.rows,result.columns,payload['rows'],payload['columns'], + contract=spec.result_contract), + reference_rows_match=compare_results(result.rows,result.columns,spec.expected_values['rows'], + spec.expected_values['columns'],contract=spec.result_contract)) + except Exception as exc: + item.update(trace_rows_match=False,reference_rows_match=False,error_type=type(exc).__name__) + records.append(item) +finally: + for connector in connectors.values(): + connector.close() +after={name:digest(ROOT/info['database']) for name,info in datasets.items()} +audit={'input_report':str(args.input_report.resolve()),'input_report_sha256':digest(args.input_report), + 'script_sha256':digest(Path(__file__)),'replayed_executions':len(records), + 'trace_rows_matched':sum(r['trace_rows_match'] for r in records), + 'reference_rows_matched':sum(r['reference_rows_match'] for r in records), + 'databases_unchanged':before==after,'database_sha256':before,'new_model_calls':0, + 'note':'Supplementary engine replay through DatabaseTool and original SQL policy, not an independent policy/semantic verdict. The independent reference oracles were frozen separately. Matching rows still do not prove source intent.', + 'records':records} +args.report.parent.mkdir(parents=True,exist_ok=True) +with args.report.open('x') as output: + json.dump(audit,output,ensure_ascii=False,indent=2);output.write('\n') +print(json.dumps({k:v for k,v in audit.items() if k!='records'})) +raise SystemExit(0 if audit['databases_unchanged'] and all(r['trace_rows_match'] and r['reference_rows_match'] for r in records) else 1) diff --git a/evaluation/observers/paired_resume_v1.py b/evaluation/observers/paired_resume_v1.py new file mode 100644 index 0000000..03ce48e --- /dev/null +++ b/evaluation/observers/paired_resume_v1.py @@ -0,0 +1,130 @@ +"""Resume an authorized pair schedule without rerunning any completed case.""" +import copy +import hashlib +import json +from pathlib import Path +import sys +from datetime import datetime, timezone + +ROOT = Path.cwd() +sys.path.insert(0, str(ROOT)) +from scripts import run_paired_benchmark as paired +from queryforge.evaluation import TaskOutcome, TaskTrace +from queryforge.infrastructure.models.base import BaseModelProvider + +source_path = Path(sys.argv.pop(1)).resolve() +source = json.loads(source_path.read_text()) +args = paired.parse_args() +preview_args = copy.copy(args) +preview_args.dry_run = True +preview = paired.run(preview_args) +manifest = preview['manifest'] +for key in manifest: + if key != 'api_spend' and manifest[key] != source['manifest'][key]: + raise RuntimeError('Resume refused: manifest changed: '+key) +schedule = [dict(task_id=item['task_id'], repeat=item['repeat'], arm=arm) + for item in manifest['schedule'] for arm in item['order']] +retained = source['records'] +if not retained or len(retained) >= len(schedule): + raise RuntimeError('Resume requires a nonempty incomplete schedule') +for position, record in enumerate(retained): + if any(record[key] != value for key, value in schedule[position].items()): + raise RuntimeError('Retained prefix does not match the schedule') +report_path = Path(args.report).resolve() +for path in [report_path, report_path.with_suffix('.checkpoint.jsonl'), + report_path.with_suffix('.provider_usage.jsonl'), report_path.with_suffix('.manifest.json')]: + if path.exists(): + raise RuntimeError('Resume refuses to overwrite evidence: '+str(path)) +usage_path = report_path.with_suffix('.provider_usage.jsonl') +usage_file = usage_path.open('x') +usage_file.write(source_path.with_suffix('.provider_usage.jsonl').read_text()) +usage_file.flush() +checkpoint = report_path.with_suffix('.checkpoint.jsonl').open('x') +for record in retained: + checkpoint.write(json.dumps(record, ensure_ascii=False)+'\n') +checkpoint.flush() +observer = {'sha256':hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), + 'path':str(Path(__file__).resolve()), 'resumed_from':str(source_path), + 'resumed_from_sha256':hashlib.sha256(source_path.read_bytes()).hexdigest(), + 'retained_executions':len(retained), + 'description':'Completed prefix reused verbatim, including timeout failure; only unfinished cases call the provider', + 'original_observer':source.get('execution_observer'), + 'checkpoint':str(report_path.with_suffix('.checkpoint.jsonl')), + 'provider_usage':str(usage_path)} +report_path.with_suffix('.manifest.json').write_text(json.dumps({'manifest':manifest,'observer':observer},indent=2)+'\n') +position = 0 +records = list(retained) +original_usage = BaseModelProvider.record_usage +original_run_suite = paired.harness.run_suite + +def observed_usage(self, raw_usage): + normalized = original_usage(self, raw_usage) + raw = raw_usage.model_dump() if hasattr(raw_usage, 'model_dump') else raw_usage + raw = raw if isinstance(raw, dict) else {} + entry = dict(schedule[position], at_utc=datetime.now(timezone.utc).isoformat(), + provider=getattr(self,'provider',None), model=getattr(self,'model',None)) + for key in ('prompt_tokens','completion_tokens','total_tokens','prompt_cache_hit_tokens','prompt_cache_miss_tokens'): + value = raw.get(key) + entry[key] = value if type(value) is int and value >= 0 else None + details = raw.get('completion_tokens_details') or {} + entry['reasoning_tokens'] = details.get('reasoning_tokens') if isinstance(details,dict) else None + usage_file.write(json.dumps(entry,ensure_ascii=False)+'\n') + usage_file.flush() + return normalized + +def observed_run_suite(specs, context, **kwargs): + global position + item = schedule[position] + if len(specs) != 1 or specs[0].task_id != item['task_id']: + raise RuntimeError('Observer schedule mismatch') + if position < len(retained): + record = retained[position] + outcome = TaskOutcome.model_validate({key:value for key,value in record.items() + if key not in {'arm','repeat','environment_error','environment_error_reason','provider_contract_error','raw_trace'}}) + position += 1 + return [outcome], [record['raw_trace']] + print(json.dumps(dict(event='started',execution=position+1,total=len(schedule),**item)),flush=True) + outcomes,traces = original_run_suite(specs,context,**kwargs) + if len(outcomes) != 1 or len(traces) != 1: + raise RuntimeError('Expected exactly one outcome and trace') + record = outcomes[0].model_dump() + errors = ' '.join(paired.error_text(traces[0])) + reason = paired._environment_error_reason(RuntimeError(errors)) if not record['passed'] else None + contract = not record['passed'] and paired.provider_contract_error(errors) + record.update(item,environment_error=reason is not None,environment_error_reason=reason, + provider_contract_error=contract,raw_trace=traces[0]) + records.append(record) + checkpoint.write(json.dumps(record,ensure_ascii=False)+'\n') + checkpoint.flush() + print(json.dumps(dict(event='completed',execution=position+1,total=len(schedule),**item, + passed=record['passed'],wall_ms=record.get('wall_ms'), + measured_tokens=record.get('measured_tokens'),failure_class=record.get('failure_class'))),flush=True) + position += 1 + if reason or contract: + raise RuntimeError('Infrastructure/provider-contract failure; preserve checkpoint') + if not record.get('measured_tokens') and 'model request failed' in errors.casefold(): + raise RuntimeError('Provider request failed with mixed or missing measured usage; preserve checkpoint') + return outcomes,traces + +BaseModelProvider.record_usage = observed_usage +paired.harness.run_suite = observed_run_suite +try: + report = paired.run(args) + if report['records'][:len(retained)] != retained: + raise RuntimeError('Retained records changed during resume') +except Exception as exc: + report = {'benchmark':'paired_agent_tasks','manifest':manifest,'records':records, + 'executed':bool(records),'summary':{'complete':False}, + 'interruption':{'type':type(exc).__name__,'reason':str(exc)}} + code = 1 +else: + code = 0 if report['summary']['complete'] else 1 +finally: + checkpoint.close() + usage_file.close() +report['execution_observer'] = observer +with report_path.open('x') as target: + json.dump(report,target,ensure_ascii=False,indent=2) + target.write('\n') +print(json.dumps({'report':str(report_path),'executions':len(records),'summary':report['summary']},ensure_ascii=False),flush=True) +raise SystemExit(code) diff --git a/evaluation/observers/paired_usage_v1.py b/evaluation/observers/paired_usage_v1.py new file mode 100644 index 0000000..2313d4c --- /dev/null +++ b/evaluation/observers/paired_usage_v1.py @@ -0,0 +1,110 @@ +"""Observe the existing paired harness; API parameters and verdicts are unchanged.""" +import copy +import hashlib +import json +import os +from pathlib import Path +import sys +import threading +from datetime import datetime, timezone + +ROOT = Path.cwd() +sys.path.insert(0, str(ROOT)) +from scripts import run_paired_benchmark as paired +from queryforge.infrastructure.models.base import BaseModelProvider + +args = paired.parse_args() +preview_args = copy.copy(args) +preview_args.dry_run = True +preview = paired.run(preview_args) +manifest = preview['manifest'] +schedule = [dict(task_id=item['task_id'], repeat=item['repeat'], arm=arm) + for item in manifest['schedule'] for arm in item['order']] +report_path = Path(args.report).resolve() +report_path.parent.mkdir(parents=True, exist_ok=True) +checkpoint_path = report_path.with_suffix('.checkpoint.jsonl') +usage_path = report_path.with_suffix('.provider_usage.jsonl') +manifest_path = report_path.with_suffix('.manifest.json') +observer = {'sha256': hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), + 'path': str(Path(__file__).resolve()), + 'description': 'Progress/checkpoint and numeric provider-usage observer; no API parameter, task or verdict changes', + 'checkpoint': str(checkpoint_path), 'provider_usage': str(usage_path)} +manifest_path.write_text(json.dumps({'manifest':manifest,'observer':observer}, ensure_ascii=False, indent=2)+'\n') +checkpoint = checkpoint_path.open('x') +usage_file = usage_path.open('x') +lock = threading.Lock() +position = 0 +records = [] +original_usage = BaseModelProvider.record_usage +original_run_suite = paired.harness.run_suite + +def observed_usage(self, raw_usage): + normalized = original_usage(self, raw_usage) + raw = raw_usage.model_dump() if hasattr(raw_usage, 'model_dump') else raw_usage + raw = raw if isinstance(raw, dict) else {} + entry = dict(schedule[position], at_utc=datetime.now(timezone.utc).isoformat(), + provider=getattr(self, 'provider', None), model=getattr(self, 'model', None)) + for key in ('prompt_tokens', 'completion_tokens', 'total_tokens', + 'prompt_cache_hit_tokens', 'prompt_cache_miss_tokens'): + value = raw.get(key) + entry[key] = value if type(value) is int and value >= 0 else None + details = raw.get('completion_tokens_details') or {} + entry['reasoning_tokens'] = details.get('reasoning_tokens') if isinstance(details, dict) else None + with lock: + usage_file.write(json.dumps(entry, ensure_ascii=False)+'\n') + usage_file.flush() + return normalized + +def observed_run_suite(specs, context, **kwargs): + global position + item = schedule[position] + if len(specs) != 1 or specs[0].task_id != item['task_id']: + raise RuntimeError('Observer schedule mismatch') + print(json.dumps(dict(event='started', execution=position+1, total=len(schedule), **item)), flush=True) + outcomes, traces = original_run_suite(specs, context, **kwargs) + if len(outcomes) != 1 or len(traces) != 1: + raise RuntimeError('Observer expected exactly one trace and outcome') + record = outcomes[0].model_dump() + errors = ' '.join(paired.error_text(traces[0])) + reason = paired._environment_error_reason(RuntimeError(errors)) if not record['passed'] else None + contract_error = not record['passed'] and paired.provider_contract_error(errors) + record.update(item, environment_error=reason is not None, + environment_error_reason=reason, provider_contract_error=contract_error, + raw_trace=traces[0]) + records.append(record) + checkpoint.write(json.dumps(record, ensure_ascii=False)+'\n') + checkpoint.flush() + os.fsync(checkpoint.fileno()) + print(json.dumps(dict(event='completed', execution=position+1, total=len(schedule), **item, + passed=record['passed'], wall_ms=record.get('wall_ms'), + measured_tokens=record.get('measured_tokens'), + failure_class=record.get('failure_class'), + failed_checks=[check['name'] for check in record['checks'] if not check['passed']])), flush=True) + position += 1 + if reason or contract_error: + raise RuntimeError('Infrastructure/provider-contract failure; stop and preserve partial traces') + if not record.get('measured_tokens') and 'model request failed' in errors.casefold(): + raise RuntimeError('Provider request failed without measured usage; stop and inspect') + return outcomes, traces + +BaseModelProvider.record_usage = observed_usage +paired.harness.run_suite = observed_run_suite +try: + report = paired.run(args) +except Exception as exc: + report = {'benchmark':'paired_agent_tasks', 'manifest':manifest, 'records':records, + 'executed': bool(records), 'summary':{'complete':False}, + 'interruption':{'type':type(exc).__name__, 'reason':str(exc)}, + 'execution_observer':observer} + report_path.write_text(json.dumps(report, ensure_ascii=False, indent=2)+'\n') + print(json.dumps({'report':str(report_path),'complete':False,'executions':len(records), + 'reason':str(exc)}), flush=True) + raise SystemExit(1) +else: + report['execution_observer'] = observer + report_path.write_text(json.dumps(report, ensure_ascii=False, indent=2)+'\n') + print(json.dumps({'report':str(report_path),'summary':report['summary']}, ensure_ascii=False), flush=True) + raise SystemExit(0 if report['summary']['complete'] else 1) +finally: + checkpoint.close() + usage_file.close() diff --git a/evaluation/phase4_local_acceptance_2026_10_11.json b/evaluation/phase4_local_acceptance_2026_10_11.json new file mode 100644 index 0000000..cc9645f --- /dev/null +++ b/evaluation/phase4_local_acceptance_2026_10_11.json @@ -0,0 +1,244 @@ +{ + "date": "2026-10-11", + "scope": "local_single_user_phase4", + "git_head": "d1e1e4f8ef95dfdf16bf7206ddcb797fa881eb4a", + "dirty": true, + "versions": { + "python": "3.12.11", + "sqlite": "3.50.4", + "sqlglot": "28.10.1", + "pydantic": "2.13.4", + "node": "v23.11.0" + }, + "frontend_source_sha256": "b8a75255925a3c44a62b0c6d8484e41b1791cc7846fc4fcf9a0d574e4e1fd977", + "offline_comparison": { + "before_command": "LOG_LEVEL=CRITICAL .venv/bin/python -B scripts/benchmark_agent.py --tier 1 --tasks-dir evaluation/live_tasks_v3 --split dev --split regression --split holdout --report /tmp/queryforge_phase4_live_v3.json --gate", + "after_command": "LOG_LEVEL=CRITICAL .venv/bin/python -B scripts/benchmark_agent.py --tier 1 --tasks-dir evaluation/live_tasks_v3 --split dev --split regression --split holdout --parallel-candidates 1 --skill-mode auto --report /tmp/queryforge_phase4_live_v3_final.json --gate", + "before": { + "controls": { + "parallel_candidates": null, + "skill_mode": "auto", + "history_top_k": 0, + "vector_kb": false, + "today": "2024-12-31" + }, + "effective_parallel_candidates": 1, + "provenance": { + "source_sha256": "83e6adde9def7439bb9823901846bbe5503c2bf3e6ac5168a531a1b589423a20", + "assets_sha256": "06ad2b4d54be3939d1e6bed8641c72b18fcb7192d9e88d07967e5cc86801d2b3", + "datasets_sha256": { + "anime_streaming": "e5c53343b0d3cee46cbc02610353c60e2b909fd61c1e1fee16c222771e7ecfb8", + "retail_orders": "04a18a5d5bc8118eae21b88a4159c1857f3caf86d5b0eb527e41a395f855543f", + "support_tickets": "95829871b3525ed67256cfa7297c01c11d4ade01cacfe6a0436769b89e6065ad" + }, + "contracts_sha256": { + "anime_streaming": { + "semantic_model": "fa6d790e860c2481104fe2bab3a18f3d0809e1bcb20c6f09d9be339b782d1124", + "sql_policy": "a6817e5927206348ba833acc886ae8fdacd452f585ed1d489a3c86ecd1d00a01" + }, + "retail_orders": { + "semantic_model": "46238e583ffb49136286b0566a032eddfbf6981b4f51376a0c44a309d995b167", + "sql_policy": "70ca076acf9ef843cc71d60b2661689abe2f803e9afc75f8e47402d9e726b27a" + }, + "support_tickets": { + "semantic_model": "66ca8903dd1406214dbd17239be34c86d88d8996fd1d679d6da41714ba575c9c", + "sql_policy": "003e02d935e1d5f5059dabf0b3606b7444e7ab1cdbbbf0f7c1be0aa0cd5c625f" + } + }, + "gold_sha256": "50573fa619a41660f7f548cb38598b42dc204f92708622b5b589edf1f1c01842", + "threshold_sha256": "0fb92fd7fe8bbcb90187461214358336b8ef7767ed392bf6d85fc35aa8a4143c", + "git_head": "d1e1e4f8ef95dfdf16bf7206ddcb797fa881eb4a", + "dirty": true + }, + "task_count": 23, + "passed_tasks": 23, + "threshold_violations": [], + "model_calls": 72, + "usage": { + "recorded_tasks": 23, + "unmeasured_tasks": [], + "measured_tasks": 0, + "estimated_tasks": 23, + "measured_tokens": 0, + "estimated_tokens": 299851, + "total_tokens": 299851, + "complete": true + }, + "last_turn_skill_router_model_spans": 23 + }, + "after": { + "controls": { + "parallel_candidates": 1, + "skill_mode": "auto", + "history_top_k": 0, + "vector_kb": false, + "today": "2024-12-31" + }, + "effective_parallel_candidates": 1, + "provenance": { + "source_sha256": "37691987be54e082f14a271c07801492fede4f45b6961f1205fd290b26a26b4f", + "assets_sha256": "aefff53a4c821b5ea4ddc726cca5b022e476c25ec4f992ed5bffd185849ef225", + "datasets_sha256": { + "anime_streaming": "e5c53343b0d3cee46cbc02610353c60e2b909fd61c1e1fee16c222771e7ecfb8", + "retail_orders": "04a18a5d5bc8118eae21b88a4159c1857f3caf86d5b0eb527e41a395f855543f", + "support_tickets": "95829871b3525ed67256cfa7297c01c11d4ade01cacfe6a0436769b89e6065ad" + }, + "contracts_sha256": { + "anime_streaming": { + "semantic_model": "fa6d790e860c2481104fe2bab3a18f3d0809e1bcb20c6f09d9be339b782d1124", + "sql_policy": "a6817e5927206348ba833acc886ae8fdacd452f585ed1d489a3c86ecd1d00a01" + }, + "retail_orders": { + "semantic_model": "46238e583ffb49136286b0566a032eddfbf6981b4f51376a0c44a309d995b167", + "sql_policy": "70ca076acf9ef843cc71d60b2661689abe2f803e9afc75f8e47402d9e726b27a" + }, + "support_tickets": { + "semantic_model": "66ca8903dd1406214dbd17239be34c86d88d8996fd1d679d6da41714ba575c9c", + "sql_policy": "003e02d935e1d5f5059dabf0b3606b7444e7ab1cdbbbf0f7c1be0aa0cd5c625f" + } + }, + "gold_sha256": "50573fa619a41660f7f548cb38598b42dc204f92708622b5b589edf1f1c01842", + "threshold_sha256": "0fb92fd7fe8bbcb90187461214358336b8ef7767ed392bf6d85fc35aa8a4143c", + "git_head": "d1e1e4f8ef95dfdf16bf7206ddcb797fa881eb4a", + "dirty": true + }, + "task_count": 23, + "passed_tasks": 23, + "threshold_violations": [], + "model_calls": 51, + "usage": { + "recorded_tasks": 23, + "unmeasured_tasks": [], + "measured_tasks": 0, + "estimated_tasks": 23, + "measured_tokens": 0, + "estimated_tokens": 276994, + "total_tokens": 276994, + "complete": true + }, + "last_turn_skill_router_model_spans": 3 + }, + "limitations": [ + "ScriptedModel supplies reference SQL; contracts measure engineering control flow, not real-model accuracy.", + "Before count is implicit offline default 1, after count is explicit 1; no candidate-selection payload in either run.", + "Calls include the multi-turn task; last-turn spans do not count its earlier router.", + "Source differs by phase4 follow-up fixes as well as keyword assets; this is a version observation, not a single-factor randomized ablation.", + "Tokens are local estimates; zero measured calls, no billed-token/cost or latency inference." + ] + }, + "verification": { + "python": { + "command": "./init.sh", + "tests": 1105, + "passed": 1080, + "skipped": 25, + "failed": 0, + "exit_code": 0, + "duration_seconds": 110.68 + }, + "repository": { + "command": "make check", + "checks": 13, + "passed": 13, + "exit_code": 0 + }, + "semantic": { + "command": "make semantic-check", + "checks": 86, + "passed": 86, + "exit_code": 0 + }, + "studio": { + "command": "make web-check", + "tests": 31, + "passed": 31, + "failed": 0, + "exit_code": 0 + }, + "tier1": { + "command": "LOG_LEVEL=CRITICAL .venv/bin/python -B scripts/benchmark_agent.py --tier 1 --split dev --split regression --split holdout --report /tmp/queryforge_phase4_tier1_all.json --gate", + "passed": 32, + "tasks": 32, + "exit_code": 0 + }, + "diagnostics": { + "command": "LOG_LEVEL=CRITICAL .venv/bin/python -B scripts/benchmark_agent.py --tier 1 --tasks-dir evaluation/diagnostics --split dev --split regression --split holdout --report /tmp/queryforge_phase4_diagnostics.json --gate", + "passed": 3, + "tasks": 3, + "exit_code": 0 + } + }, + "http_acceptance_command": ".venv/bin/python -B scripts/check_local_studio.py --report /tmp/queryforge_phase4_studio_acceptance.json", + "http_acceptance": { + "mode": "offline_model_real_studio_and_database", + "checks": [ + "explicit_offline_fixture", + "unreviewed_upload_denied", + "invalid_contract_not_published", + "invalid_parquet_physically_rejected", + "parquet_physical_publication", + "physical_publication", + "ready_domain_after_publication", + "physical_count_oracle", + "physical_sum_oracle", + "unpublished_domain_denied", + "domain_path_override_denied", + "write_sql_denied", + "write_rejection_keeps_data", + "snapshot_replay", + "replay_zero_model_calls", + "cross_domain_replay_and_id_conflict_denied", + "cross_origin_denied", + "sse_terminal_protocol_and_oracle", + "sse_gapless_sequence", + "sse_disconnect_persisted_cancelled", + "cancelled_run_has_no_execution_artifact", + "backend_offline_guard", + "expired_report_denied_dry_run_preserves", + "expired_report_reversibly_quarantined" + ], + "passed": 24, + "domain_id": "domain_a406888339c3472e801a6d9911cc9e87", + "unpublished_domain_id": "domain_9e5770085d0846ed9c9420f5ce38a1fe", + "run_id": "qf_a1bcca15f2af461c88a33298b29820e5", + "data_version": "20261011T153743Z-56343c26-d11136ae", + "parquet_domain_id": "domain_a72f23df01714f43a2baf58b6a7af258", + "cancelled_run_id": "qf_71a8fbce73734b13aa7e9e0c1f0e94f9", + "cancelled_state": "/tmp/queryforge_phase4_fixture/backend/runs/qf_71a8fbce73734b13aa7e9e0c1f0e94f9/state.json", + "fixture_sha256": "dee5cdbdf6639eeeb32fab8ba5e80790380c3b343116e2e633629e08c66f9bbe", + "oracle": { + "count": 3, + "sum": 60 + }, + "real_provider_calls": 0, + "duration_seconds": 21.05 + }, + "browser_acceptance": { + "browser": "Chrome native CUA keyboard", + "domain_id": "domain_871fee4d1da7410897403ace61bdb5f8", + "run_id": "qf_cae93b3597c442c59553b42e8e085837", + "visible_rows": [ + [ + 3 + ] + ], + "visible_sql": "SELECT COUNT(DISTINCT record_id) AS n FROM uploaded_record", + "replay_toast": "Saved run replayed · data version 20261011T150141Z-56343c26-4af32079.", + "model_calls_before_replay": 24, + "model_calls_after_replay": 24, + "real_provider_calls": 0 + }, + "remaining_acceptance": [ + { + "item": "complete_native_browser_upload_click_sequence", + "status": "pending", + "reason": "Synthetic CSV selected in native OS picker, but Open remained disabled; HTTP publication passed separately." + }, + { + "item": "deepseek_phase4_quality_latency_and_measured_cost", + "status": "not_run", + "reason": "No new real API spend; requires separately authorized funded evaluation." + } + ], + "real_provider_calls": 0 +} diff --git a/queryforge/application/analysis_planner.py b/queryforge/application/analysis_planner.py index ade312b..b805c83 100644 --- a/queryforge/application/analysis_planner.py +++ b/queryforge/application/analysis_planner.py @@ -16,6 +16,7 @@ from __future__ import annotations import logging +import json import re import threading import time @@ -31,6 +32,7 @@ new_run_id, run_logging_context, start_span_recorder, + stable_digest, ) from queryforge.core.schemas.models import DateContext from queryforge.domain.analysis import ( @@ -43,6 +45,10 @@ ) from queryforge.domain.security import load_sql_policy from queryforge.domain.semantic import MetricMatch, SemanticModelContext, SemanticModelLoader +from queryforge.domain.semantic.query_constraints import ( + UnsupportedConstraint, bind_filters, extract_filters, +) +from queryforge.domain.semantic.sql_validator import QuerySpecCompiler from queryforge.infrastructure.db.adapters import open_database as SQLiteConnector from queryforge.infrastructure.tools.database_tool import DatabaseTool from queryforge.interfaces.transport_security import ( @@ -372,7 +378,14 @@ def _execute_analysis( model_context = self._load_semantic_model(model_path, tools, text) request = self.build_request(text, model_context) date_context = self._date_context(text, request) - ambiguity = is_high_impact_ambiguity(text, request) + if request.is_blocked: + return self._clarification_payload( + text, request, domain_id=domain_id, + reason=request.unresolved_questions[0] if request.unresolved_questions else "unsupported_request", + budget=budget, + ) + intent_text, _ = extract_filters(text) + ambiguity = is_high_impact_ambiguity(intent_text, request) if ambiguity: request.status = "blocked" request.unresolved_questions = [ @@ -393,7 +406,28 @@ def _execute_analysis( reason="no_governed_metric_match", budget=budget, ) - ungoverned = self._ungoverned_breakdown_terms(text, model_context) + metrics = [m for m in model_context.model.metrics if m.name in request.metric_ids] + problem = None + if request.time_range and (date_context is None or any(not m.time_field for m in metrics)): + problem = "unsupported_time_window: a resolved window and governed metric time field are required" + elif len(metrics) > 1 and (request.time_grain or request.comparison_baseline) and any(not m.time_field for m in metrics): + problem = "unsupported_metric_combination: time analysis requires a time field for every metric" + elif request.time_grain not in {None, "daily", "weekly", "monthly", "quarterly", "yearly"}: + problem = "unsupported_time_grain:" + str(request.time_grain) + elif (request.comparison_baseline or request.time_grain) and not self._time_dimension_ref( + model_context, metrics[0], next(e for e in model_context.model.entities if e.name == metrics[0].entity), + request.time_grain, + ): + problem = "unsupported_comparison: a governed time dimension is required" + if not problem and len(metrics) > 1 and (request.time_grain or request.comparison_baseline): + calendars = {(m.analysis.time.timezone, m.analysis.time.fiscal_year_start_month) if m.analysis and m.analysis.time else ("UTC", 1) for m in metrics} + if not self._shared_time_dimension_ref(model_context, metrics, request.time_grain) or len(calendars) != 1: + problem = "unsupported_metric_combination: multi-metric periods require one shared time dimension, timezone and calendar" + if problem: + request.status = "blocked" + request.unresolved_questions.append(problem) + return self._clarification_payload(text, request, domain_id=domain_id, reason=problem, budget=budget) + ungoverned = self._ungoverned_breakdown_terms(intent_text, model_context) if ungoverned: # The question asks for a breakdown the semantic model does not # declare. Answering without it would return a different question's @@ -435,7 +469,10 @@ def _execute_analysis( if persisted is not None: analysis_plan = persisted self._rebuild_registry_missing_steps(analysis_plan, registry) + self._require_request(analysis_plan, request, model_context, text) resumer.save_plan(analysis_plan) + else: + self._require_request(analysis_plan, request, model_context, text) analysis_plan, unavailable = self._drop_unavailable_steps( analysis_plan, registry, blocked=self._blocked_actions() ) @@ -452,7 +489,9 @@ def _execute_analysis( run_versions={ "data_version": data_version, "semantic_version": ( - domain.semantic_version if domain is not None else None + str(domain.semantic_version if domain is not None else model_context.model.version) + + ":" + stable_digest(json.dumps({"model": model_context.model.model_dump(mode="json"), + "ranges": [r.model_dump(mode="json") for r in date_context.ranges] if date_context else []}, sort_keys=True)) ), "policy_version": ( domain.policy_version if domain is not None else None @@ -528,24 +567,49 @@ def build_request( ) -> AnalysisRequest: """Build the typed analysis intent using the public step-04 API.""" + intent_text, filters, unresolved = question, [], [] + try: + intent_text, filters = extract_filters(question) + except UnsupportedConstraint as exc: + unresolved.append(f"unsupported_filter: {exc}") metric_matches: list[MetricMatch] = ( - SemanticModelLoader.match_metrics(model_context.model, question) + SemanticModelLoader.match_metrics(model_context.model, intent_text) if model_context is not None else [] ) dimensions = [ match.semantic_name - for match in (model_context.matches if model_context is not None else []) + for match in (SemanticModelLoader.match_question(model_context.model, intent_text) + if model_context is not None else []) if match.kind == "dimension" ] + if model_context is not None and metric_matches and filters: + try: + filters = bind_filters(model_context.model, [m.metric for m in metric_matches], filters) + except UnsupportedConstraint as exc: + unresolved.append(f"unsupported_filter: {exc}") + grain = detect_time_grain(intent_text) + baseline = detect_comparison_baseline(intent_text) + if grain is None and baseline: + if baseline == "previous_month" or re.search(r"\bmom\b", intent_text, re.I): + grain = "monthly" + elif baseline == "previous_quarter" or re.search(r"\bqoq\b", intent_text, re.I): + grain = "quarterly" + elif baseline == "previous_year": + grain = "yearly" + elif baseline in {"previous_period", "same_period_last_year"}: + unresolved.append("unsupported_comparison: specify the calendar grain for this baseline") return AnalysisRequest( intent="analyze", metric_ids=[match.metric.name for match in metric_matches], dimensions=list(dict.fromkeys(dimensions)), - time_range=detect_time_range(question), - time_grain=detect_time_grain(question), - comparison_baseline=detect_comparison_baseline(question), + filters=[{"expression": f} for f in filters], + time_range=detect_time_range(intent_text), + time_grain=grain, + comparison_baseline=baseline, output="structured_analysis", + unresolved_questions=unresolved, + status="blocked" if unresolved else "valid", ) def build_plan( @@ -573,29 +637,86 @@ def build_plan( raise ValueError( f"metric {metric_name!r} references unknown entity {metric.entity!r}" ) - dimension_refs = self._dimension_refs( - model_context, request.dimensions, question - ) - time_dimension = self._time_dimension_ref(model_context, metric, entity) + dimension_refs = self._analysis_dimension_refs(model_context, request, question) + time_dimension = self._time_dimension_ref(model_context, metric, entity, request.time_grain) + if len(request.metric_ids) > 1: + time_dimension = self._shared_time_dimension_ref(model_context, + [m for m in model_context.model.metrics if m.name in request.metric_ids], request.time_grain) template = self._select_template( - question, request, dimension_refs, time_dimension + extract_filters(question)[0], request, dimension_refs, time_dimension + ) + steps = self._template_steps( + template, metric_name, table, dimension_refs, request, time_dimension=time_dimension, ) + for step in steps: + if step.action == "query_metric": + step.inputs["metric_ids"] = list(request.metric_ids) + step.inputs["filters"] = list(request.filters) + if request.comparison_baseline: + step.inputs["comparison_baseline"] = request.comparison_baseline + # Every declared join target is verified at execution time. + step.budget["max_tool_calls"] = 1 + len(model_context.model.entities) + len(request.metric_ids) + elif step.action == "compare_periods" and request.comparison_baseline: + step.inputs["comparison_baseline"] = request.comparison_baseline + if request.time_grain: + step.inputs["time_grain"] = request.time_grain + step.budget["max_tool_calls"] = len(request.metric_ids) + if len(request.metric_ids) > 1 and template != "contribution": + # One query returns all compatible measures. Single-series analysis + # tools cannot interpret several measure columns, so do not invoke them. + steps = [s for s in steps if s.action not in {"drill_down", "render_chart"}] + steps[-1].depends_on = [s.id for s in steps if s.action in {"query_metric", "compare_periods"}] + steps[-1].validation["require_evidence"] = ["metric_resolution", "data_quality", "metric_value"] + for step in steps: + if step.action == "compare_periods": + step.budget["max_tool_calls"] = len(request.metric_ids) + else: + selected_metric = next(m for m in model_context.model.metrics if m.name == metric_name) + metadata = QuerySpecCompiler._analysis_metadata(selected_metric, entity) + if metadata["additivity"] == "non_additive" or any( + ref in metadata["non_additive_dimensions"] for ref in dimension_refs + ): + # Recompute each group; never sum ratios or distinct counts. + steps = [s for s in steps if s.action != "drill_down"] + for step in steps: + step.depends_on = [d for d in step.depends_on if d != "drill_down"] + step.validation["require_evidence"] = [e for e in step.validation.get("require_evidence", []) if e != "drill_down"] return AnalysisPlan( plan_id=f"plan_{uuid4().hex[:10]}", task_id=f"task_{uuid4().hex[:10]}", question=question, domain_id=domain_id, - steps=self._template_steps( - template, - metric_name, - table, - dimension_refs, - request, - time_dimension=time_dimension, - ), + steps=steps, status="pending", ) + def _require_request( + self, plan: AnalysisPlan, request: AnalysisRequest, + model_context: SemanticModelContext, question: str, + ) -> None: + """Bind delivery obligations even for caller-supplied or resumed plans.""" + for step in plan.steps: + if step.action == "compose_answer": + first = next(m for m in model_context.model.metrics if m.name == request.metric_ids[0]) + entity = next(e for e in model_context.model.entities if e.name == first.entity) + time_ref = self._time_dimension_ref(model_context, first, entity, request.time_grain) + dimensions = self._analysis_dimension_refs(model_context, request, question) + if len(request.metric_ids) > 1: + time_ref = self._shared_time_dimension_ref(model_context, + [m for m in model_context.model.metrics if m.name in request.metric_ids], request.time_grain) + # Inputs are included in journal fingerprints; validation-only + # metadata would allow a stale composed answer to be reused. + step.inputs["require_request"] = { + "metric_ids": list(request.metric_ids), + "filters": [f["expression"] for f in request.filters], + "dimensions": dimensions, + "comparison_baseline": request.comparison_baseline, + "time_grain": request.time_grain, + "time_range": request.time_range, + "diagnosis": bool(request.comparison_baseline and request.time_grain + and any(ref != time_ref for ref in dimensions)), + } + # ------------------------------------------------------------- templates #: Deterministic task templates (plan 阶段 4 / 11 第 6 条). @@ -646,18 +767,20 @@ def _select_template( ) -> str: """Pick a deterministic task template from the typed request. - Ordered-series templates (trend/anomaly) require a resolvable time - dimension, because the governed compiler does not bucket timestamps. + Ordered-series templates require a resolvable time dimension. A requested + category breakdown must not be discarded in favour of a single series. """ lowered = question.casefold() + if request.comparison_baseline and time_dimension and any(ref != time_dimension for ref in dimension_refs): + return "contribution" if time_dimension and any(marker in lowered for marker in cls._ANOMALY_MARKERS): return "anomaly" - has_time = bool(request.time_range) or bool(request.time_grain) + has_time = bool(request.time_grain or request.comparison_baseline) if not has_time and time_dimension and any( marker in lowered for marker in cls._TREND_MARKERS ): has_time = True - if time_dimension and has_time: + if time_dimension and has_time and all(ref == time_dimension for ref in dimension_refs): return "trend" if request.comparison_baseline and dimension_refs: return "contribution" @@ -666,8 +789,10 @@ def _select_template( return "default" @staticmethod - def _time_dimension_ref(model_context: Any, metric: Any, entity: Any) -> str | None: - """The entity dimension whose column backs the metric's time field.""" + def _time_dimension_ref( + model_context: SemanticModelContext, metric: Any, entity: Any, grain: str | None = None, + ) -> str | None: + """Resolve the metric's own time field or its governed calendar join.""" if entity is None: return None time_field = getattr(metric, "time_field", None) @@ -677,6 +802,51 @@ def _time_dimension_ref(model_context: Any, metric: Any, entity: Any) -> str | N for dimension in getattr(entity, "dimensions", []): if dimension.column == column: return f"{entity.name}.{dimension.name}" + period = {"daily": "date", "weekly": "date", "quarterly": "quarter", "yearly": "year"}.get(grain, "month") + for candidate in model_context.model.entities: + dimension = next((d for d in candidate.dimensions if d.name == period), None) + if dimension is None: + continue + path = SemanticModelLoader.resolve_join_path(model_context.model, entity.name, candidate.name) + if path is None or not path.safe: + continue + direct = QuerySpecCompiler._direct_time_join( + model_context, base_table=entity.table, metric_time_field=metric.time_field, + dimension_entity=candidate, join_paths=[path], + ) + if direct is not None: + return f"{candidate.name}.{dimension.name}" + return None + + @classmethod + def _analysis_dimension_refs(cls, context, request, question): + refs = cls._dimension_refs(context, request.dimensions, question) + if not request.time_grain: + return refs + metrics = [m for m in context.model.metrics if m.name in request.metric_ids] + entities = {e.name: e for e in context.model.entities} + temporal = {cls._time_dimension_ref(context, m, entities[m.entity], grain) + for m in metrics for grain in ("daily", "monthly", "quarterly", "yearly")} + time_ref = cls._shared_time_dimension_ref(context, metrics, request.time_grain) + return list(dict.fromkeys(time_ref if ref in temporal and time_ref else ref for ref in refs)) + + @classmethod + def _shared_time_dimension_ref(cls, context, metrics, grain): + entities = {e.name: e for e in context.model.entities} + references = [cls._time_dimension_ref(context, m, entities[m.entity], grain) for m in metrics] + if len(set(references)) == 1: + return references[0] + common = set.intersection(*(set(m.allowed_dimensions) for m in metrics)) + for reference in sorted(common): + entity_name, _, dimension_name = reference.partition(".") + target = entities[entity_name] + if dimension_name not in {"date", "month", "quarter", "year"}: + continue + if all(QuerySpecCompiler._direct_time_join( + context, base_table=entities[m.entity].table, metric_time_field=m.time_field, + dimension_entity=target, join_paths=[SemanticModelLoader.resolve_join_path(context.model, m.entity, target.name)], + ) for m in metrics): + return reference return None def _template_steps( @@ -802,16 +972,25 @@ def _template_steps( ), ] if template == "contribution": - # Per-category two-period values are not queryable yet (the governed - # compiler groups by one dimension), so the plan compares aggregate - # periods and records the missing decomposition as a limitation. + if not time_dimension or not request.time_grain: + # Unsupported/ambiguous baselines keep the existing refusal path. + category_refs = dimension_refs + else: + category_refs = [time_dimension, *(ref for ref in dimension_refs if ref != time_dimension)] return [ resolved, quality, + PlanStep( + id="query_totals", action="query_metric", + inputs={**metric_knobs, "dimensions": [time_dimension] if time_dimension else [], + "result_role": "metric_totals", "limit": 100}, + depends_on=["check_data_quality"], expected_evidence=["metric_totals"], + budget={"max_tool_calls": 2}, + ), PlanStep( id="query_metric", action="query_metric", - inputs={**metric_knobs, "limit": 100}, + inputs={**metric_knobs, "dimensions": category_refs, "limit": 1000}, depends_on=["check_data_quality"], expected_evidence=["metric_value"], validation={"require_grain": dimension_refs}, @@ -820,19 +999,30 @@ def _template_steps( PlanStep( id="compare_periods", action="compare_periods", - inputs={}, - depends_on=["query_metric"], + inputs={"dataset_kind": "metric_totals"} if request.time_grain else {}, + depends_on=["query_totals"] if request.time_grain else ["query_metric"], expected_evidence=["period_comparison"], validation={"require_metric": metric_name, "knobs": metric_knobs}, budget={"max_tool_calls": 1}, ), + PlanStep( + id="calculate_contribution", action="calculate_contribution", inputs={}, + depends_on=["query_metric", "compare_periods"], expected_evidence=["contribution"], + budget={"max_tool_calls": len(request.metric_ids)}, + ), + PlanStep( + id="detect_anomaly", action="detect_anomaly", inputs={"dataset_kind": "metric_totals"}, + depends_on=["query_totals"], expected_evidence=["anomaly"], + validation={"knobs": {"min_points": 4}}, budget={"max_tool_calls": len(request.metric_ids)}, + ), self._compose_step( - ["query_metric", "compare_periods"], + ["calculate_contribution", "detect_anomaly"], [ "metric_resolution", "data_quality", "metric_value", "period_comparison", + "metric_totals", "contribution", "anomaly", ], ), ] @@ -1036,7 +1226,8 @@ def _date_context(question: str, request: AnalysisRequest) -> Any: except Exception: # pragma: no cover - planner must not depend on the workflow return None try: - ranges = DateParserNode.parse_rules(question, date.today()) + intent_text, _ = extract_filters(question) + ranges = DateParserNode.parse_rules(intent_text, date.today()) except Exception: # pragma: no cover - a parser failure never blocks the run return None if not ranges: diff --git a/queryforge/application/resources.py b/queryforge/application/resources.py index 7247a10..0309924 100644 --- a/queryforge/application/resources.py +++ b/queryforge/application/resources.py @@ -90,10 +90,13 @@ def report_path( report_output_dir or config.report_output_dir ).expanduser().resolve() validate_report_root(config, report_output_dir) - path = root / f"{run_id}.html" - if not path.is_file(): - raise ValueError(f"Report does not exist for run_id {run_id!r}") - return path + from queryforge.infrastructure.storage.report_store import ReportStore + return ReportStore(root, config.report_retention_days).report_path(run_id) + + def expire_reports(self, *, dry_run: bool = True) -> dict: + from queryforge.infrastructure.storage.report_store import ReportStore + config = self.config_loader() + return ReportStore(config.report_output_dir, config.report_retention_days).expire(dry_run=dry_run) def list_skills(self) -> list[dict]: return [ diff --git a/queryforge/bundled_skills/business_rules/skill.yml b/queryforge/bundled_skills/business_rules/skill.yml index 526e343..4aa3469 100644 --- a/queryforge/bundled_skills/business_rules/skill.yml +++ b/queryforge/bundled_skills/business_rules/skill.yml @@ -3,3 +3,4 @@ description: Example commerce metric rules for order revenue and cancellation ha allowed_nodes: [gen_sql, reflect, fix] enabled: false priority: 95 +selection_keywords: ["order revenue", "cancelled orders", "cancellation"] diff --git a/queryforge/bundled_skills/data_modeling/skill.yml b/queryforge/bundled_skills/data_modeling/skill.yml index a046423..24bc8ea 100644 --- a/queryforge/bundled_skills/data_modeling/skill.yml +++ b/queryforge/bundled_skills/data_modeling/skill.yml @@ -3,3 +3,4 @@ description: Apply reliable dimensional, normalized, and event-modeling rules at allowed_nodes: [plan_mode, gen_sql, reflect, fix] enabled: false priority: 75 +selection_keywords: ["order revenue", "grain", "join", "independently", "line items", "schema", "粒度", "连接"] diff --git a/queryforge/bundled_skills/data_quality_testing/skill.yml b/queryforge/bundled_skills/data_quality_testing/skill.yml index 9e36b8f..d90f75d 100644 --- a/queryforge/bundled_skills/data_quality_testing/skill.yml +++ b/queryforge/bundled_skills/data_quality_testing/skill.yml @@ -3,3 +3,4 @@ description: Validate schema, uniqueness, completeness, validity, reconciliation allowed_nodes: [gen_sql, reflect, fix] enabled: false priority: 85 +selection_keywords: ["null", "missing", "duplicate", "freshness", "reconcile", "quality", "缺失", "重复", "质量"] diff --git a/queryforge/bundled_skills/governance_and_security/skill.yml b/queryforge/bundled_skills/governance_and_security/skill.yml index 601a761..db8c1fb 100644 --- a/queryforge/bundled_skills/governance_and_security/skill.yml +++ b/queryforge/bundled_skills/governance_and_security/skill.yml @@ -3,3 +3,4 @@ description: Apply data minimization, sensitive-data handling, lineage, retentio allowed_nodes: [plan_mode, gen_sql, reflect, fix] enabled: false priority: 88 +selection_keywords: ["sensitive", "restricted", "retention", "privacy", "权限", "敏感"] diff --git a/queryforge/bundled_skills/ingestion_and_cdc/skill.yml b/queryforge/bundled_skills/ingestion_and_cdc/skill.yml index 397b7bf..23d0ab1 100644 --- a/queryforge/bundled_skills/ingestion_and_cdc/skill.yml +++ b/queryforge/bundled_skills/ingestion_and_cdc/skill.yml @@ -3,3 +3,4 @@ description: Reason about source ingestion, incremental loads, deduplication, an allowed_nodes: [plan_mode, gen_sql, reflect, fix] enabled: false priority: 80 +selection_keywords: ["ingestion", "cdc", "incremental", "deduplication", "增量"] diff --git a/queryforge/bundled_skills/observability_and_operations/skill.yml b/queryforge/bundled_skills/observability_and_operations/skill.yml index 7438d58..733ce8d 100644 --- a/queryforge/bundled_skills/observability_and_operations/skill.yml +++ b/queryforge/bundled_skills/observability_and_operations/skill.yml @@ -3,3 +3,4 @@ description: Define freshness, volume, failure, lineage, and recovery signals fo allowed_nodes: [plan_mode, reflect, fix] enabled: false priority: 55 +selection_keywords: ["alert", "monitor", "failure rate", "告警"] diff --git a/queryforge/bundled_skills/performance_optimization/skill.yml b/queryforge/bundled_skills/performance_optimization/skill.yml index bbeee9a..3958ded 100644 --- a/queryforge/bundled_skills/performance_optimization/skill.yml +++ b/queryforge/bundled_skills/performance_optimization/skill.yml @@ -3,3 +3,4 @@ description: Reduce scanned data and expensive operations without changing query allowed_nodes: [gen_sql, reflect, fix] enabled: false priority: 60 +selection_keywords: ["slow", "optimize", "performance", "explain", "性能", "慢查询"] diff --git a/queryforge/bundled_skills/requirements_and_contracts/skill.yml b/queryforge/bundled_skills/requirements_and_contracts/skill.yml index e01d3d3..05d5dc5 100644 --- a/queryforge/bundled_skills/requirements_and_contracts/skill.yml +++ b/queryforge/bundled_skills/requirements_and_contracts/skill.yml @@ -3,3 +3,4 @@ description: Translate analytical requirements into explicit grain, keys, metric allowed_nodes: [plan_mode, gen_sql, reflect] enabled: false priority: 90 +selection_keywords: ["contract", "requirements", "metric definition", "口径", "契约"] diff --git a/queryforge/bundled_skills/sql_best_practices/skill.yml b/queryforge/bundled_skills/sql_best_practices/skill.yml index ea6d394..0fe556f 100644 --- a/queryforge/bundled_skills/sql_best_practices/skill.yml +++ b/queryforge/bundled_skills/sql_best_practices/skill.yml @@ -3,3 +3,4 @@ description: Generate safe, readable, deterministic, and efficient analytical SQ allowed_nodes: [gen_sql, reflect, fix] enabled: true priority: 100 +selection_keywords: [] diff --git a/queryforge/bundled_skills/transformation_and_orchestration/skill.yml b/queryforge/bundled_skills/transformation_and_orchestration/skill.yml index c1d1f63..295ad8f 100644 --- a/queryforge/bundled_skills/transformation_and_orchestration/skill.yml +++ b/queryforge/bundled_skills/transformation_and_orchestration/skill.yml @@ -3,3 +3,4 @@ description: Design idempotent transformations with explicit dependencies, stage allowed_nodes: [plan_mode, gen_sql, reflect, fix] enabled: false priority: 70 +selection_keywords: ["backfill", "idempotent", "pipeline", "transform", "回填"] diff --git a/queryforge/core/config.py b/queryforge/core/config.py index ff37858..45a4f63 100644 --- a/queryforge/core/config.py +++ b/queryforge/core/config.py @@ -73,6 +73,7 @@ class Config: report_max_rows: int = 50 report_max_charts: int = 3 report_output_dir: str = ".queryforge/reports" + report_retention_days: int = 30 mcp_resources_enabled: bool = True mcp_prompts_enabled: bool = True mcp_session_enabled: bool = True @@ -223,6 +224,7 @@ def load_config( os.getenv("REPORT_MAX_CHARTS"), default=3, minimum=1 ), report_output_dir=os.getenv("REPORT_OUTPUT_DIR", ".queryforge/reports"), + report_retention_days=min(_environment_int(os.getenv("REPORT_RETENTION_DAYS"), default=30, minimum=1), 3650), mcp_resources_enabled=_environment_bool( os.getenv("MCP_RESOURCES_ENABLED"), default=True ), diff --git a/queryforge/core/outcomes.py b/queryforge/core/outcomes.py index e5ad48c..21985a8 100644 --- a/queryforge/core/outcomes.py +++ b/queryforge/core/outcomes.py @@ -88,6 +88,8 @@ def normalize_outcome(value: Any) -> TerminalOutcome | None: "degraded": "partial", "error": "failed", "canceled": "cancelled", + "unsupported": "blocked", + "unverified": "blocked", } #: Transport event protocol outcomes. Deliberately smaller than the canonical set: @@ -117,7 +119,7 @@ def derive_outcome( 2. a recorded gate block wins (a deterministic gate refused the stage and recorded why) — this is the case E-02 got wrong; 3. otherwise the workflow's own result status, normalised; - 4. otherwise the run is treated as succeeded. + 4. otherwise fail closed: no recognized terminal result proves success. """ if cancelled: @@ -126,10 +128,7 @@ def derive_outcome( return "blocked" normalized = normalize_outcome(result_status) if normalized is None: - # Not a terminal spelling: an unknown or non-terminal value is treated as - # a success, which matches the historical behaviour of defaulting to - # "success" while making the decision explicit and testable. - return "succeeded" + return "failed" return normalized diff --git a/queryforge/domain/analysis/diagnostics.py b/queryforge/domain/analysis/diagnostics.py new file mode 100644 index 0000000..ad50123 --- /dev/null +++ b/queryforge/domain/analysis/diagnostics.py @@ -0,0 +1,84 @@ +"""Reconcile category changes with independently queried period totals.""" +from __future__ import annotations + +import json +import math +from typing import Any + +from .analysis_tools import numbers_close + + +def reconcile_buckets(dataset: dict[str, Any], totals: dict[str, Any], metric: str, + current_period: str, baseline_period: str) -> dict[str, Any]: + """Prove both period populations before decomposing their difference. + + Empty category buckets are zero only with enforced ingestion coverage and + complete, unbounded query results. Independently queried totals also catch + rows lost at dimension joins, even when those losses cancel in the delta. + """ + if any(source.get("truncated") or ( + (source.get("query_spec") or {}).get("limit") + and len(source.get("rows", [])) >= source["query_spec"]["limit"] + ) for source in (dataset, totals)): + raise ValueError("unverified_reconciliation: bounded results cannot prove all categories") + metadata = dataset.get("metric_contracts", {}).get(metric, {}) + if metadata.get("additivity") != "additive" or any( + ref in metadata.get("non_additive_dimensions", []) for ref in dataset.get("dimensions", []) + ): + raise ValueError("unsupported_additivity: category deltas require an additive metric") + if (dataset.get("filters") != totals.get("filters") + or metadata != totals.get("metric_contracts", {}).get(metric) + or dataset.get("time_grain") != totals.get("time_grain") + or dataset.get("time_filter") != totals.get("time_filter")): + raise ValueError("unverified_reconciliation: totals and buckets have different populations") + dimensions = dataset.get("dimensions", []) + if len(dimensions) < 2 or totals.get("dimensions") != dimensions[:1]: + raise ValueError("unsupported_grain: need one time dimension followed by category dimensions") + def measure(row, columns): + value = row[columns.index(metric)] + if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value): + raise ValueError("unverified_measure: category values must be finite numbers") + return value + total_values = {} + for row in totals.get("rows", []): + period = str(row[0]) + if period in total_values: + raise ValueError("unverified_reconciliation: duplicate total period") + total_values[period] = measure(row, totals["columns"]) + if current_period not in total_values or baseline_period not in total_values: + raise ValueError("data_absent: independent current or baseline total is missing") + by_category = {} + for row in dataset.get("rows", []): + period = str(row[0]) + if period not in {current_period, baseline_period}: + continue + key_values = list(row[1:len(dimensions)]) + key = json.dumps(key_values, ensure_ascii=False, separators=(",", ":")) + group = by_category.setdefault(key, {"dimensions": dict(zip(dimensions[1:], key_values)), "periods": {}}) + if period in group["periods"]: + raise ValueError("unverified_reconciliation: duplicate category-period key") + group["periods"][period] = measure(row, dataset["columns"]) + if not by_category: + raise ValueError("data_absent: no category values for the requested periods") + complete = dataset.get("period_completeness") == totals.get("period_completeness") == "complete" + buckets, empty_buckets = [], [] + for key, group in sorted(by_category.items()): + for period in (current_period, baseline_period): + if period not in group["periods"]: + if not complete: + raise ValueError("unverified_empty_bucket: missing category period without complete coverage") + group["periods"][period] = 0 + empty_buckets.append({"category": key, "period": period, "reason": "empty_bucket_in_complete_population"}) + buckets.append({"category": key, "current": group["periods"][current_period], + "baseline": group["periods"][baseline_period], "dimensions": group["dimensions"]}) + current = math.fsum(bucket["current"] for bucket in buckets) + baseline = math.fsum(bucket["baseline"] for bucket in buckets) + if not (numbers_close(current, total_values[current_period]) and numbers_close(baseline, total_values[baseline_period])): + raise ValueError("unverified_reconciliation: category sums disagree with independent period totals") + return {"buckets": buckets, "current_period": current_period, "baseline_period": baseline_period, + "independent_current": total_values[current_period], "independent_baseline": total_values[baseline_period], + "bucket_current_total": current, "bucket_baseline_total": baseline, + "residual_current": current - total_values[current_period], + "residual_baseline": baseline - total_values[baseline_period], + "expected_total_delta": total_values[current_period] - total_values[baseline_period], + "empty_buckets": empty_buckets} diff --git a/queryforge/domain/analysis/evidence.py b/queryforge/domain/analysis/evidence.py index 139b7ea..0cc1427 100644 --- a/queryforge/domain/analysis/evidence.py +++ b/queryforge/domain/analysis/evidence.py @@ -1301,6 +1301,7 @@ def result_findings( KIND_ANOMALY, "aggregate", "metric_value", + "metric_totals", "query_metric", "result_set", "trend", diff --git a/queryforge/domain/semantic/contract_validator.py b/queryforge/domain/semantic/contract_validator.py index 11f8e94..b2f65f1 100644 --- a/queryforge/domain/semantic/contract_validator.py +++ b/queryforge/domain/semantic/contract_validator.py @@ -14,6 +14,7 @@ SemanticEntity, SemanticModel, ) +from queryforge.domain.semantic.periods import invalid_time_sql, time_contract class ContractCheck(BaseModel): @@ -108,6 +109,19 @@ def validate( entity = entity_by_name.get(metric.entity) if entity is None: continue + temporal = time_contract(metric) + if temporal: + invalid = connection.execute( + f'SELECT COUNT(*) FROM "{entity.table}" WHERE {invalid_time_sql(metric.time_field, temporal)}' + ).fetchone()[0] + report.checks.append(ContractCheck( + scope="metric", subject=metric.name, rule="time_values", + status="failed" if invalid else "passed", + expected={"invalid_dates": 0, "role": temporal.role, "timezone": temporal.timezone, + "coverage_start": temporal.coverage_start, "complete_through": temporal.complete_through}, + observed={"invalid_dates": invalid}, + message="Coverage bounds are an authored ingestion guarantee; sparse fact dates do not establish completeness.", + )) cls._validate_rules( connection, report, diff --git a/queryforge/domain/semantic/model.py b/queryforge/domain/semantic/model.py index 22592d8..af291ce 100644 --- a/queryforge/domain/semantic/model.py +++ b/queryforge/domain/semantic/model.py @@ -269,6 +269,10 @@ def validate_physical_references( "in expression" ) expressions = [metric.expression, *metric.default_filters] + if metric.analysis: + for dimension in metric.analysis.non_additive_dimensions: + if dimension not in metric.allowed_dimensions: + errors.append(f"metric {metric.name!r} non-additive dimension {dimension!r} must be allowed") for expression in expressions: references = cls._extract_physical_references(expression) if not references: @@ -665,7 +669,14 @@ def match_question( @staticmethod def match_metrics(model: SemanticModel, question: str) -> list[MetricMatch]: - normalized_question = SemanticModelLoader._normalize(question) + from queryforge.domain.semantic.request_contract import measure_intent + + intent = measure_intent(question) + # Contextual mentions and output labels are not requested measures. + intent = re.sub(r"\b(?:across|over) all \w+\b", "", intent, flags=re.I) + normalized_question = SemanticModelLoader._normalize(intent) + count_request = bool(re.search(r"\b(?:how many|count|number of)\b|数量|多少", intent, re.I)) + detail_request = bool(re.search(r"\b(?:list|show)\b.*\b(?:identifiers|ids)\b|编号列表", intent, re.I)) candidates: list[tuple[int, int, MetricMatch]] = [] for metric_index, metric in enumerate(model.metrics): matching_terms = [ @@ -675,6 +686,13 @@ def match_metrics(model: SemanticModel, question: str) -> list[MetricMatch]: ] if matching_terms: term = max(matching_terms, key=lambda item: len(item)) + explicit = SemanticModelLoader._contains_term(normalized_question, metric.name) + if not explicit and detail_request and metric.aggregation == "count": + continue + if not explicit and count_request and metric.aggregation == "ratio" and not re.search( + r"\b(?:average|avg|rate|ratio|aov|ctr)\b|平均|比例|率", intent, re.I + ): + continue candidates.append( ( -len(SemanticModelLoader._normalize(term)), @@ -683,7 +701,20 @@ def match_metrics(model: SemanticModel, question: str) -> list[MetricMatch]: ) ) candidates.sort(key=lambda item: (item[0], item[1])) - return [item[2] for item in candidates[:3]] + # Prefer a specific phrase over an embedded generic synonym (e.g. sales). + selected = [] + for _, _, match in candidates: + term = SemanticModelLoader._normalize(match.matched_term) + occurrences = [(item.start(), item.end()) for item in re.finditer( + rf"(? len(term)] + if occurrences and all(any(left <= start and end <= right for left, right in covered) + for start, end in occurrences): + continue + selected.append(match) + return selected @staticmethod def _validate_columns( diff --git a/queryforge/domain/semantic/output_lineage.py b/queryforge/domain/semantic/output_lineage.py new file mode 100644 index 0000000..e0b9446 --- /dev/null +++ b/queryforge/domain/semantic/output_lineage.py @@ -0,0 +1,44 @@ +"""Expressions that actually contribute to the final query projection.""" + +from sqlglot import exp +from sqlglot.optimizer.scope import Scope + + +def output_dependencies(root, scope_by_expression): + nodes: set[int] = set() + visited: set[tuple[int, int]] = set() + + def visit(node, scope, depth=0): + if depth > 64: + raise ValueError("Output lineage exceeds the deterministic depth bound") + if not isinstance(node, exp.Expression) or scope is None: + return + key = (id(node), id(scope)) + if key in visited: + return + visited.add(key) + nodes.add(id(node)) + if isinstance(node, exp.Select): + scope = scope_by_expression.get(id(node), scope) + for projection in node.selects: + visit(projection, scope, depth + 1) + return + if isinstance(node, exp.Subquery): + visit(node.this, scope_by_expression.get(id(node.this)), depth + 1) + return + if isinstance(node, (exp.Column, exp.Star)): + for name, (_, source) in scope.selected_sources.items(): + if isinstance(node, exp.Column) and node.table and node.table.casefold() != name.casefold(): + continue + if not isinstance(source, Scope) or not isinstance(source.expression, exp.Select): + continue + for index, projection in enumerate(source.expression.selects): + label = (source.outer_columns[index] if index < len(source.outer_columns) else projection.alias_or_name) + if node.is_star or label.casefold() == node.name.casefold(): + visit(projection, source, depth + 1) + return + for child in node.iter_expressions(): + visit(child, scope_by_expression.get(id(child), scope), depth + 1) + + visit(root, scope_by_expression.get(id(root))) + return nodes diff --git a/queryforge/domain/semantic/periods.py b/queryforge/domain/semantic/periods.py new file mode 100644 index 0000000..d8d3e18 --- /dev/null +++ b/queryforge/domain/semantic/periods.py @@ -0,0 +1,140 @@ +"""Calendar arithmetic shared by deterministic compilation and comparison. + +Week labels are Monday dates. Fiscal quarters/years use their start dates. +Coverage is an authored ingestion guarantee, not inferred from sparse fact rows. +""" +from __future__ import annotations + +import calendar +from datetime import date, timedelta + +from .query_constraints import UnsupportedConstraint + + +def time_contract(metric): + return metric.analysis.time if metric.analysis else None + + +def calendar_source_sql(reference): + text = f"CAST({reference} AS TEXT)" + return (f"CASE WHEN {text} GLOB '[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]' " + f"THEN SUBSTR({text}, 1, 4) || '-' || SUBSTR({text}, 5, 2) || '-' || SUBSTR({text}, 7, 2) " + f"ELSE {text} END") + + +def calendar_sql(reference, contract=None): + source = calendar_source_sql(reference) + modifier = f", '{contract.timezone}'" if contract and contract.timezone != "UTC" else "" + return f"DATE({source}{modifier})" + + +def invalid_time_sql(reference, contract=None): + source = calendar_source_sql(reference) + civil = f"SUBSTR({source}, 1, 10)" + return f"({calendar_sql(reference, contract)} IS NULL OR DATE({civil}) IS NULL OR DATE({civil}) != {civil})" + + +def bucket_sql(reference, grain, contract=None): + day = calendar_sql(reference, contract) + fiscal = contract.fiscal_year_start_month if contract else 1 + if grain == "weekly": + return f"DATE({day}, '-' || ((CAST(STRFTIME('%w', {day}) AS INTEGER) + 6) % 7) || ' days')" + formats = {"daily": "%Y-%m-%d", "monthly": "%Y-%m", "yearly": "%Y"} + if fiscal != 1 and grain in {"quarterly", "yearly"}: + shifted = f"DATE({day}, 'start of month', '-{fiscal - 1} months')" + start = (f"STRFTIME('%Y', {shifted}) || '-' || " + f"PRINTF('%02d', ((CAST(STRFTIME('%m', {shifted}) AS INTEGER) - 1) / 3) * 3 + 1) || '-01'" + if grain == "quarterly" else f"STRFTIME('%Y', {shifted}) || '-01-01'") + return f"DATE({start}, '+{fiscal - 1} months')" + if grain in formats: + return f"STRFTIME('{formats[grain]}', {day})" + if grain == "quarterly": + return (f"STRFTIME('%Y', {day}) || '-Q' || " + f"CAST((CAST(STRFTIME('%m', {day}) AS INTEGER) + 2) / 3 AS INTEGER)") + return None + + +def month_shift(day, months): + year, month = divmod(day.year * 12 + day.month - 1 + months, 12) + return date(year, month + 1, min(day.day, calendar.monthrange(year, month + 1)[1])) + + +def period_bounds(day, grain, contract=None): + fiscal = contract.fiscal_year_start_month if contract else 1 + if grain == "daily": + return day, day + if grain == "weekly": + start = day - timedelta(days=day.weekday()) + return start, start + timedelta(days=6) + start = day.replace(day=1) + if grain == "monthly": + return start, month_shift(start, 1) - timedelta(days=1) + if grain in {"quarterly", "yearly"}: + year_start = date(day.year - (day.month < fiscal), fiscal, 1) + months = ((day.year - year_start.year) * 12 + day.month - fiscal) + start = month_shift(year_start, (months // 3) * 3) if grain == "quarterly" else year_start + return start, month_shift(start, 3 if grain == "quarterly" else 12) - timedelta(days=1) + raise UnsupportedConstraint(f"unsupported_time_grain: {grain}") + + +def label_date(label): + try: + if "-Q" in label: + year, quarter = label.split("-Q") + return date(int(year), int(quarter) * 3 - 2, 1) + return date.fromisoformat(label if len(label) == 10 else label + ("-01" if len(label) == 7 else "-01-01")) + except ValueError as exc: + raise UnsupportedConstraint(f"unsupported_calendar_period: {label}") from exc + + +def period_label(day, grain, contract=None): + start, _ = period_bounds(day, grain, contract) + if grain in {"daily", "weekly"} or (contract and contract.fiscal_year_start_month != 1 and grain in {"quarterly", "yearly"}): + return start.isoformat() + if grain == "monthly": + return start.strftime("%Y-%m") + if grain == "quarterly": + return f"{start.year:04d}-Q{(start.month - 1) // 3 + 1}" + return str(start.year) + + +def baseline_day(day, baseline, grain): + if baseline in {"same_period_last_year", "previous_year"}: + try: + return day.replace(year=day.year - 1) + except ValueError as exc: + raise UnsupportedConstraint("unsupported_baseline: leap day has no same calendar day last year") from exc + if baseline == "previous_month" and grain != "monthly": + raise UnsupportedConstraint("unsupported_baseline: previous_month requires monthly grain") + if baseline == "previous_quarter" and grain != "quarterly": + raise UnsupportedConstraint("unsupported_baseline: previous_quarter requires quarterly grain") + if baseline not in {"previous_period", "previous_month", "previous_quarter"}: + raise UnsupportedConstraint(f"unsupported_baseline: {baseline}") + if grain in {"daily", "weekly"}: + return day - timedelta(days=7 if grain == "weekly" else 1) + return month_shift(day, {"monthly": -1, "quarterly": -3, "yearly": -12}[grain]) + + +def comparison_context(context, baseline, grain, contract=None): + if not context or not baseline or not grain: + return context + ranges = list(context.ranges) + for span in context.ranges: + first, last = date.fromisoformat(span.start_date), date.fromisoformat(span.end_date) + # Include the complete baseline buckets, never a clipped month-end shift. + start, _ = period_bounds(baseline_day(period_bounds(first, grain, contract)[0], baseline, grain), grain, contract) + _, end = period_bounds(baseline_day(period_bounds(last, grain, contract)[0], baseline, grain), grain, contract) + ranges.append(span.model_copy(update={"expression": "comparison baseline:" + baseline, + "start_date": start.isoformat(), "end_date": end.isoformat()})) + return context.model_copy(update={"ranges": ranges}) + + +def require_complete_period(label, grain, contract, requested_ranges=()): + start, end = period_bounds(label_date(label), grain, contract) + if not contract or not contract.require_complete_periods: + return "unverified" + if start < date.fromisoformat(contract.coverage_start) or end > date.fromisoformat(contract.complete_through): + raise UnsupportedConstraint(f"incomplete_period: {label} is outside declared complete coverage") + if requested_ranges and not any(date.fromisoformat(span[0]) <= start and date.fromisoformat(span[1]) >= end for span in requested_ranges): + raise UnsupportedConstraint(f"incomplete_period: requested window clips {label}") + return "complete" diff --git a/queryforge/domain/semantic/query_constraints.py b/queryforge/domain/semantic/query_constraints.py new file mode 100644 index 0000000..c8ea8be --- /dev/null +++ b/queryforge/domain/semantic/query_constraints.py @@ -0,0 +1,177 @@ +"""Bound literal request predicates to reviewed semantic columns. + +These helpers parse expressions only. Execution and physical column authorization +remain owned by DatabaseTool; unsupported expressions never become raw SQL tails. +""" + +from __future__ import annotations + +import re + +import sqlglot +from sqlglot import exp + +from queryforge.domain.semantic.schemas import SemanticModel, SemanticMetric + + +class UnsupportedConstraint(ValueError): + pass + + +def _mask_literals(text: str) -> str: + return re.sub(r"'(?:[^']|'')*'", lambda m: " " * len(m.group()), text) + + +def literal_predicate(text: str) -> exp.Expression: + """Accept only column/literal predicates, never functions or query clauses.""" + if re.search(r";|--|/\*|\*/", _mask_literals(text)): + raise UnsupportedConstraint("comments and multiple statements are unsupported") + try: + trees = sqlglot.parse(f"SELECT 1 WHERE {text}", read="sqlite") + except Exception as exc: + raise UnsupportedConstraint("filter cannot be parsed") from exc + if len(trees) != 1 or not isinstance(trees[0], exp.Select): + raise UnsupportedConstraint("filter must be one predicate") + tree = trees[0] + if any(value for key, value in tree.args.items() if key not in {"expressions", "where"}): + raise UnsupportedConstraint("query clauses are not filters") + where = tree.args.get("where") + if where is None: + raise UnsupportedConstraint("empty filter") + + def scalar(node): + return isinstance(node, (exp.Literal, exp.Null, exp.Boolean)) or ( + isinstance(node, exp.Neg) and isinstance(node.this, exp.Literal) + and not node.this.is_string + ) + + def check(node): + if isinstance(node, (exp.Paren, exp.Not)): + return check(node.this) + if isinstance(node, (exp.And, exp.Or)): + return check(node.this) and check(node.expression) + if isinstance(node, (exp.EQ, exp.NEQ, exp.GT, exp.GTE, exp.LT, exp.LTE, exp.Is)): + return isinstance(node.this, exp.Column) and scalar(node.expression) + if isinstance(node, exp.In): + return (isinstance(node.this, exp.Column) and not node.args.get("query") + and bool(node.expressions) and all(scalar(v) for v in node.expressions)) + if isinstance(node, exp.Between): + return (isinstance(node.this, exp.Column) and scalar(node.args.get("low")) + and scalar(node.args.get("high"))) + return False + + predicate = where.this + if not check(predicate) or any(node.comments for node in tree.walk()): + raise UnsupportedConstraint("only column comparisons with literal values are supported") + return predicate + + +def extract_filters(question: str) -> tuple[str, list[str]]: + """Separate explicit filter text from metric/grouping intent. + + Quoted values cannot introduce a marker or a trailing grouping instruction. + Non-temporal 'for/with' clauses must use literal comparison syntax; an + unparsed slice cannot silently turn into an unrestricted total. + """ + masked = _mask_literals(question) + marker = re.search( + r"\b(?:where|filtered\s+by|only\s+include)\b|只看|仅看|筛选|条件为|其中", masked, re.I + ) + if marker is None: + marker = re.search( + r"\b(?:for|with)\s+(?=[\w.\"\s]+(?:=|!=|<>|<=|>=|<|>|\bIN\b|\bIS\b|\bBETWEEN\b))", + masked, re.I, + ) + if marker is None: + informal = re.search(r"\b(?:for|with)\s+", masked, re.I) + if informal: + tail = question[informal.end():].strip() + temporal = re.match( + r"(?:\d{4}\b|Q[1-4]\b|(?:the\s+)?(?:last|previous|past|this|next)\s+" + r"(?:\d+\s+)?(?:days?|weeks?|months?|quarters?|years?)\b" + r"|(?:Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?" + r"|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?)\b)", + tail, re.I, + ) + if not temporal: + raise UnsupportedConstraint("non-temporal for/with clauses require a literal comparison") + return question, [] + tail = question[marker.end():].strip() + boundary = re.search(r"\s+(?:by|grouped\s+by|按)\s*", _mask_literals(tail), re.I) + rest = tail[boundary.start():] if boundary else "" + fragment = tail[:boundary.start()] if boundary else tail + fragment = fragment.strip().rstrip("??。") + predicate = literal_predicate(fragment) + return question[:marker.start()] + rest, [predicate.sql(dialect="sqlite")] + + +def bind_filters(model: SemanticModel, metrics: list[SemanticMetric], filters: list[str]) -> list[str]: + """Resolve an unqualified column to the metric base entity, fail closed.""" + entity = next(e for e in model.entities if e.name == metrics[0].entity) + columns = set(entity.expected_columns + entity.primary_key + entity.grain) + columns.update(d.column for d in entity.dimensions) + for metric in metrics: + parsed = sqlglot.parse_one(f"SELECT {metric.expression}", read="sqlite") + columns.update(c.name for c in parsed.find_all(exp.Column) if c.table == entity.table) + columns.difference_update(entity.hidden_columns) + bound = [] + for text in filters: + predicate = literal_predicate(text) + for column in predicate.find_all(exp.Column): + if column.db or column.catalog: + raise UnsupportedConstraint("database-qualified filters are unsupported") + # Cross-fact filters must name a conformed, governed dimension. An + # unqualified fact-local predicate has no common population meaning. + targets = [e for e in model.entities if column.table in {e.name, e.table} + and any(d.column == column.name for d in e.dimensions) + and column.name not in e.hidden_columns] + if targets and (targets[0].name != entity.name or len({m.entity for m in metrics}) > 1): + target = targets[0] + references = [f"{target.name}.{d.name}" for d in target.dimensions if d.column == column.name] + if any(not any(ref in m.allowed_dimensions for ref in references) for m in metrics): + raise UnsupportedConstraint("filter dimension must be allowed by every requested metric") + column.set("table", exp.to_identifier(target.table)) + continue + if len({m.entity for m in metrics}) > 1: + raise UnsupportedConstraint("cross-fact filters require a qualified conformed dimension") + if (column.name not in columns or column.db or column.catalog + or column.table not in {"", entity.table, entity.name}): + raise UnsupportedConstraint(f"unknown or unavailable filter column {column.sql()!r}") + column.set("table", exp.to_identifier(entity.table)) + bound.append(predicate.sql(dialect="sqlite")) + return bound + + +def require_filter_predicates(sql: str, filters: list[str], *, metric_ctes: list[str] | None = None) -> None: + """Prove each requested predicate is a mandatory WHERE conjunct. + + Looking for a column or literal anywhere in SQL is insufficient: an OR + branch could make the requested restriction optional. Compiled queries use + exact predicates, so AST equality is a conservative delivery check. + """ + if not filters: + return + try: + tree = sqlglot.parse_one(sql, read="sqlite") + except Exception as exc: + raise UnsupportedConstraint("compiled filter SQL cannot be verified") from exc + scopes = [tree] + if metric_ctes: + ctes = {cte.alias: cte.this for cte in tree.find_all(exp.CTE)} + if any(name not in ctes for name in metric_ctes): + raise UnsupportedConstraint("request_incomplete: missing metric aggregation scope") + scopes = [ctes[name] for name in metric_ctes] + + def conjuncts(node): + if isinstance(node, exp.Paren): + return conjuncts(node.this) + if isinstance(node, exp.And): + return conjuncts(node.this) + conjuncts(node.expression) + return [node] + + for scope in scopes: + where = scope.args.get("where") if isinstance(scope, exp.Select) else None + observed = conjuncts(where.this) if where else [] + for text in filters: + if any(predicate not in observed for predicate in conjuncts(literal_predicate(text))): + raise UnsupportedConstraint("request_incomplete: SQL is missing a mandatory filter predicate") diff --git a/queryforge/domain/semantic/request_contract.py b/queryforge/domain/semantic/request_contract.py new file mode 100644 index 0000000..864593c --- /dev/null +++ b/queryforge/domain/semantic/request_contract.py @@ -0,0 +1,65 @@ +"""Explicit output labels and measure intent, independent of model verdicts.""" + +from __future__ import annotations + +import re + +import sqlglot +from sqlglot import exp + + +_LABEL = r"[A-Za-z_][A-Za-z0-9_]*" +_RETURN = re.compile( + rf"\breturn\s+(?:(?:a single|one|a) column named\s+|only\s+)?" + rf"(?P{_LABEL}(?:\s*(?:,|and)\s*{_LABEL})*)" + r"(?=\s*(?:[.]|$|,\s*(?:sorted by|in that order)|\s+in one row))", + re.IGNORECASE, +) +_CHINESE_RETURN = re.compile(rf"(?:仅|只)返回\s*(?P{_LABEL})\s*列") + + +def output_contract(question: str) -> tuple[str, ...]: + """Recognize formal identifier lists only; ordinary prose remains intent.""" + match = _RETURN.search(question) or _CHINESE_RETURN.search(question) + if match is None: + return () + return tuple(re.split(r"\s*(?:,|\band\b)\s*", match["labels"], flags=re.I)) + + +def measure_intent(question: str) -> str: + match = _RETURN.search(question) or _CHINESE_RETURN.search(question) + return question[:match.start()] if match else question + + +def validate_output_contract(question: str, sql: str) -> str | None: + required = output_contract(question) + if not required: + return None + try: + statements = [item for item in sqlglot.parse(sql, read="sqlite") if item] + root = statements[0] if len(statements) == 1 else None + if not isinstance(root, exp.Select) or any(item.is_star for item in root.selects): + raise ValueError("final projection is not an explicit SELECT") + actual = tuple(item.alias_or_name for item in root.selects) + if actual == required: + if re.search(r"\b(?:list|show)\b.*\b(?:identifiers|ids)\b", measure_intent(question), re.I): + from sqlglot.optimizer.scope import traverse_scope + from queryforge.domain.semantic.output_lineage import output_dependencies + scopes = {id(scope.expression): scope for scope in traverse_scope(root)} + dependencies = output_dependencies(root, scopes) + if any(id(node) in dependencies for node in root.find_all(exp.AggFunc)): + return "Output contract requests identifiers; an aggregate cannot satisfy the list." + if any(id(node) in dependencies and not isinstance(node, (exp.Select, exp.Alias, exp.Column, exp.Identifier)) for node in root.walk()): + return "Output contract requests original identifiers; transformed or constant values cannot satisfy the list." + if any(not isinstance(item.this if isinstance(item, exp.Alias) else item, exp.Column) for item in root.selects): + return "Output contract requests identifiers as explicit columns." + return None + except (sqlglot.errors.ParseError, ValueError): + actual = () + return f"Output contract requires columns {list(required)} in order; observed {list(actual)}." + + +def null_filter_terms(question: str) -> tuple[str, ...]: + text = re.sub(r"'([^']|'')*'", " ", measure_intent(question)) + matches = re.findall(r"\b(?:have|has|with)\s+(?:a\s+)?NULL\s+(\w+)\b|\b(\w+)\s+IS\s+NULL\b", text, re.I) + return tuple(left or right for left, right in matches) diff --git a/queryforge/domain/semantic/schemas.py b/queryforge/domain/semantic/schemas.py index 17b234d..78dc565 100644 --- a/queryforge/domain/semantic/schemas.py +++ b/queryforge/domain/semantic/schemas.py @@ -3,6 +3,8 @@ from __future__ import annotations from typing import Literal +from datetime import date +import re from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator @@ -185,6 +187,97 @@ class ResolvedJoinPath(StrictSemanticModel): explicit: bool = False +class RatioComponents(StrictSemanticModel): + """Aggregate both populations at the requested grain before division.""" + + numerator: str = Field(min_length=1) + denominator: str = Field(min_length=1) + scale: float = Field(default=1.0, gt=0, allow_inf_nan=False) + + @field_validator("numerator", "denominator") + @classmethod + def aggregate_expression(cls, value: str) -> str: + import sqlglot + from sqlglot import exp + + nodes = [node for node in sqlglot.parse(value, read="sqlite") if node is not None] + if len(nodes) != 1 or any(marker in value for marker in (";", "--", "/*", "*/")): + raise ValueError("ratio components must be one expression without comments") + node = nodes[0] + # A component is one aggregate over rows, never an average of ratios or + # an unrelated subquery population. More complex definitions need review. + if not isinstance(node, (exp.Sum, exp.Count)) or any( + isinstance(child, (exp.Select, exp.Div, exp.AggFunc)) + for child in node.walk() if child is not node + ): + raise ValueError("ratio components must be a single SUM or COUNT aggregate") + if any(not column.table or column.db or column.catalog for column in node.find_all(exp.Column)): + raise ValueError("ratio component columns must be qualified table.column references") + return node.sql(dialect="sqlite") + + @property + def expression(self) -> str: + return (f"CAST({self.numerator} AS REAL) * {self.scale} / " + f"NULLIF({self.denominator}, 0)") + + +class MetricTimeContract(StrictSemanticModel): + role: str = Field(min_length=1) + timezone: str = "UTC" + fiscal_year_start_month: int = Field(default=1, ge=1, le=12) + coverage_start: str | None = None + complete_through: str | None = None + require_complete_periods: bool = False + + @field_validator("role") + @classmethod + def nonblank_role(cls, value: str) -> str: + if not value.strip(): + raise ValueError("time role must not be blank") + return value.strip() + + @field_validator("timezone") + @classmethod + def supported_timezone(cls, value: str) -> str: + if value == "UTC": + return value + if not re.fullmatch(r"[+-](?:0\d|1[0-3]):[0-5]\d|[+-]14:00", value): + raise ValueError("SQLite time contracts support UTC or fixed offsets (+08:00); named DST zones are unsupported") + return value + + @model_validator(mode="after") + def coverage_contract(self) -> "MetricTimeContract": + if bool(self.coverage_start) != bool(self.complete_through): + raise ValueError("coverage_start and complete_through must be declared together") + if self.require_complete_periods and not self.coverage_start: + raise ValueError("complete period enforcement requires declared coverage bounds") + if self.coverage_start: + start, end = date.fromisoformat(self.coverage_start), date.fromisoformat(self.complete_through) + if start > end: + raise ValueError("coverage_start must not exceed complete_through") + return self + + +class MetricAnalysisContract(StrictSemanticModel): + unit: str = Field(min_length=1) + additivity: Literal["additive", "non_additive", "semi_additive"] + non_additive_dimensions: list[str] = Field(default_factory=list) + time: MetricTimeContract | None = None + + @field_validator("unit") + @classmethod + def nonblank_unit(cls, value: str) -> str: + if not value.strip(): + raise ValueError("metric unit must not be blank") + return value.strip() + + @model_validator(mode="after") + def semi_additive_dimensions(self) -> "MetricAnalysisContract": + if self.additivity == "semi_additive" and not self.non_additive_dimensions: + raise ValueError("semi_additive metrics require non_additive_dimensions") + return self + + class SemanticMetric(OperationalContract): name: str = Field(min_length=1) description: str = Field(min_length=1) @@ -195,6 +288,35 @@ class SemanticMetric(OperationalContract): default_filters: list[str] = Field(default_factory=list) allowed_dimensions: list[str] = Field(default_factory=list) time_field: str | None = None + ratio: RatioComponents | None = None + analysis: MetricAnalysisContract | None = None + + @model_validator(mode="before") + @classmethod + def materialize_ratio(cls, data): + if isinstance(data, dict) and data.get("ratio") is not None: + data = dict(data) + ratio = RatioComponents.model_validate(data["ratio"]) + canonical = ratio.expression + if data.get("expression") and data["expression"] != canonical: + raise ValueError("ratio expression must match its declared components; omit expression to derive it") + data["expression"] = canonical + return data + + @model_validator(mode="after") + def analysis_consistency(self) -> "SemanticMetric": + if self.ratio and self.aggregation != "ratio": + raise ValueError("ratio components require ratio aggregation") + if self.analysis: + distinct = bool(re.search(r"\bDISTINCT\b", self.expression, re.I)) + if (self.aggregation == "ratio" or distinct) and self.analysis.additivity != "non_additive": + raise ValueError("ratios and distinct counts must be non_additive") + if self.analysis.time and not self.time_field: + raise ValueError("a time contract requires time_field") + if (self.analysis.time and self.time_field.endswith("_key") + and self.analysis.time.timezone != "UTC"): + raise ValueError("date keys already represent calendar dates; timezone shifts require timestamps") + return self @field_validator("name", "description", "entity", "expression") @classmethod diff --git a/queryforge/domain/semantic/sql_validator.py b/queryforge/domain/semantic/sql_validator.py index 8972c8f..fd183e9 100644 --- a/queryforge/domain/semantic/sql_validator.py +++ b/queryforge/domain/semantic/sql_validator.py @@ -19,7 +19,9 @@ from __future__ import annotations from dataclasses import dataclass +from decimal import Decimal from typing import Any, Literal +import re import sqlglot from sqlglot import exp @@ -27,6 +29,8 @@ from pydantic import BaseModel, ConfigDict, Field from queryforge.domain.semantic.model import SemanticModelLoader +from queryforge.domain.semantic.query_constraints import bind_filters, literal_predicate, require_filter_predicates +from queryforge.domain.semantic.periods import bucket_sql, calendar_sql, comparison_context, time_contract, invalid_time_sql from queryforge.domain.semantic.schemas import ( MetricMatch, ResolvedJoinPath, @@ -188,6 +192,8 @@ def __init__(self, root: exp.Expression, table_columns: dict[str, set[str]]) -> self.table_columns = table_columns self.scopes: list[Scope] = list(traverse_scope(root)) self.scope_by_expression = {id(scope.expression): scope for scope in self.scopes} + from queryforge.domain.semantic.output_lineage import output_dependencies + self.output_nodes = output_dependencies(root, self.scope_by_expression) self.cte_names = { cte.alias_or_name.casefold() for cte in root.find_all(exp.CTE) @@ -275,7 +281,17 @@ def _resolve_source( self, source: Any, column_name: str, depth: int ) -> set[tuple[str, str]]: if isinstance(source, Scope): - return self._resolve_unqualified(source, column_name, depth + 1) + if depth > 8 or not isinstance(source.expression, exp.Select): + return set() + resolved = set() + for index, projection in enumerate(source.expression.selects): + label = source.outer_columns[index] if source.outer_columns else projection.alias_or_name + if projection.is_star: + resolved |= self._resolve_unqualified(source, column_name, depth + 1) + elif label.casefold() == column_name.casefold(): + for column in projection.find_all(exp.Column): + resolved |= self.resolve_column(source, column, depth + 1) + return resolved if isinstance(source, exp.Table): return {(source.name, column_name)} return set() @@ -286,7 +302,7 @@ def _resolve_unqualified( if depth > 8: return set() resolved: set[tuple[str, str]] = set() - for source in scope.sources.values(): + for _, source in scope.selected_sources.values(): resolved |= self._resolve_source(source, column_name, depth + 1) return resolved @@ -374,6 +390,8 @@ def aggregates(self) -> list[tuple[exp.Expression, _Aggregate]]: if not isinstance(expression, (exp.Select, exp.Union)): continue for aggregate in expression.find_all(exp.AggFunc): + if id(aggregate) not in self.output_nodes: + continue if id(aggregate) in seen: continue seen.add(id(aggregate)) @@ -442,12 +460,24 @@ def __init__( metric_join_paths: list[ResolvedJoinPath] | None = None, requested_dimensions: list[str] | None = None, date_context: Any | None = None, + time_grain: str | None = None, + comparison_baseline: str | None = None, + user_filters: list[str] | None = None, + non_null_columns: set[tuple[str, str]] | None = None, + unique_columns: set[tuple[str, str]] | None = None, + null_filter_terms: tuple[str, ...] = (), ) -> None: self.semantic_model = semantic_model self.metric_matches = list(metric_matches) self.metric_join_paths = list(metric_join_paths or []) self.requested_dimensions = list(requested_dimensions or []) self.date_context = date_context + self.time_grain = time_grain + self.comparison_baseline = comparison_baseline + self.user_filters = user_filters or [] + self.non_null_columns = set(non_null_columns or []) + self.unique_columns = set(unique_columns or []) + self.null_filter_terms = null_filter_terms self.model = semantic_model.model self.entities_by_name: dict[str, SemanticEntity] = { entity.name: entity for entity in self.model.entities @@ -458,6 +488,19 @@ def __init__( self.table_columns: dict[str, set[str]] = { entity.table: self._entity_columns(entity) for entity in self.model.entities } + # These references have already passed physical authoring validation. + # Legacy models need not enumerate expected_columns to declare a measure. + for metric in self.model.metrics: + for expression in [metric.expression, *metric.default_filters, *([metric.time_field] if metric.time_field else [])]: + for column in sqlglot.parse_one(f"SELECT {expression}", read="sqlite").find_all(exp.Column): + if column.table in self.table_columns: + self.table_columns[column.table].add(column.name) + for relationship in self.model.relationships: + for reference in (relationship.from_ref, relationship.to_ref): + entity_name, _, column = reference.partition(".") + owner = self.entities_by_name.get(entity_name) + if owner: + self.table_columns[owner.table].add(column) # -------------------------------------------------------------- factories @classmethod @@ -467,14 +510,24 @@ def for_context(cls, context: Any) -> "SemanticSQLValidator | None": metric_matches = list(getattr(context, "metric_matches", None) or []) if semantic_model is None or not metric_matches: return None + from queryforge.domain.semantic.request_contract import null_filter_terms return cls( semantic_model, metric_matches, + null_filter_terms=null_filter_terms(getattr(context.task, "question", "")), metric_join_paths=list(getattr(context, "metric_join_paths", None) or []), requested_dimensions=list( getattr(context, "metric_requested_dimensions", None) or [] ), date_context=getattr(context, "date_context", None), + time_grain=getattr(context, "time_grain", None), + non_null_columns={(schema.table_name, column.name) + for schema in (getattr(context, "relevant_tables", None) or []) + for column in schema.columns if not column.nullable}, + unique_columns={(schema.table_name, column.name) + for schema in (getattr(context, "relevant_tables", None) or []) + for column in schema.columns if column.primary_key and not column.nullable + and sum(item.primary_key for item in schema.columns) == 1}, ) @staticmethod @@ -535,6 +588,8 @@ def validate(self, sql: str) -> SemanticValidationResult: evidence=evidence, ) root = statements[0] + if isinstance(root, exp.Select) and any(cte.alias.startswith("_qf_metric_") for cte in root.find_all(exp.CTE)): + return self._validate_separate_metrics(root, evidence) unsupported = self._unsupported_shape(root) if unsupported is not None: @@ -556,6 +611,7 @@ def validate(self, sql: str) -> SemanticValidationResult: violations: list[dict[str, str]] = [] self._check_unknown_schema(index, violations, evidence) measure_nodes = self._check_metric_expressions(index, violations, evidence) + self._check_requested_null_filters(index, violations) self._check_default_filters(index, violations, evidence, measure_nodes) self._check_time_filter(index, violations, evidence) self._check_join_keys(index, violations, evidence) @@ -568,6 +624,63 @@ def validate(self, sql: str) -> SemanticValidationResult: ) return SemanticValidationResult(status=PASSED, evidence=evidence) + def _validate_separate_metrics(self, root, evidence): + """Prove the aggregate join wrapper and validate every fact scope. + + Set operations remain unsupported elsewhere. Here UNION only creates the + key domain; exact AST comparison proves keys, NULL-safe joins, all output + measures and the absence of extra/unreferenced scopes. Branches cannot + smuggle a row bound or change the governed expression/grouping. + """ + try: + limit = int(root.args["limit"].expression.this) if root.args.get("limit") else 0 + expected = QuerySpecCompiler.compile( + semantic_model=self.semantic_model, metric_matches=self.metric_matches, + metric_join_paths=self.metric_join_paths, requested_dimensions=self.requested_dimensions, + date_context=self.date_context, limit=limit, + time_grain=self.time_grain, comparison_baseline=self.comparison_baseline, user_filters=self.user_filters, + ) + if expected is None or len(self.metric_matches) < 2: + raise ValueError("independent metric scopes cannot be compiled for the requested grain") + oracle = sqlglot.parse_one(expected.sql, read="sqlite") + observed_ctes = {cte.alias: cte for cte in root.find_all(exp.CTE)} + expected_ctes = {cte.alias: cte for cte in oracle.find_all(exp.CTE)} + names = expected.evidence["metric_ctes"] + if set(observed_ctes) != set(expected_ctes): + raise ValueError("unexpected or missing aggregate/key scope") + observed_wrapper, expected_wrapper = root.copy(), oracle.copy() + for wrapper in (observed_wrapper, expected_wrapper): + for cte in wrapper.find_all(exp.CTE): + if cte.alias in names: + cte.set("this", sqlglot.parse_one("SELECT 0")) + if observed_wrapper != expected_wrapper: + raise ValueError("aggregate wrapper does not preserve one row per requested key and every measure") + for name, match in zip(names, self.metric_matches): + branch, branch_oracle = observed_ctes[name].this, expected_ctes[name].this + if (branch.expressions != branch_oracle.expressions or branch.args.get("group") != branch_oracle.args.get("group") + or branch.args.get("from_") != branch_oracle.args.get("from_") + or branch.args.get("joins") != branch_oracle.args.get("joins") + or branch.args.get("where") != branch_oracle.args.get("where") + or branch.args.get("limit") or branch.args.get("distinct") or branch.args.get("having")): + raise ValueError(f"{name}: changed measure, grouping, or incomplete aggregate population") + require_filter_predicates(branch.sql(dialect="sqlite"), match.metric.default_filters) + require_filter_predicates(branch.sql(dialect="sqlite"), expected.user_filters) + validator = SemanticSQLValidator( + # The full FROM/JOIN/GROUP/projection AST was proven against + # the safe compiler above, including metric-specific time + # roles. Validate the remaining expression/filter/schema + # obligations at the branch's own metric and date scope. + self.semantic_model, [match], date_context=comparison_context( + self.date_context, self.comparison_baseline, self.time_grain, time_contract(match.metric)), + ) + result = validator.validate(branch.sql(dialect="sqlite")) + if result.status != PASSED: + return result + evidence.setdefault("metric_scopes", {})[match.metric.name] = result.evidence + return SemanticValidationResult(status=PASSED, evidence=evidence) + except Exception as exc: + return SemanticValidationResult(status=UNSUPPORTED, unsupported_reason=f"unverified aggregate join: {exc}", evidence=evidence) + # ------------------------------------------------------------ unsupported def _unsupported_shape(self, root: exp.Expression) -> str | None: for _ in root.find_all(exp.Lateral): @@ -660,7 +773,7 @@ def _metric_requirements( for aggregate in expression.find_all(exp.AggFunc): argument = aggregate.this if isinstance(argument, exp.Distinct): - argument = argument.this + argument = argument.expressions[0] if len(argument.expressions) == 1 else None if isinstance(argument, exp.Star): requirements.append( _MetricAggregateRequirement( @@ -705,7 +818,7 @@ def _aggregate_satisfies( if requirement.star: return observed.star or bool(observed.columns) if requirement.column is None: - return True + return False return requirement.column in observed.columns if observed.function != requirement.function: return False @@ -734,7 +847,7 @@ def _check_metric_expressions( ) -> list[exp.Expression]: observed = index.aggregates() measure_nodes: list[exp.Expression] = [] - sql_has_division = next(index.root.find_all(exp.Div), None) is not None + sql_has_division = any(id(node) in index.output_nodes for node in index.root.find_all(exp.Div)) for match in self.metric_matches: metric = match.metric @@ -745,11 +858,22 @@ def _check_metric_expressions( requirements, columns, has_division = self._metric_requirements( metric, base_table ) + star_proofs = { + requirement.column: node + for requirement in requirements + if requirement.function == "COUNT" and requirement.distinct + and requirement.column in self.unique_columns + for node, aggregate in observed + if aggregate.function == "COUNT" and aggregate.star and not aggregate.distinct + and self._single_physical_source(index, node) == {base_table} + } missing_columns = sorted( f"{table}.{column}" for table, column in columns + if (table, column) not in star_proofs if not any( - (table, column) in resolved for _, _, resolved in index.column_facts + (table, column) in resolved and id(node) in index.output_nodes + for _, node, resolved in index.column_facts ) ) if missing_columns: @@ -778,6 +902,13 @@ def _check_metric_expressions( if requirement.function == "SUM" and requirement.column is not None for _node, aggregate in observed ) + if metric.ratio: + proof = self._declared_ratio_proof(index, metric) + avg_equivalence = proof == "average" + if proof is None: + self._add_violation(violations, RULE_METRIC_EXPRESSION, + f"metric {metric.name!r} declared ratio numerator, denominator, scale and numeric division cannot be verified") + evidence.setdefault("ratio_components", {})[metric.name] = proof or "unverified" matched_any = True for requirement in requirements: matched = [ @@ -785,6 +916,9 @@ def _check_metric_expressions( for node, aggregate in observed if self._aggregate_satisfies(requirement, aggregate) ] + if not matched and requirement.column in star_proofs: + node = star_proofs[requirement.column] + matched = [(node, next(aggregate for item, aggregate in observed if item is node))] if not matched and avg_equivalence: # SUM(column)/COUNT(*) ratio metrics accept the equivalent AVG(column). continue @@ -818,6 +952,103 @@ def _check_metric_expressions( ) return measure_nodes + def _check_requested_null_filters(self, index, violations): + def conjuncts(node): + if isinstance(node, exp.Paren): + return conjuncts(node.this) + if isinstance(node, exp.And): + return conjuncts(node.this) + conjuncts(node.expression) + return [node] + + for term in self.null_filter_terms: + for match in self.metric_matches: + entity = self.entities_by_name[match.metric.entity] + names = [name for name in self.table_columns[entity.table] + if name.casefold() == term.casefold() or name.casefold().endswith("_" + term.casefold())] + lineage = index.scope_lineage(self._metric_scope(index, match.metric, entity.table)) + proved = len(names) == 1 and any( + isinstance(predicate, exp.Is) and isinstance(predicate.expression, exp.Null) + and isinstance(predicate.this, exp.Column) + and index.resolve_column(scope, predicate.this) == {(entity.table, names[0])} + for scope, kind, expression in index.predicates if kind == "where" and id(scope) in lineage + for predicate in conjuncts(expression)) + if not proved: + self._add_violation(violations, RULE_METRIC_EXPRESSION, + f"requested NULL {term} filter cannot be verified for metric {match.metric.name!r}") + + @staticmethod + def _single_physical_source(index, node): + scope = index.scope_of(node) + if scope is None: + return set() + sources = [source for _, source in scope.selected_sources.values()] + # A derived source could duplicate rows or remove uniqueness. + if len(sources) != 1 or any(not isinstance(source, exp.Table) for source in sources): + return set() + return {source.name for source in sources} + + @classmethod + def _ratio_signature(cls, value, index=None, scope=None): + """Exact math, permitting aliases, parentheses and neutral multiplication. + + Decimal compares numeric literals without rounding large integer factors. + Derived aggregate columns cannot be mistaken for raw measure columns. + """ + if isinstance(value, (exp.Alias, exp.Paren)): + return cls._ratio_signature(value.this, index, scope) + if isinstance(value, exp.Column): + if scope is not None: + sources = [scope.sources.get(value.table)] if value.table else list(scope.sources.values()) + if any(isinstance(source, Scope) for source in sources): + return ("unverified_derived_column", value.sql()) + resolved = index.resolve_column(scope, value) + if len(resolved) == 1: + return ("column", *next(iter(resolved))) + return ("unresolved_column", value.sql()) + return ("column", value.table, value.name) + if isinstance(value, exp.Literal): + return ("literal", value.is_string, value.this if value.is_string else Decimal(value.this)) + if isinstance(value, exp.Mul): + for literal, other in ((value.this, value.expression), (value.expression, value.this)): + if isinstance(literal, exp.Literal) and not literal.is_string and Decimal(literal.this) == 1: + return cls._ratio_signature(other, index, scope) + if isinstance(value, exp.Expression): + return (value.key, tuple((key, cls._ratio_signature(item, index, scope)) for key, item in sorted(value.args.items()) if item is not None)) + if isinstance(value, list): + return tuple(cls._ratio_signature(item, index, scope) for item in value) + return value + + def _declared_ratio_proof(self, index, metric): + expected = {"direct": self._ratio_signature(_parse_expression(metric.expression))} + numerator = _parse_expression(metric.ratio.numerator) + denominator = _parse_expression(metric.ratio.denominator) + if isinstance(numerator, exp.Sum) and isinstance(numerator.this, exp.Column) and isinstance(denominator, exp.Count): + column = numerator.this + same_population = (isinstance(denominator.this, exp.Column) and denominator.this == column) or ( + isinstance(denominator.this, exp.Star) and (column.table, column.name) in self.non_null_columns) + if same_population: + expected["average"] = self._ratio_signature(_parse_expression( + f"AVG({column.sql(dialect='sqlite')}) * {metric.ratio.scale}")) + for projection in index.root.walk(): + if id(projection) not in index.output_nodes: + continue + scope = index.scope_of(projection) + while isinstance(projection, (exp.Alias, exp.Paren)): + projection = projection.this + # Reporting precision may round the final value, never its inputs. + if isinstance(projection, exp.Round): + decimals = projection.args.get("decimals") + if decimals is None or ( + isinstance(decimals, exp.Literal) and decimals.is_int + and 0 <= int(decimals.this) <= 15 + ): + projection = projection.this + signature = self._ratio_signature(projection, index, scope) + for proof, reference in expected.items(): + if signature == reference: + return proof + return None + def _default_filter_expectations( self, raw_filter: str, base_table: str ) -> tuple[list[tuple[str, str]] | None, tuple[str, Any] | None] | None: @@ -970,6 +1201,8 @@ def _metric_scope( for node, aggregate in index.aggregates(): if wanted and (wanted & set(aggregate.columns)): return index.scope_of(node) + if aggregate.function == "COUNT" and aggregate.star and self._single_physical_source(index, node) == {base_table}: + return index.scope_of(node) return index.scopes[-1] if index.scopes else None def _filter_comparisons( @@ -1335,11 +1568,14 @@ def _check_fanout( violations: list[dict[str, str]], evidence: dict[str, Any], ) -> None: - used_tables = set(index.referenced_tables) for match in self.metric_matches: base_entity = self.entities_by_name.get(match.metric.entity) if base_entity is None: continue + metric_scope = self._metric_scope(index, match.metric, base_entity.table) + lineage = index.scope_lineage(metric_scope) + used_tables = {source.name for scope in index.scopes if id(scope) in lineage + for _, source in scope.selected_sources.values() if isinstance(source, exp.Table)} governed_tables = {base_entity.table} | { table for path in self.metric_join_paths @@ -1372,9 +1608,15 @@ def _check_grain( violations: list[dict[str, str]], evidence: dict[str, Any], ) -> None: + active_lineage = set().union(*( + index.scope_lineage(self._metric_scope(index, match.metric, + self.entities_by_name[match.metric.entity].table)) + for match in self.metric_matches + )) if self.metric_matches else set() grouped = { resolved for scope, column in index.group_by_columns + if id(scope) in active_lineage for resolved in index.resolve_column(scope, column) } evidence["group_by"] = sorted(f"{table}.{column}" for table, column in grouped) @@ -1407,11 +1649,14 @@ def _check_grain( class QuerySpec(BaseModel): - """Deterministic compiled query for one matched governed metric.""" + """Deterministic compiled query over a compatible governed population.""" model_config = ConfigDict(extra="forbid") metric_name: str + metric_names: list[str] = Field(default_factory=list) + user_filters: list[str] = Field(default_factory=list) + time_grain: str | None = None aggregation: Literal["count", "sum", "ratio"] base_table: str measure_expression: str @@ -1475,6 +1720,9 @@ def compile( requested_dimensions: list[str] | None = None, date_context: Any | None = None, limit: int = 100, + user_filters: list[str] | None = None, + time_grain: str | None = None, + comparison_baseline: str | None = None, ) -> QuerySpec | None: if not metric_matches: return None @@ -1482,6 +1730,12 @@ def compile( entities_by_name = {entity.name: entity for entity in model.entities} first = metric_matches[0] metric = first.metric + metrics = [match.metric for match in metric_matches] + if len(metrics) > 1: + return cls._compile_separate_metrics( + semantic_model, metric_matches, metric_join_paths or [], requested_dimensions or [], + date_context, limit, user_filters or [], time_grain, comparison_baseline, + ) entity = entities_by_name.get(metric.entity) if entity is None: return None @@ -1490,10 +1744,30 @@ def compile( joins: list[str] = [] seen_join_tables: set[str] = set() group_by: list[str] = [] + group_projections: list[str] = [] #: Chronological ordering for period-name dimensions (month_name, ...), so a #: time series is never ordered alphabetically. order_by: list[str] = [] - for reference in requested_dimensions or []: + bucketed_time = False + time_dimension = None + bound_filters = bind_filters(model, metrics, user_filters or []) + filter_dimensions = [] + for predicate in bound_filters: + for column in literal_predicate(predicate).find_all(exp.Column): + if column.table != base_table: + owner = next((e for e in model.entities if e.table == column.table), None) + if owner: + dimension = next((d for d in owner.dimensions if d.column == column.name), None) + if dimension: + filter_dimensions.append(f"{owner.name}.{dimension.name}") + join_keys = [] + contract = time_contract(metric) + for reference in dict.fromkeys([*(requested_dimensions or []), *filter_dimensions]): + if (time_grain and metric.analysis and metric.analysis.additivity == "semi_additive" + and reference in metric.analysis.non_additive_dimensions): + return None + if metric.allowed_dimensions and reference not in metric.allowed_dimensions: + return None entity_name, separator, dimension_name = reference.partition(".") dimension_entity = entities_by_name.get(entity_name) if not separator or dimension_entity is None: @@ -1508,21 +1782,37 @@ def compile( ) if dimension is None: return None - group_by.append(f"{dimension_entity.table}.{dimension.column}") + dimension_path = cls._resolve_path(semantic_model, metric.entity, entity_name, metric_join_paths or []) + direct = cls._direct_time_join( + semantic_model, base_table=base_table, metric_time_field=metric.time_field, + dimension_entity=dimension_entity, join_paths=[dimension_path] if dimension_path else [], + ) if dimension_entity.table != base_table else None + grouping = f"{dimension_entity.table}.{dimension.column}" + is_time = grouping == metric.time_field or ( + direct is not None and dimension.name in {"date", "month", "quarter", "year"} + ) + if time_grain and is_time: + grouping = bucket_sql(metric.time_field, time_grain, contract) + if grouping is None: + return None + bucketed_time = True + if reference in (requested_dimensions or []): + time_dimension = reference + if reference in (requested_dimensions or []): + group_by.append(grouping) + group_projections.append(f"{grouping} AS {cls._alias(reference)}" + if time_grain and is_time else grouping) ordering = cls._natural_order_column(dimension_entity, dimension) - if ordering is not None: - order_by.append(f"{dimension_entity.table}.{ordering}") + if reference in (requested_dimensions or []): + order_by.append(f"{dimension_entity.table}.{ordering}" if ordering and not (time_grain and is_time) + else grouping) if dimension_entity.table == base_table: continue - direct = cls._direct_time_join( - semantic_model, - base_table=base_table, - metric_time_field=metric.time_field, - dimension_entity=dimension_entity, - join_paths=metric_join_paths or [], - ) if direct is not None: - joins.append(direct) + if dimension_entity.table not in seen_join_tables: + joins.append(direct) + seen_join_tables.add(dimension_entity.table) + join_keys.append((dimension_entity.table, direct.rsplit(".", 1)[-1])) if dimension_entity.table not in used_tables: used_tables.append(dimension_entity.table) continue @@ -1539,6 +1829,7 @@ def compile( if step.to_table in {base_table, *seen_join_tables}: continue seen_join_tables.add(step.to_table) + join_keys.append((step.to_table, step.to_column)) joins.append( f"JOIN {step.to_table} ON {step.from_table}.{step.from_column} = " f"{step.to_table}.{step.to_column}" @@ -1546,16 +1837,22 @@ def compile( if step.to_table not in used_tables: used_tables.append(step.to_table) + if time_grain and not bucketed_time: + return None time_field = metric.time_field - time_filter = cls._time_filter(time_field, date_context) - where_clauses = [*metric.default_filters] + expanded_dates = comparison_context(date_context, comparison_baseline, time_grain, contract) + time_filter = cls._time_filter(time_field, expanded_dates, contract) + where_clauses = [*metric.default_filters, *bound_filters] if time_filter: where_clauses.append(time_filter) - alias = cls._alias(metric.name) statement = f"SELECT " if group_by: - statement += ", ".join(group_by) + ", " - statement += f"{metric.expression} AS {alias} FROM {base_table}" + statement += ", ".join(group_projections) + ", " + statement += ", ".join(f"{m.expression} AS {cls._alias(m.name)}" for m in metrics) + if metric.ratio: + statement += (f", {metric.ratio.numerator} AS {cls._alias(metric.name + '__numerator')}" + f", {metric.ratio.denominator} AS {cls._alias(metric.name + '__denominator')}") + statement += f" FROM {base_table}" if joins: statement += " " + " ".join(joins) if where_clauses: @@ -1570,6 +1867,9 @@ def compile( statement += f" LIMIT {int(limit)}" return QuerySpec( metric_name=metric.name, + metric_names=[m.name for m in metrics], + user_filters=bound_filters, + time_grain=time_grain, aggregation=metric.aggregation, base_table=base_table, measure_expression=metric.expression, @@ -1588,6 +1888,10 @@ def compile( tables_used=used_tables, evidence={ "metric": metric.name, + "metrics": [m.name for m in metrics], + "user_filters": bound_filters, + "time_grain": time_grain, + "time_dimension": time_dimension, "aggregation": metric.aggregation, "default_filters": list(metric.default_filters), "time_field": time_field, @@ -1596,9 +1900,94 @@ def compile( "order_by": order_by or list(group_by), "joins": joins, "limit": int(limit), + "join_keys": join_keys, + "source_grains": [(base_table, entity.effective_grain)] if entity.effective_grain else [], + "time_validations": ([f"SELECT COUNT(*) AS invalid_dates FROM {base_table} WHERE {invalid_time_sql(metric.time_field, contract)} LIMIT 1"] if contract else []), + "metric_contracts": {metric.name: cls._analysis_metadata(metric, entity)}, + "ratio_components": ({metric.name: metric.ratio.model_dump()} if metric.ratio else {}), + "requested_ranges": [(r.start_date, r.end_date) for r in (date_context.ranges if date_context else [])], + "query_ranges": [(r.start_date, r.end_date) for r in (expanded_dates.ranges if expanded_dates else [])], }, ) + @staticmethod + def _analysis_metadata(metric, entity=None): + inferred = "non_additive" if metric.aggregation == "ratio" or re.search(r"\bDISTINCT\b", metric.expression, re.I) else "additive" + proof = None + if not metric.analysis and entity and entity.primary_key == entity.effective_grain and len(entity.primary_key) == 1: + measure = sqlglot.parse_one(metric.expression, read="sqlite") + if isinstance(measure, exp.Count) and isinstance(measure.this, exp.Distinct) and len(measure.this.expressions) == 1: + column = measure.this.expressions[0] + if isinstance(column, exp.Column) and (column.table, column.name) == (entity.table, entity.primary_key[0]): + inferred, proof = "additive", "unique_row_identity" + return {"unit": metric.analysis.unit if metric.analysis else None, + "additivity": metric.analysis.additivity if metric.analysis else inferred, + "additivity_proof": proof, + "non_additive_dimensions": metric.analysis.non_additive_dimensions if metric.analysis else [], + "time": time_contract(metric).model_dump() if time_contract(metric) else None, + "population_filters": list(metric.default_filters)} + + @classmethod + def _compile_separate_metrics(cls, context, matches, paths, dimensions, dates, limit, filters, grain, baseline): + """Union the aggregate key domain, then join one row per grain/key. + + Facts never join to facts. NULL groups and groups present in only one + population survive; missing measures stay NULL rather than invented zero. + """ + bound = bind_filters(context.model, [match.metric for match in matches], filters) + specs = [cls.compile(semantic_model=context, metric_matches=[match], metric_join_paths=paths, + requested_dimensions=dimensions, date_context=dates, limit=0, + user_filters=bound, time_grain=grain, comparison_baseline=baseline) + for match in matches] + if any(spec is None for spec in specs): + return None + keys = [f"_qf_g{i}" for i in range(len(dimensions))] or ["_qf_scalar"] + names = [f"_qf_metric_{i}" for i in range(len(specs))] + ctes, key_queries, selects, joins = [], [], [], [] + for name, spec in zip(names, specs): + tree = sqlglot.parse_one(spec.sql, read="sqlite") + projections = list(tree.expressions) + if dimensions: + projections[:len(dimensions)] = [exp.alias_(projection, key) for projection, key in zip(projections, keys)] + else: + projections.insert(0, exp.alias_(exp.Literal.number(1), keys[0])) + tree.set("expressions", projections) + tree.set("order", None) + ctes.append(f"{name} AS ({tree.sql(dialect='sqlite')})") + key_queries.append(f"SELECT {', '.join(keys)} FROM {name}") + selects.append(f"{name}.{cls._alias(spec.metric_name)} AS {cls._alias(spec.metric_name)}") + metric = next(match.metric for match in matches if match.metric.name == spec.metric_name) + if metric.ratio: + selects.extend(f"{name}.{cls._alias(metric.name + suffix)} AS {cls._alias(metric.name + suffix)}" + for suffix in ("__numerator", "__denominator")) + joins.append(f"LEFT JOIN {name} ON " + " AND ".join(f"_qf_keys.{key} IS {name}.{key}" for key in keys)) + ctes.append("_qf_keys AS (" + " UNION ".join(key_queries) + ")") + group_selects = [f"_qf_keys.{key} AS {cls._alias(reference)}" for key, reference in zip(keys, dimensions)] + sql = ("WITH " + ", ".join(ctes) + " SELECT " + ", ".join(group_selects + selects) + + " FROM _qf_keys " + " ".join(joins)) + if dimensions: + sql += " ORDER BY " + ", ".join(f"_qf_keys.{key}" for key in keys) + if limit > 0: + sql += f" LIMIT {int(limit)}" + return specs[0].model_copy(update={ + "metric_names": [match.metric.name for match in matches], "user_filters": bound, + "limit": limit, "sql": sql, + "tables_used": list(dict.fromkeys(table for spec in specs for table in spec.tables_used)), + "explanation": "Independently aggregate each governed population, then join at the requested grain.", + "evidence": {"metric_ctes": names, "join_keys": list(dict.fromkeys(tuple(key) for spec in specs for key in spec.evidence["join_keys"])), + "time_validations": list(dict.fromkeys(sql for spec in specs for sql in spec.evidence["time_validations"])), + "source_grains": [(spec.base_table, spec.evidence["source_grains"][0][1]) for spec in specs if spec.evidence["source_grains"]], + "metric_contracts": {name: metadata for spec in specs for name, metadata in spec.evidence["metric_contracts"].items()}, + "ratio_components": {match.metric.name: match.metric.ratio.model_dump() for match in matches if match.metric.ratio}, + "requested_ranges": specs[0].evidence["requested_ranges"], "query_ranges": specs[0].evidence["query_ranges"], + "time_dimension": specs[0].evidence.get("time_dimension"), + "metric_queries": {spec.metric_name: spec.sql for spec in specs}}, + }) + + @staticmethod + def _time_bucket(reference: str, grain: str) -> str | None: + return bucket_sql(reference, grain) + @staticmethod def _natural_order_column(dimension_entity: Any, dimension: Any) -> str | None: """The column that orders a period-name dimension chronologically. @@ -1745,7 +2134,7 @@ def _resolve_path( return path @staticmethod - def _time_filter(time_field: str | None, date_context: Any | None) -> str | None: + def _time_filter(time_field: str | None, date_context: Any | None, contract=None) -> str | None: if not time_field: return None ranges = [ @@ -1753,11 +2142,13 @@ def _time_filter(time_field: str | None, date_context: Any | None) -> str | None for item in (getattr(date_context, "ranges", None) or []) ] clauses: list[str] = [] + date_key = time_field.casefold().endswith("_key") + field = time_field if date_key else calendar_sql(time_field, contract) for start, end in ranges: if not isinstance(start, str) or not isinstance(end, str): continue clauses.append( - f"{time_field} BETWEEN {QuerySpecCompiler._time_literal(time_field, start)}" + f"{field} BETWEEN {QuerySpecCompiler._time_literal(time_field, start)}" f" AND {QuerySpecCompiler._time_literal(time_field, end)}" ) if not clauses: diff --git a/queryforge/domain/skills/manager.py b/queryforge/domain/skills/manager.py index 98c6716..463a732 100644 --- a/queryforge/domain/skills/manager.py +++ b/queryforge/domain/skills/manager.py @@ -4,6 +4,9 @@ from dataclasses import dataclass from html import escape +from collections import OrderedDict +from hashlib import sha256 +from threading import RLock from queryforge.domain.skills.registry import ( SkillDefinition, @@ -32,14 +35,20 @@ class SkillManager: def __init__(self, registry: SkillRegistry | None = None) -> None: self.registry = registry or SkillRegistry() + self._context_cache: OrderedDict[tuple, SkillContext] = OrderedDict() + self._cache_lock = RLock() def context_for_node( self, node_name: str, selected_names: list[str] | tuple[str, ...] | None = None, + *, + available_names: list[str] | None = None, ) -> SkillContext: all_skills = self.registry.list_skills() available = [skill for skill in all_skills if skill.applies_to(node_name)] + if available_names is not None: + available = [skill for skill in available if skill.name in available_names] if selected_names is None: loaded = [skill for skill in available if skill.metadata.enabled] else: @@ -54,12 +63,26 @@ def context_for_node( requested_set = set(requested) loaded = [skill for skill in available if skill.name in requested_set] - return SkillContext( + contents = [self._read_content(skill) for skill in loaded] + key = (str(self.registry.skills_dir), node_name, + tuple(skill.metadata for skill in available), + tuple((skill.name, sha256(content.encode()).hexdigest()) for skill, content in zip(loaded, contents))) + with self._cache_lock: + cached = self._context_cache.get(key) + if cached is not None: + self._context_cache.move_to_end(key) + return cached + result = SkillContext( node_name=node_name, available_skills=self._render_available(node_name, available), - loaded_skills=self._render_loaded(node_name, loaded), + loaded_skills=self._render_loaded(node_name, loaded, contents), loaded_skill_names=tuple(skill.name for skill in loaded), ) + with self._cache_lock: + self._context_cache[key] = result + if len(self._context_cache) > 32: + self._context_cache.popitem(last=False) + return result @staticmethod def _render_available(node_name: str, skills: list[SkillDefinition]) -> str: @@ -76,19 +99,19 @@ def _render_available(node_name: str, skills: list[SkillDefinition]) -> str: return "\n".join(lines) @staticmethod - def _render_loaded(node_name: str, skills: list[SkillDefinition]) -> str: + def _read_content(skill: SkillDefinition) -> str: + try: + content = skill.instruction_path.read_text(encoding="utf-8").strip() + except (OSError, UnicodeError) as exc: + raise SkillRegistryError(f"Could not read skill instructions {skill.instruction_path}: {exc}") from exc + if len(content) > MAX_SKILL_CONTENT_CHARS: + raise SkillRegistryError(f"Skill {skill.name!r} exceeds {MAX_SKILL_CONTENT_CHARS} characters") + return content + + @staticmethod + def _render_loaded(node_name: str, skills: list[SkillDefinition], contents: list[str]) -> str: lines = [f''] - for skill in skills: - try: - content = skill.instruction_path.read_text(encoding="utf-8").strip() - except (OSError, UnicodeError) as exc: - raise SkillRegistryError( - f"Could not read skill instructions {skill.instruction_path}: {exc}" - ) from exc - if len(content) > MAX_SKILL_CONTENT_CHARS: - raise SkillRegistryError( - f"Skill {skill.name!r} exceeds {MAX_SKILL_CONTENT_CHARS} characters" - ) + for skill, content in zip(skills, contents): lines.extend( [ f' ', diff --git a/queryforge/domain/skills/registry.py b/queryforge/domain/skills/registry.py index 9d77400..9ab69ee 100644 --- a/queryforge/domain/skills/registry.py +++ b/queryforge/domain/skills/registry.py @@ -4,6 +4,7 @@ import re from dataclasses import dataclass +from hashlib import sha256 from pathlib import Path from typing import Any @@ -30,6 +31,7 @@ class SkillMetadata: allowed_nodes: tuple[str, ...] enabled: bool priority: int + selection_keywords: tuple[str, ...] | None = None @dataclass(frozen=True, slots=True) @@ -51,6 +53,7 @@ class SkillRegistry: def __init__(self, skills_dir: str | Path = DEFAULT_SKILLS_DIR) -> None: self.skills_dir = Path(skills_dir).expanduser().resolve() + self._metadata_cache: dict[tuple[Path, str], SkillMetadata] = {} def list_skills(self) -> list[SkillDefinition]: if not self.skills_dir.exists(): @@ -73,7 +76,18 @@ def list_skills(self) -> list[SkillDefinition]: raise SkillRegistryError( f"Skill {directory.name!r} is missing SKILL.md: {instruction_path}" ) - metadata = self._read_metadata(metadata_path) + try: + raw = metadata_path.read_bytes() + fingerprint = sha256(raw).hexdigest() + except OSError as exc: + raise SkillRegistryError(f"Could not read skill metadata {metadata_path}: {exc}") from exc + key = (metadata_path, fingerprint) + metadata = self._metadata_cache.get(key) + if metadata is None: + metadata = self._read_metadata(metadata_path, raw) + if len(self._metadata_cache) >= 128: + self._metadata_cache.clear() + self._metadata_cache[key] = metadata if metadata.name != directory.name: raise SkillRegistryError( f"Skill name {metadata.name!r} must match directory {directory.name!r}" @@ -103,9 +117,9 @@ def get(self, name: str) -> SkillDefinition: ) @staticmethod - def _read_metadata(path: Path) -> SkillMetadata: + def _read_metadata(path: Path, raw: bytes | None = None) -> SkillMetadata: try: - payload = yaml.safe_load(path.read_text(encoding="utf-8")) + payload = yaml.safe_load(raw.decode("utf-8") if raw is not None else path.read_text(encoding="utf-8")) except (OSError, UnicodeError, yaml.YAMLError) as exc: raise SkillRegistryError(f"Could not read skill metadata {path}: {exc}") from exc if not isinstance(payload, dict): @@ -131,12 +145,18 @@ def _read_metadata(path: Path) -> SkillMetadata: priority = payload.get("priority") if isinstance(priority, bool) or not isinstance(priority, int): raise SkillRegistryError(f"priority must be an integer: {path}") + keywords = payload.get("selection_keywords") + if keywords is not None and (not isinstance(keywords, list) or not all( + isinstance(item, str) and item.strip() for item in keywords + )): + raise SkillRegistryError(f"selection_keywords must be a string list: {path}") return SkillMetadata( name=name, description=description, allowed_nodes=allowed_nodes, enabled=enabled, priority=priority, + selection_keywords=tuple(item.casefold().strip() for item in keywords) if keywords is not None else None, ) diff --git a/queryforge/evaluation/__init__.py b/queryforge/evaluation/__init__.py index 94ec519..a41a0aa 100644 --- a/queryforge/evaluation/__init__.py +++ b/queryforge/evaluation/__init__.py @@ -2,9 +2,10 @@ The package scores recorded agent traces against gold tasks and aggregates them into a recomputable report. It is deliberately isolated from the pipeline it -grades: it imports nothing but the standard library and pydantic, never +grades: it uses the standard library, pydantic and independent SQLGlot source +analysis, never ``queryforge.workflow``/``application``/``orchestration``/``interfaces``, so a -bug in the runtime cannot make the benchmark lenient (see +runtime verdict cannot make the benchmark lenient (see ``tests/test_agent_task_gold.py::test_evaluator_does_not_import_runtime_being_graded``). Typical use:: diff --git a/queryforge/evaluation/evaluator.py b/queryforge/evaluation/evaluator.py index caf0288..b3890ac 100644 --- a/queryforge/evaluation/evaluator.py +++ b/queryforge/evaluation/evaluator.py @@ -4,9 +4,9 @@ **Goal oriented, never path oriented.** A task is scored on the observable outcome -- the status the pipeline reported, the evidence it produced, the -values it published, the claims it made -- and *never* on SQL text or on the -order in which steps ran. Two runs that reach the same goal by different routes -both pass (16-T2). +values it published, the claims it made and opt-in physical source requirements +-- never on exact SQL text or the order in which steps ran. Two runs that reach +the same declared goal by different routes both pass (16-T2). **Nothing self-assessed is trusted.** ``validation_problems``, ``answer_validation.review_required``, a payload's own ``passed`` flag and any @@ -19,8 +19,8 @@ -- the step's exit gate ("从原始 case 与 trace 可重算报告") is executable, not aspirational. -This module imports nothing but the standard library and pydantic: the evaluator -must not be able to share a bug with the code it grades (see +This evaluator uses the standard library, pydantic and SQLGlot for independent +source analysis. It never delegates verdicts to the runtime it grades (see ``tests/test_agent_task_gold.py::test_evaluator_does_not_import_runtime_being_graded``). """ @@ -33,6 +33,7 @@ from pydantic import BaseModel, ConfigDict, Field from queryforge.evaluation.tasks import TaskSpec, spec_index +from queryforge.evaluation.sources import check_sql_sources from queryforge.evaluation.thresholds import check_metrics from queryforge.evaluation.trace import ( TaskTrace, @@ -70,7 +71,7 @@ ) #: Fixed check names (contract 3.3), in reporting order. ``claim_guard`` and -#: ``budget`` are only emitted when the gold declares the corresponding +#: ``budget`` and ``sql_sources`` are only emitted when the gold declares the corresponding #: constraint, so a rate computed over a check never divides by tasks the check #: did not apply to. CHECK_NAMES: tuple[str, ...] = ( @@ -80,6 +81,7 @@ "required_evidence", "forbidden_evidence", "expected_values", + "sql_sources", "evidence_anchor", "tool_legality", "tool_validity", @@ -167,6 +169,7 @@ "budget", "outcome_kind", "status_accepted", + "sql_sources", "expected_values", "forbidden_evidence", "evidence_anchor", @@ -184,6 +187,7 @@ "required_evidence": "missing_evidence", "forbidden_evidence": "policy_not_enforced", "expected_values": "wrong_value", + "sql_sources": "unsupported_claim", "evidence_anchor": "unsupported_claim", "tool_legality": "illegal_tool", "tool_validity": "failed_tool", @@ -713,12 +717,12 @@ def _format_value(value: Any) -> str: return str(value) -def _values_match(actual: Any, expected: Any, tolerance: float) -> bool: +def _values_match(actual: Any, expected: Any, tolerance: float, *, ordered: bool = False, absolute_tolerance: float = 0.0) -> bool: """Compare one gold value with the observed one. - Numbers use the task's *relative* tolerance (with an exact match required for - a gold zero, where a relative tolerance is undefined), strings and booleans - compare exactly, and lists compare as multisets (order is not an outcome). + Numbers use the task's relative tolerance. Zero is exact unless an absolute + tolerance is explicitly declared. Strings and booleans compare exactly; + outer lists are multisets, while cells inside rows retain their positions. """ if isinstance(expected, bool) or isinstance(actual, bool): @@ -728,7 +732,7 @@ def _values_match(actual: Any, expected: Any, tolerance: float) -> bool: return False try: return math.isclose( - float(actual), float(expected), rel_tol=tolerance, abs_tol=0.0 + float(actual), float(expected), rel_tol=tolerance, abs_tol=absolute_tolerance ) except (OverflowError, ValueError): return False @@ -737,13 +741,15 @@ def _values_match(actual: Any, expected: Any, tolerance: float) -> bool: return False if len(actual) != len(expected): return False + if ordered: + return all(_values_match(a, e, tolerance, ordered=True, absolute_tolerance=absolute_tolerance) for a, e in zip(actual, expected)) remaining = [item for item in actual] for wanted in expected: index = next( ( position for position, candidate in enumerate(remaining) - if _values_match(candidate, wanted, tolerance) + if _values_match(candidate, wanted, tolerance, ordered=isinstance(wanted, list), absolute_tolerance=absolute_tolerance) ), None, ) @@ -755,7 +761,7 @@ def _values_match(actual: Any, expected: Any, tolerance: float) -> bool: if not isinstance(actual, Mapping): return False return all( - key in actual and _values_match(actual[key], value, tolerance) + key in actual and _values_match(actual[key], value, tolerance, absolute_tolerance=absolute_tolerance) for key, value in expected.items() ) return actual == expected @@ -1008,7 +1014,7 @@ def _check_forbidden_evidence(spec: TaskSpec, kinds: set[str]) -> CheckResult: def _check_expected_values(spec: TaskSpec, payload: Mapping[str, Any]) -> CheckResult: """``expected_values``: gold values by dotted path, with tolerance (3.3 #5).""" - if not spec.expected_values: + if not spec.expected_values and spec.result_contract is None: return _result( "expected_values", True, "the gold fixes no value", expected={}, actual={} ) @@ -1027,12 +1033,29 @@ def _check_expected_values(spec: TaskSpec, payload: Mapping[str, Any]) -> CheckR problems.append(f"{key}: path not present in the payload") continue observed[key] = actual + if spec.result_contract is not None and key in { + spec.result_contract.columns_path, spec.result_contract.rows_path + }: + # The contract aligns named columns before comparing ordered cells. + continue tolerance = spec.tolerance_for(key) - if not _values_match(actual, expected, tolerance): + absolute = spec.values_absolute_tolerance.get(key, spec.values_absolute_tolerance.get("*", 0.0)) + if not _values_match(actual, expected, tolerance, absolute_tolerance=absolute): problems.append( f"{key}: observed {_format_value(actual)}, expected " - f"{_format_value(expected)} (relative tolerance {tolerance:g})" + f"{_format_value(expected)} (relative tolerance {tolerance:g}, absolute tolerance {absolute:g})" ) + if spec.result_contract is not None: + from queryforge.evaluation.results import compare_results, cells_match + contract = spec.result_contract + found_columns, columns = payload_path(payload, contract.columns_path) + found_rows, rows = payload_path(payload, contract.rows_path) + expected_rows = spec.expected_values.get(contract.rows_path) + expected_columns = spec.expected_values.get(contract.columns_path) or contract.required_columns + if (not found_columns or not found_rows or expected_rows is None or not expected_columns + or not compare_results(rows, columns, expected_rows, expected_columns, contract=contract, + cell_match=lambda a, e: cells_match(a, e, spec.tolerance_for(contract.rows_path)))): + problems.append("result_contract: required columns, row positions/order or empty-result policy mismatched") detail = ( f"all {len(spec.expected_values)} gold value(s) matched" if not problems @@ -1052,6 +1075,28 @@ def _check_expected_values(spec: TaskSpec, payload: Mapping[str, Any]) -> CheckR ) +def _check_sql_sources(spec: TaskSpec, payload: Mapping[str, Any]) -> CheckResult | None: + """Opt-in independent source coverage; matching values alone are insufficient.""" + + if not spec.required_sql_tables: + return None + coverage = check_sql_sources(payload.get("sql"), spec.required_sql_tables) + detail = ( + "all required physical sources are active in the final SQL" + if coverage.passed else + f"SQL source coverage is unverified: {coverage.reason}" + if not coverage.verified else + f"required physical source(s) missing: {_preview(coverage.missing_tables)}" + ) + return _result( + "sql_sources", coverage.passed, detail, + expected=list(spec.required_sql_tables), + actual={"verified": coverage.verified, "active_tables": list(coverage.active_tables), + "missing_tables": list(coverage.missing_tables)}, + reason=coverage.reason, + ) + + def _check_evidence_anchor( spec: TaskSpec, view: AnswerView, known_ids: set[str] ) -> CheckResult: @@ -1744,6 +1789,7 @@ def evaluate_task( denied, denial_signals = policy_denial(payload, trace.tool_calls) usage = usage_accounting(trace) cost, cost_basis = cost_accounting(trace, usage, price_table) + source_check = _check_sql_sources(spec, payload) checks: list[CheckResult] = [ _check_trace_available(trace), @@ -1752,6 +1798,7 @@ def evaluate_task( _check_required_evidence(spec, kinds, entries), _check_forbidden_evidence(spec, kinds), _check_expected_values(spec, payload), + *([source_check] if source_check is not None else []), _check_evidence_anchor(spec, view, known_ids), _check_tool_legality(spec, trace), _check_tool_validity(spec, trace, steps), diff --git a/queryforge/evaluation/isolation.py b/queryforge/evaluation/isolation.py index f496255..8924ff1 100644 --- a/queryforge/evaluation/isolation.py +++ b/queryforge/evaluation/isolation.py @@ -41,3 +41,30 @@ def strings(value): for number, line in enumerate(path.read_text().splitlines(), 1): if line.strip() and any(fingerprint(s) in protected for s in strings(json.loads(line))): raise ValueError(f"holdout contamination: {path}:{number}") + + +def audit_dataset_schemas(specs, datasets, root: Path) -> dict[str, str]: + """Compare physical schemas, so renaming a dataset cannot evade holdout isolation.""" + from queryforge.infrastructure.db.sqlite_connector import SQLiteConnector + + signatures, splits = {}, {} + for spec in specs: + dataset = datasets.get(spec.dataset) + if dataset is None: + raise ValueError(f"unknown dataset: {spec.dataset}") + if dataset.get("split_scope") != spec.split: + raise ValueError(f"dataset split_scope mismatch: {spec.dataset}") + if spec.dataset not in signatures: + database = Path(dataset["database"]) + connector = SQLiteConnector(str(database if database.is_absolute() else root / database)) + try: + schemas = [connector.describe_table(name).model_dump() for name in connector.list_tables()] + # Rows are deliberately excluded: copied data on the same schema still leaks. + signatures[spec.dataset] = hashlib.sha256(json.dumps(schemas, sort_keys=True).encode()).hexdigest() + finally: + connector.close() + key = signatures[spec.dataset] + if key in splits and splits[key] != spec.split: + raise ValueError(f"physical schema split leakage: {spec.dataset}") + splits[key] = spec.split + return signatures diff --git a/queryforge/evaluation/paired.py b/queryforge/evaluation/paired.py new file mode 100644 index 0000000..e24f201 --- /dev/null +++ b/queryforge/evaluation/paired.py @@ -0,0 +1,75 @@ +"""Paired summaries with task-cluster uncertainty, independent of the agent runtime.""" +from __future__ import annotations + +import math +import random +from collections import defaultdict +from statistics import mean + + +def summarize_pairs(records, *, repeats: int, seed: int = 17, bootstrap_samples: int = 2000): + if repeats < 2 or bootstrap_samples < 100: + raise ValueError("paired experiments need at least two repeats and 100 bootstrap samples") + groups = defaultdict(dict) + datasets = {} + for record in records: + if type(record.get("passed")) is not bool: + raise ValueError("paired verdict must be a boolean") + task, repeat, arm = record["task_id"], record["repeat"], record["arm"] + if arm not in {"baseline", "treatment"} or type(repeat) is not int or not 0 <= repeat < repeats: + raise ValueError("invalid pair arm or repeat") + if task in datasets and datasets[task] != record["dataset"]: + raise ValueError("paired dataset mismatch") + datasets[task] = record["dataset"] + key = (task, repeat) + if arm in groups[key]: + raise ValueError("duplicate pair arm") + groups[key][arm] = record + if not groups: + raise ValueError("no paired observations") + for task in datasets: + for repeat in range(repeats): + if set(groups.get((task, repeat), {})) != {"baseline", "treatment"}: + raise ValueError(f"missing pair: {task}, repeat {repeat}") + eligible = [pair for pair in groups.values() if not any( + r.get("environment_error") or r.get("provider_contract_error") for r in pair.values())] + excluded = [{"task_id": task, "repeat": repeat, + "arms": [arm for arm, r in pair.items() if r.get("environment_error")]} + for (task, repeat), pair in groups.items() if any(r.get("environment_error") for r in pair.values())] + contract_errors = [{"task_id": task, "repeat": repeat, + "arms": [arm for arm, r in pair.items() if r.get("provider_contract_error")]} + for (task, repeat), pair in groups.items() if any(r.get("provider_contract_error") for r in pair.values())] + + def cluster_summary(pairs, value): + clusters = defaultdict(list) + baselines, treatments = defaultdict(list), defaultdict(list) + for pair in pairs: + b, t = value(pair["baseline"]), value(pair["treatment"]) + if b is None or t is None or not all(math.isfinite(x) for x in (b, t)): + continue + task = pair["baseline"]["task_id"] + clusters[task].append(t - b) + baselines[task].append(b) + treatments[task].append(t) + if not clusters: + return {"pairs": 0, "unique_tasks": 0, "baseline_mean": None, "treatment_mean": None, + "delta": None, "ci95": None} + differences = [mean(v) for _, v in sorted(clusters.items())] + rng = random.Random(seed) + samples = sorted(mean(rng.choices(differences, k=len(differences))) for _ in range(bootstrap_samples)) + return {"pairs": sum(map(len, clusters.values())), "unique_tasks": len(clusters), + "baseline_mean": mean(mean(v) for v in baselines.values()), + "treatment_mean": mean(mean(v) for v in treatments.values()), "delta": mean(differences), + "ci95": [samples[int(.025 * bootstrap_samples)], samples[int(.975 * bootstrap_samples) - 1]]} + + return {"total_pairs": len(groups), "evaluable_pairs": len(eligible), "excluded_environment_pairs": excluded, + "excluded_provider_contract_pairs": contract_errors, + "unique_tasks": len(datasets), "datasets": sorted(set(datasets.values())), "repeats": repeats, + "accuracy": cluster_summary(eligible, lambda r: float(r["passed"])), + "wall_ms": cluster_summary(eligible, lambda r: r.get("wall_ms")), + "measured_tokens": cluster_summary(eligible, lambda r: r.get("measured_tokens") or None), + "cost_usd": cluster_summary(eligible, lambda r: r.get("cost_usd") if r.get("cost_basis") in {"reported", "priced"} else None), + "uncertainty": {"method": "paired task-cluster percentile bootstrap", "samples": bootstrap_samples, + "seed": seed, "estimand": "equal-weight task means; treatment minus baseline", + "note": "Repeats stay inside their task cluster. Small curated task sets do not establish generalization; a zero-width interval is not proof of no effect."}, + "complete": not (excluded or contract_errors)} diff --git a/queryforge/evaluation/results.py b/queryforge/evaluation/results.py new file mode 100644 index 0000000..1196937 --- /dev/null +++ b/queryforge/evaluation/results.py @@ -0,0 +1,90 @@ +"""Declared output contracts: column positions stay significant inside a row.""" +from __future__ import annotations + +import math +from typing import Any, Callable, Literal + +from pydantic import BaseModel, ConfigDict, Field, field_validator + + +class ResultContract(BaseModel): + model_config = ConfigDict(extra="forbid") + required_columns: list[str] | None = None + allow_extra_columns: bool = False + row_order: Literal["ordered", "multiset"] = "multiset" + empty: Literal["allow", "forbid"] = "allow" + columns_path: str = "columns" + rows_path: str = "rows" + + @field_validator("required_columns") + @classmethod + def unique_columns(cls, value): + if value is not None and (not value or len(set(value)) != len(value) or any(not name.strip() for name in value)): + raise ValueError("required_columns must be nonempty, unique column names") + return value + + +def cells_match(actual: Any, expected: Any, tolerance: float = 1e-9) -> bool: + if actual is None or expected is None or isinstance(actual, bool) or isinstance(expected, bool): + return actual is expected + if isinstance(actual, (int, float)) and isinstance(expected, (int, float)): + if isinstance(actual, int) and isinstance(expected, int): + return actual == expected + try: + return math.isfinite(actual) and math.isfinite(expected) and math.isclose(actual, expected, rel_tol=tolerance, abs_tol=tolerance) + except OverflowError: + return False + return type(actual) is type(expected) and actual == expected + + +def compare_results(actual_rows, actual_columns, expected_rows, expected_columns, *, + contract: ResultContract | None = None, + cell_match: Callable[[Any, Any], bool] = cells_match, + positional_aliases: bool = False) -> bool: + contract = contract or ResultContract() + if (not isinstance(actual_rows, (list, tuple)) or not isinstance(expected_rows, (list, tuple)) + or (actual_columns is not None and not isinstance(actual_columns, (list, tuple))) + or not isinstance(expected_columns, (list, tuple))): + return False + actual_columns, expected_columns = list(actual_columns or []), list(expected_columns or []) + if not actual_columns and not actual_rows: + # No values exist to establish even legacy positional projection shape. + return False + required = contract.required_columns or expected_columns + if any(not isinstance(column, str) for column in [*actual_columns, *expected_columns]): + return False + if (len(set(actual_columns)) != len(actual_columns) or len(set(expected_columns)) != len(expected_columns) + or not set(required).issubset(expected_columns)): + return False + expected_width = len(expected_columns) + actual_width = len(actual_columns) if actual_columns else expected_width + if any(not isinstance(row, (list, tuple)) or len(row) != actual_width for row in actual_rows): + return False + if any(not isinstance(row, (list, tuple)) or len(row) != expected_width for row in expected_rows): + return False + if actual_columns and set(required).issubset(actual_columns): + if not contract.allow_extra_columns and set(actual_columns) != set(required): + return False + actual_positions = [actual_columns.index(column) for column in required] + expected_positions = [expected_columns.index(column) for column in required] + elif positional_aliases and contract.required_columns is None and actual_width == expected_width and ( + not actual_columns or not (set(actual_columns) & set(expected_columns)) + ): + actual_positions = expected_positions = list(range(expected_width)) + else: + return False + if contract.empty == "forbid" and (not actual_rows or not expected_rows): + return False + if len(actual_rows) != len(expected_rows): + return False + def row_matches(actual, expected): + return all(cell_match(actual[a], expected[e]) for a, e in zip(actual_positions, expected_positions)) + if contract.row_order == "ordered": + return all(row_matches(a, e) for a, e in zip(actual_rows, expected_rows)) + remaining = list(actual_rows) + for expected in expected_rows: + match = next((i for i, row in enumerate(remaining) if row_matches(row, expected)), None) + if match is None: + return False + remaining.pop(match) + return True diff --git a/queryforge/evaluation/sources.py b/queryforge/evaluation/sources.py new file mode 100644 index 0000000..c7e65d9 --- /dev/null +++ b/queryforge/evaluation/sources.py @@ -0,0 +1,97 @@ +"""Independent SQLite source coverage for opt-in evaluation contracts. + +Source coverage is a necessary check, not proof that joins, filters or business +meaning are correct. Only physical sources in scopes used by the final SELECT +are counted. An unused CTE, a table alias and a coincidentally equal result +cannot establish a required source. +""" + +from __future__ import annotations + +from dataclasses import dataclass + +import sqlglot +from sqlglot import exp +from sqlglot.errors import SqlglotError +from sqlglot.optimizer.normalize_identifiers import normalize_identifiers +from sqlglot.optimizer.scope import Scope, build_scope + + +@dataclass(frozen=True) +class SourceCoverage: + verified: bool + active_tables: tuple[str, ...] = () + missing_tables: tuple[str, ...] = () + reason: str | None = None + + @property + def passed(self) -> bool: + return self.verified and not self.missing_tables + + +class _UnsupportedSource(ValueError): + pass + + +def check_sql_sources(sql: object, required_tables: list[str]) -> SourceCoverage: + """Verify physical source names without executing SQL or consulting runtime. + + This contract supports the isolated SQLite fixtures: ASCII identifiers, + unqualified names and the ``main`` namespace, SELECTs, non-recursive CTEs + and set operations. + Other namespaces, recursive CTEs, source functions and unsupported scopes + return unverified. Values, aliases and the model's own verdict are ignored. + """ + + if not isinstance(required_tables, list) or any( + not isinstance(name, str) or not name.strip().isascii() or not name.strip().isidentifier() + for name in required_tables + ): + return SourceCoverage(False, reason="unsupported_required_table") + required = {name.strip().casefold() for name in required_tables} + if not isinstance(sql, str) or not sql.strip(): + return SourceCoverage(False, reason="missing_sql") + try: + statements = sqlglot.parse(sql, read="sqlite") + if len(statements) != 1 or not isinstance(statements[0], (exp.Select, exp.SetOperation)): + return SourceCoverage(False, reason="unsupported_statement") + # SQLGlot's Unicode normalization must not equate distinct SQLite names. + if any(not node.name.isascii() for node in statements[0].find_all(exp.Identifier)): + return SourceCoverage(False, reason="unsupported_identifier") + tree = normalize_identifiers(statements[0], dialect="sqlite") + if any(node.args.get("recursive") for node in tree.find_all(exp.With)): + return SourceCoverage(False, reason="recursive_cte") + root = build_scope(tree) + if root is None: + return SourceCoverage(False, reason="unsupported_scope") + active: set[str] = set() + visited: set[int] = set() + + def visit(scope: Scope) -> None: + if id(scope) in visited: + return + visited.add(id(scope)) + if not isinstance(scope.expression, (exp.Select, exp.SetOperation)): + raise _UnsupportedSource("unsupported_scope") + for _, source in scope.selected_sources.values(): + if isinstance(source, Scope): + visit(source) + elif isinstance(source, exp.Table) and isinstance(source.this, exp.Identifier): + if not source.name: + raise _UnsupportedSource("unsupported_source") + if source.catalog or (source.db and source.db.casefold() != "main"): + raise _UnsupportedSource("unsupported_namespace") + active.add(source.name.casefold()) + else: + raise _UnsupportedSource("unsupported_source") + for child in (*scope.subquery_scopes, *scope.union_scopes): + visit(child) + + visit(root) + missing = required - active + return SourceCoverage(True, tuple(sorted(active)), tuple(sorted(missing)), + "missing_required_tables" if missing else None) + except _UnsupportedSource as exc: + return SourceCoverage(False, reason=str(exc)) + except (SqlglotError, ValueError, TypeError, RecursionError): + return SourceCoverage(False, reason="invalid_or_unsupported_sql") diff --git a/queryforge/evaluation/tasks.py b/queryforge/evaluation/tasks.py index 2608ef4..a2c1b42 100644 --- a/queryforge/evaluation/tasks.py +++ b/queryforge/evaluation/tasks.py @@ -24,6 +24,7 @@ from typing import Any, Iterable, Literal, Sequence from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator +from queryforge.evaluation.results import ResultContract #: Splits of the benchmark; the file name is the split (contract 2.2/2.4). KNOWN_SPLITS: tuple[str, ...] = ("dev", "regression", "holdout") @@ -117,7 +118,10 @@ class TaskSpec(BaseModel): required_evidence: list[str] = Field(default_factory=list) forbidden_evidence: list[str] = Field(default_factory=list) expected_values: dict[str, Any] = Field(default_factory=dict) + result_contract: ResultContract | None = None + required_sql_tables: list[str] = Field(default_factory=list) values_tolerance: dict[str, float] = Field(default_factory=dict) + values_absolute_tolerance: dict[str, float] = Field(default_factory=dict) answer_must_reference_evidence: bool = True forbidden_claims: list[str] = Field(default_factory=list) required_claims: list[str] = Field(default_factory=list) @@ -142,6 +146,24 @@ class TaskSpec(BaseModel): def _normalize_lists(cls, value: Any) -> list[str]: return _clean_text_list(value) + @field_validator("required_sql_tables", mode="before") + @classmethod + def _require_source_names(cls, value: Any) -> list[str]: + # Unlike descriptive lists, an invalid constraint must not be dropped. + if not isinstance(value, list): + raise ValueError("required_sql_tables must be a list of non-empty table names") + names: list[str] = [] + for item in value: + if not isinstance(item, str) or not item.strip(): + raise ValueError("required_sql_tables must contain non-empty strings") + if not item.strip().isascii() or not item.strip().isidentifier(): + raise ValueError("required_sql_tables supports unqualified ASCII identifiers") + name = item.strip().casefold() + if name in names: + raise ValueError("required_sql_tables contains a duplicate table name") + names.append(name) + return names + @field_validator("task_id", "dataset", "question") @classmethod def _require_text(cls, value: str) -> str: @@ -155,7 +177,7 @@ def _require_text(cls, value: str) -> str: def _normalize_replaceable(cls, value: Any) -> dict[str, list[str]]: return _clean_replaceable(value) - @field_validator("values_tolerance", mode="before") + @field_validator("values_tolerance", "values_absolute_tolerance", mode="before") @classmethod def _normalize_tolerance(cls, value: Any) -> dict[str, float]: return _clean_tolerance(value) diff --git a/queryforge/infrastructure/storage/report_store.py b/queryforge/infrastructure/storage/report_store.py new file mode 100644 index 0000000..73acb36 --- /dev/null +++ b/queryforge/infrastructure/storage/report_store.py @@ -0,0 +1,55 @@ +"""Local report confinement, expiry and reversible operator cleanup.""" +from __future__ import annotations + +import os +import re +import time +from pathlib import Path +from uuid import uuid4 + + +class ReportStore: + def __init__(self, root: str | Path, retention_days: int = 30): + if not 1 <= retention_days <= 3650: + raise ValueError("Report retention must be between 1 and 3650 days") + self.root = Path(root).expanduser().resolve() + self.retention_days = retention_days + + def paths(self, run_id: str) -> tuple[Path, Path]: + if not re.fullmatch(r"[A-Za-z0-9_-]{1,128}", run_id or ""): + raise ValueError("run_id contains unsafe path characters") + paths = (self.root / f"{run_id}.html", self.root / f"{run_id}.manifest.json") + if any(path.is_symlink() or path.resolve().parent != self.root for path in paths): + raise ValueError("Report path escapes the configured directory") + return paths + + def report_path(self, run_id: str, *, now: float | None = None) -> Path: + path, _ = self.paths(run_id) + if not path.is_file(): + raise ValueError(f"Report does not exist for run_id {run_id!r}") + if path.stat().st_mtime <= (time.time() if now is None else now) - self.retention_days * 86400: + raise ValueError(f"Report expired for run_id {run_id!r}") + return path + + def expire(self, *, dry_run: bool = True, now: float | None = None) -> dict: + """Quarantine expired HTML/manifest pairs; never delete retained evidence.""" + cutoff = (time.time() if now is None else now) - self.retention_days * 86400 + expired, skipped = [], [] + for html in sorted(self.root.glob("*.html")): + try: + paths = self.paths(html.stem) + if html.stat().st_mtime > cutoff: + continue + if not dry_run: + quarantine = self.root / ".expired" + if quarantine.is_symlink(): + raise ValueError("Unsafe report quarantine directory") + destination = quarantine / f"{html.stem}_{uuid4().hex}" + destination.mkdir(parents=True) + for path in paths: + if path.is_file(): + os.replace(path, destination / path.name) + expired.append(html.stem) + except (OSError, ValueError) as exc: + skipped.append({"run_id": html.stem, "reason": str(exc)}) + return {"dry_run": dry_run, "expired": expired, "skipped": skipped, "action": "preview" if dry_run else "quarantined"} diff --git a/queryforge/interfaces/api/app.py b/queryforge/interfaces/api/app.py index c098d03..d122d3d 100644 --- a/queryforge/interfaces/api/app.py +++ b/queryforge/interfaces/api/app.py @@ -17,6 +17,7 @@ SessionExpireRequest, SessionPreferenceRequest, SessionVersionInvalidationRequest, + ReportExpireRequest, ) from queryforge.interfaces.gateway import GatewayAdapter from queryforge.interfaces.transport_security import request_api_key_matches @@ -128,6 +129,14 @@ async def transport_auth(request: Request, call_next): return JSONResponse( {"detail": "Authentication required."}, status_code=401 ) + # Local browser clients use the Studio proxy. A foreign web origin must + # not be able to submit a simple multipart request directly to the + # unauthenticated loopback API (JSON preflight alone is insufficient). + if request.url.hostname in {"localhost", "127.0.0.1", "::1"}: + origin = request.headers.get("origin") + expected_origin = f"{request.url.scheme}://{request.url.netloc}" + if (origin and origin != expected_origin) or request.headers.get("sec-fetch-site") == "cross-site": + return JSONResponse({"detail": "Cross-origin local API request denied."}, status_code=403) return await call_next(request) def call(operation: Callable[[], dict | list]): @@ -300,6 +309,10 @@ def report(run_id: str): except ValueError as exc: raise HTTPException(status_code=404, detail=str(exc)) from exc + @app.post("/reports/expire") + def expire_reports(request: ReportExpireRequest): + return call(lambda: agent_service.expire_reports(dry_run=request.dry_run)) + @app.post("/gateway/webhook") def gateway_webhook(request: GatewayWebhookRequest): return call( diff --git a/queryforge/interfaces/api/schemas.py b/queryforge/interfaces/api/schemas.py index 01debb4..5c0a35f 100644 --- a/queryforge/interfaces/api/schemas.py +++ b/queryforge/interfaces/api/schemas.py @@ -7,6 +7,10 @@ from queryforge.application import AgentOptions +class ReportExpireRequest(BaseModel): + dry_run: bool = True + + class AskRequest(BaseModel): question: str = Field(min_length=1) database: str | None = None diff --git a/queryforge/orchestration/planner/executor.py b/queryforge/orchestration/planner/executor.py index 5b30056..d243d1b 100644 --- a/queryforge/orchestration/planner/executor.py +++ b/queryforge/orchestration/planner/executor.py @@ -18,6 +18,7 @@ import re import time +from datetime import date, timedelta from concurrent.futures import ThreadPoolExecutor from typing import Any, Callable, Literal, Mapping, Sequence @@ -30,8 +31,11 @@ stable_digest, ) from queryforge.domain.semantic.model import SemanticModelLoader -from queryforge.domain.semantic.schemas import MetricMatch -from queryforge.domain.semantic.sql_validator import QuerySpec, QuerySpecCompiler +from queryforge.domain.semantic.query_constraints import UnsupportedConstraint, require_filter_predicates +from queryforge.domain.analysis.diagnostics import reconcile_buckets +from queryforge.domain.semantic.periods import baseline_day, label_date, period_label, period_bounds, require_complete_period +from queryforge.domain.semantic.schemas import MetricMatch, MetricTimeContract +from queryforge.domain.semantic.sql_validator import QuerySpec, QuerySpecCompiler, SemanticSQLValidator from queryforge.orchestration.planner.plan import ( LOCAL_ACTIONS, AnalysisPlan, @@ -609,7 +613,7 @@ def _reuse_step( record = self.journal.step(step_id) if record is None or not record.reusable(): return False - kind = EVIDENCE_KINDS.get(step.action, step.action) + kind = self._evidence_kind(step) outputs = dict(record.outputs or {}) if step.action not in LOCAL_ACTIONS: evidence_id = ( @@ -897,10 +901,11 @@ def _run_step( state.blocked_reason = str(exc) else: result.outputs = outputs - evidence_id = context.evidence_id(EVIDENCE_KINDS.get(step.action, step.action)) + kind = self._evidence_kind(step) + evidence_id = context.evidence_id(kind) if step.action not in LOCAL_ACTIONS: state.record_evidence( - step, evidence_id, EVIDENCE_KINDS.get(step.action, step.action), outputs + step, evidence_id, kind, outputs ) result.evidence_ids = [evidence_id] elif outputs.get("answer") is not None: @@ -950,6 +955,12 @@ def _fail( # ------------------------------------------------------------- dispatch + @staticmethod + def _evidence_kind(step: PlanStep) -> str: + if step.action == "query_metric" and step.inputs.get("result_role") == "metric_totals": + return "metric_totals" + return EVIDENCE_KINDS.get(step.action, step.action) + def _dispatch( self, step: PlanStep, @@ -1005,24 +1016,55 @@ def _dispatch_computed( if not observation.ok: raise self._error_for_observation(observation) return dict(observation.result or {}) - params = self._assemble_step11(action, step, state) - observation = self._execute_tool(tool, params, context=context, step=step) + dataset = state.evidence_payload(step.inputs.get("dataset_kind") or "metric_value") or {} + if action in {"compare_periods", "calculate_contribution", "detect_anomaly"} and len(dataset.get("metrics", [])) > 1: + collections = {} + for name in dataset["metrics"]: + collections[name] = self._computed_payload(action, step, context, state, {**dataset, "metric": name}) + key = {"compare_periods": "comparisons", "calculate_contribution": "by_metric", "detect_anomaly": "by_metric"}[action] + payload = {**collections[dataset["metrics"][0]], "metrics": dataset["metrics"], key: collections, + "period_completeness": dataset.get("period_completeness", "unverified")} + if step.inputs.get("comparison_baseline"): + payload["comparison_baseline"] = step.inputs["comparison_baseline"] + return payload + return self._computed_payload(action, step, context, state, dataset) + + def _computed_payload(self, action, step, context, state, dataset): + params = self._assemble_step11(action, step, state, dataset_override=dataset) + reconciliation = params.pop("_reconciliation", None) + observation = self._execute_tool(self._tool_for(action), params, context=context, step=step) if not observation.ok: raise self._error_for_observation(observation) payload = dict(observation.result or {}) + if action == "compare_periods" and step.inputs.get("comparison_baseline"): + payload["comparison_baseline"] = step.inputs["comparison_baseline"] + metadata = dataset.get("metric_contracts", {}).get(dataset.get("metric"), {}) + payload["period_completeness"] = "complete" if (metadata.get("time") or {}).get("require_complete_periods") else "unverified" + if action == "calculate_contribution": + if payload.get("undefined_reason") or not payload.get("residual_explained"): + raise UnsupportedAnalysisError("unverified_reconciliation: contribution tool could not reconcile the total change") + if reconciliation: + payload.update({key: value for key, value in reconciliation.items() if key != "buckets"}) + payload["source_evidence_ids"] = state.evidence_ids_for(["metric_value", "metric_totals", "period_comparison"]) + payload["category_dimensions"] = [bucket["dimensions"] for bucket in reconciliation["buckets"]] payload.setdefault("method", payload.get("method")) payload.setdefault("parameters", {"assembled": True, **{k: v for k, v in params.items() if k not in {"series", "buckets", "rows"}}}) return payload def _assemble_step11( - self, action: str, step: PlanStep, state: "_ExecutionState" + self, action: str, step: PlanStep, state: "_ExecutionState", *, dataset_override=None, ) -> dict[str, Any]: knobs = dict(step.validation.get("knobs") or {}) - dataset = state.evidence_payload("metric_value") or {} + dataset = dataset_override if dataset_override is not None else (state.evidence_payload("metric_value") or {}) resolution = state.evidence_payload("metric_resolution") or {} metric_kind = self._metric_kind(resolution) if action == "compare_periods": self._require_single_series_dimension(action, dataset) + query_limit = (dataset.get("query_spec") or {}).get("limit") + if step.inputs.get("comparison_baseline") and ( + dataset.get("truncated") or (query_limit and len(dataset.get("rows") or []) >= query_limit) + ): + raise UnsupportedAnalysisError("unsupported_baseline: bounded series cannot prove the latest period") series = self._series(dataset) if len(series) < 2: raise DataAbsentError( @@ -1034,16 +1076,31 @@ def _assemble_step11( self._require_ordered_time_series( action, [str(point["period"]) for point in series] ) + current, baseline = self._comparison_pair( + series, step.inputs.get("comparison_baseline"), step.inputs.get("time_grain") or dataset.get("time_grain"), dataset=dataset, + ) return { - "current": series[-1]["value"], - "baseline": series[-2]["value"], - "label": f"{series[-2]['period']} -> {series[-1]['period']}", + "current": current["value"], + "baseline": baseline["value"], + "label": f"{baseline['period']} -> {current['period']}", + "unit": (dataset.get("metric_contracts", {}).get(dataset.get("metric"), {}) or {}).get("unit"), # Explicit values: schema validation may materialise omitted # optional parameters as None, which would override the tool's # own defaults. "method": str(knobs.get("method") or "absolute_relative"), } if action == "drill_down": + analysis = resolution.get("analysis") or {} + if analysis.get("additivity_proof") == "unique_row_identity": + checks = (state.evidence_payload("data_quality") or {}).get("checks", []) + if not any(c.get("check") == "grain_unique" and c.get("status") == "ok" + and c.get("table") == resolution.get("table") for c in checks): + raise UnsupportedAnalysisError("unverified_additivity: row identity uniqueness was not proven") + if (analysis.get("additivity") == "non_additive" or any( + dimension in analysis.get("non_additive_dimensions", []) + for dimension in dataset.get("dimensions", []) + )): + raise UnsupportedAnalysisError("unsupported_additivity: bucket totals cannot be summed for this metric") buckets = self._buckets(dataset) if not buckets: raise DataAbsentError("data_absent: no categorical buckets to drill into") @@ -1058,23 +1115,44 @@ def _assemble_step11( params["dimension"] = knobs["dimension"] return params if action == "calculate_contribution": - contribution = self._contribution_buckets(dataset) - if contribution is None: - raise DataAbsentError( - "data_absent: contribution needs per-category values for two " - "comparable periods in one result" - ) + metadata = dataset.get("metric_contracts", {}).get(dataset.get("metric"), {}) + if metadata.get("additivity") != "additive": + raise UnsupportedAnalysisError("unsupported_additivity: this metric cannot be decomposed by summing buckets") + if metadata.get("additivity_proof") == "unique_row_identity": + spec = dataset.get("query_spec") or {} + checks = list((state.evidence_payload("data_quality") or {}).get("checks", [])) + checks.extend(c for audit in spec.get("grain_checks", []) for c in audit.get("checks", [])) + sources = [table for table, _ in spec.get("source_grains", [])] + if not sources or not all(any(c.get("check") == "grain_unique" and c.get("status") == "ok" + and c.get("table") == table for c in checks) for table in sources): + raise UnsupportedAnalysisError("unverified_additivity: row identity uniqueness was not proven") + totals = state.evidence_payload("metric_totals") or {} + comparison = state.evidence_payload("period_comparison") or {} + comparison = comparison.get("comparisons", {}).get(dataset.get("metric"), comparison) + periods = str(comparison.get("label") or "").split(" -> ") + if len(periods) != 2: + raise UnsupportedAnalysisError("unverified_reconciliation: an independently compared pair is required") + try: + contribution = reconcile_buckets(dataset, totals, dataset["metric"], periods[1], periods[0]) + except ValueError as exc: + raise UnsupportedAnalysisError(str(exc)) from exc return { - "buckets": contribution["buckets"], - "metric_kind": metric_kind, + "buckets": [{k: v for k, v in bucket.items() if k != "dimensions"} for bucket in contribution["buckets"]], + "metric_kind": "additive", "expected_total_delta": contribution.get("expected_total_delta"), "additive": True, + "_reconciliation": contribution, + "unit": metadata.get("unit"), } if action == "detect_anomaly": self._require_single_series_dimension(action, dataset) + query_limit = (dataset.get("query_spec") or {}).get("limit") + if dataset.get("truncated") or (query_limit and len(dataset.get("rows") or []) >= query_limit): + raise UnsupportedAnalysisError("unverified_anomaly: bounded series") series = self._series(dataset) if not series: raise DataAbsentError("data_absent: no ordered series to analyse") + self._require_ordered_time_series(action, [str(point["period"]) for point in series]) return { "series": series, "method": str(knobs.get("method") or "baseline_deviation"), @@ -1082,10 +1160,15 @@ def _assemble_step11( "seasonality": str(knobs.get("seasonality") or "none"), "missing": str(knobs.get("missing") or "skip"), "threshold": float(knobs.get("threshold") or 2.0), + "unit": dataset.get("metric_contracts", {}).get(dataset.get("metric"), {}).get("unit"), } if action == "render_chart": rows = list(dataset.get("rows") or []) columns = [str(column) for column in (dataset.get("columns") or [])] + audit = {name + suffix for name in dataset.get("metrics", []) for suffix in ("__numerator", "__denominator")} + indexes = [i for i, column in enumerate(columns) if column not in audit] + rows = [[row[i] for i in indexes] for row in rows] + columns = [columns[i] for i in indexes] if not rows or not columns: raise DataAbsentError("data_absent: no result rows to chart") return { @@ -1098,6 +1181,63 @@ def _assemble_step11( f"plan action {action!r} has no value assembly", tool=action ) + @staticmethod + def _comparison_pair(series, baseline, grain, dataset=None): + if not baseline: + return series[-1], series[-2] # historical hand-authored plans + current = series[-1] + label = str(current["period"]) + metadata = ((dataset or {}).get("metric_contracts") or {}).get((dataset or {}).get("metric"), {}) + temporal = MetricTimeContract.model_validate(metadata["time"]) if metadata.get("time") else None + if grain: + try: + requested = ((dataset or {}).get("query_spec") or {}).get("requested_ranges", []) + if requested: + expected_current = period_label(date.fromisoformat(max(span[1] for span in requested)), grain, temporal) + if label != expected_current: + raise DataAbsentError(f"data_absent: requested current period {expected_current} is missing") + require_complete_period(label, grain, temporal, requested) + expected = period_label(baseline_day(label_date(label), baseline, grain), grain, temporal) + match = next((point for point in series if str(point["period"]) == expected), None) + if match is None: + raise DataAbsentError(f"data_absent: requested baseline {baseline!r} ({expected}) is missing") + require_complete_period(expected, grain, temporal) + return current, match + except UnsupportedConstraint as exc: + raise UnsupportedAnalysisError(str(exc)) from exc + if not grain: + grain = ("daily" if re.fullmatch(r"\d{4}-\d{2}-\d{2}", label) + else "monthly" if re.fullmatch(r"\d{4}-\d{2}", label) + else "quarterly" if re.fullmatch(r"\d{4}-Q[1-4]", label) + else "yearly" if re.fullmatch(r"\d{4}", label) else None) + position = _calendar_position(label) + if grain is None or position is None or position[0] == 0: + raise UnsupportedAnalysisError("unsupported_baseline: dated calendar periods are required") + year, month = position + expected = None + if baseline in {"same_period_last_year", "previous_year"}: + expected = str(year - 1) + label[4:] + elif baseline in {"previous_period", "previous_month", "previous_quarter"}: + if baseline == "previous_month" and grain != "monthly": + raise UnsupportedAnalysisError("unsupported_baseline: previous_month requires monthly grain") + if baseline == "previous_quarter" and grain != "quarterly": + raise UnsupportedAnalysisError("unsupported_baseline: previous_quarter requires quarterly grain") + if grain == "daily": + expected = (date.fromisoformat(label) - timedelta(days=1)).isoformat() + elif grain in {"monthly", "quarterly"}: + previous = year * 12 + month - 1 - (3 if grain == "quarterly" else 1) + previous_year, previous_month = divmod(previous, 12) + expected = (f"{previous_year:04d}-Q{previous_month // 3 + 1}" if grain == "quarterly" + else f"{previous_year:04d}-{previous_month + 1:02d}") + elif grain == "yearly": + expected = str(year - 1) + else: + raise UnsupportedAnalysisError(f"unsupported_baseline: {baseline!r}") + match = next((point for point in series if str(point["period"]) == expected), None) + if match is None: + raise DataAbsentError(f"data_absent: requested baseline {baseline!r} ({expected}) is missing") + return current, match + @staticmethod def _metric_kind(resolution: dict[str, Any]) -> str: aggregation = str(resolution.get("aggregation") or "sum").casefold() @@ -1105,6 +1245,8 @@ def _metric_kind(resolution: dict[str, Any]) -> str: return "ratio" if aggregation in {"count_distinct", "distinct"}: return "distinct" + if (resolution.get("analysis") or {}).get("additivity") == "non_additive": + return "distinct" return "additive" @classmethod @@ -1162,6 +1304,14 @@ def _require_ordered_time_series( alphabetically re-ordered series — cannot pass it. """ + if all(re.fullmatch(r"\d{4}-\d{2}-\d{2}", str(label)) for label in labels): + try: + positions = [date.fromisoformat(str(label)).toordinal() for label in labels] + except ValueError as exc: + raise UnsupportedAnalysisError("unsupported_grain: invalid calendar date") from exc + if all(current > previous for previous, current in zip(positions, positions[1:])): + return + raise UnsupportedAnalysisError("unsupported_grain: daily series is not in time order") positions = [_calendar_position(label) for label in labels] if any(position is None for position in positions): unlabelled = [ @@ -1199,7 +1349,8 @@ def _series(cls, dataset: dict[str, Any]) -> list[dict[str, Any]]: rows = list(dataset.get("rows") or []) if len(columns) < 2: return [] - value_index = cls._numeric_index(columns, rows) + value_index = (columns.index(dataset["metric"]) if dataset.get("metric") in columns + else cls._numeric_index(columns, rows)) if value_index is None: return [] label_index = next( @@ -1357,6 +1508,7 @@ def _resolve_metric( "entity": metric.entity, "table": entity.table if entity else None, "expression": metric.expression, + "analysis": QuerySpecCompiler._analysis_metadata(metric, entity), "time_field": metric.time_field, "declared_dimensions": dimensions, "legal_dimensions": legal, @@ -1402,16 +1554,28 @@ def _query_metric( ] limit = int(step.inputs.get("limit") or 100) explicit_sql = step.inputs.get("sql") + metric_ids = list(step.inputs.get("metric_ids") or [metric_name]) + filters = [str(item["expression"]) for item in (step.inputs.get("filters") or [])] spec: QuerySpec | None = None if explicit_sql: + governed = context.semantic_model.model if context.semantic_model else None + if governed and any(m.ratio for m in governed.metrics if m.name in metric_ids): + raise UnsupportedAnalysisError("unsupported_request: explicit SQL cannot prove declared ratio components") + if (filters or len(metric_ids) > 1 or step.inputs.get("time_grain") + or getattr(context, "date_context", None)): + raise UnsupportedAnalysisError("unsupported_request: explicit SQL cannot prove these request constraints") sql = str(explicit_sql) degraded, degraded_reason = False, None else: - spec = self._compile_spec(context, str(metric_name or ""), dimensions, limit, resolution) + spec = self._compile_spec( + context, str(metric_name or ""), dimensions, limit, resolution, + metric_ids=metric_ids, user_filters=filters, time_grain=step.inputs.get("time_grain"), + comparison_baseline=step.inputs.get("comparison_baseline"), + ) if spec is not None: sql = spec.sql degraded, degraded_reason = False, None - elif dimensions: + elif dimensions or filters or len(metric_ids) > 1 or step.inputs.get("time_grain"): # A breakdown was requested and no governed query could be # compiled for it: a raw preview would answer a different # question, so the step fails instead of reporting success. @@ -1422,6 +1586,51 @@ def _query_metric( else: return self._query_metric_fallback(step, context, state, result, resolution) + try: + require_filter_predicates(sql, filters, metric_ctes=spec.evidence.get("metric_ctes") if spec else None) + except UnsupportedConstraint as exc: + raise UnsupportedAnalysisError(str(exc)) from exc + if spec: + for metadata in spec.evidence.get("metric_contracts", {}).values(): + temporal = metadata.get("time") or {} + if temporal.get("require_complete_periods"): + first, last = date.fromisoformat(temporal["coverage_start"]), date.fromisoformat(temporal["complete_through"]) + for start, end in spec.evidence.get("requested_ranges", []): + start_day, end_day = date.fromisoformat(start), date.fromisoformat(end) + if end_day < first or start_day > last: + raise DataAbsentError("data_absent: no value for the requested scope outside complete coverage") + if start_day < first or end_day > last: + raise UnsupportedAnalysisError("incomplete_period: requested window extends outside complete coverage") + if spec.evidence.get("metric_ctes"): + selected = [MetricMatch(matched_term=name, metric=next(m for m in context.semantic_model.model.metrics if m.name == name)) for name in metric_ids] + verdict = SemanticSQLValidator(context.semantic_model, selected, requested_dimensions=dimensions, + date_context=getattr(context, "date_context", None), time_grain=spec.time_grain, + comparison_baseline=step.inputs.get("comparison_baseline"), user_filters=filters).validate(sql) + if verdict.status != "passed": + raise UnsupportedAnalysisError(verdict.error_message()) + for validation_sql in spec.evidence.get("time_validations", []): + observation = self._execute_sql("execute_sql", validation_sql, context=context, step=step) + payload = dict(observation.result or {}) + if not observation.ok or payload.get("rows") != [[0]]: + raise UnsupportedAnalysisError("unverified_time_values: metric event dates violate the time contract") + spec.evidence.setdefault("time_checks", []).append({"sql": validation_sql, "invalid_dates": 0}) + # Check the actual join target, not merely the author's declaration. + # Unknown/denied checks fail closed. All SQL remains inside DatabaseTool. + checks = [(table, [column]) for table, column in spec.evidence.get("join_keys", [])] + checks += [(table, grain) for table, grain in spec.evidence.get("source_grains", []) if table != spec.base_table] + for table, grain in dict.fromkeys((table, tuple(grain)) for table, grain in checks): + unique = self._execute_tool("check_data_quality", { + "table_name": table, "checks": ["grain_unique"], + "options": {"grain_columns": list(grain)}, + }, context=context, step=step) + check = dict(unique.result or {}) + spec.evidence.setdefault("grain_checks", []).append(check) + if unique.ok and any(c.get("reason") == "empty_table" for c in check.get("checks", [])): + suggestions = state.note_missing_dimension(metric_name, dimensions, resolution) + raise DataAbsentError(_with_alternative_dimensions( + f"data_absent: join population {table!r} is empty for dimensions {dimensions}", suggestions)) + if not unique.ok or check.get("status") != "ok": + raise UnsupportedAnalysisError(f"unverified_join_grain: {table}.{grain} is not proven unique") observation = self._execute_sql("execute_sql", sql, context=context, step=step) if not observation.ok: if observation.error_category == WorkflowErrorCategory.budget.value: @@ -1430,6 +1639,8 @@ def _query_metric( payload = dict(observation.result or {}) rows = list(payload.get("rows") or []) columns = list(payload.get("columns") or []) + if spec is not None and not set(metric_ids).issubset(columns): + raise UnsupportedAnalysisError("request_incomplete: result is missing requested metric columns") if not rows: suggestions = state.note_missing_dimension( metric_name, dimensions, resolution @@ -1441,9 +1652,15 @@ def _query_metric( suggestions, ) ) + values = ({name: rows[0][columns.index(name)] for name in metric_ids} + if spec and not dimensions and len(rows) == 1 else {}) + if any(value is None for value in values.values()): + raise DataAbsentError("data_absent: a requested metric has no value for the requested scope (absent data or zero denominator)") + if spec and any(row[columns.index(name)] is None for row in rows for name in metric_ids): + raise DataAbsentError("unverified_measure: a group is absent or has a zero denominator; no complete answer can be claimed") value = None - if len(rows) == 1 and len(columns) == 1: - value = rows[0][0] + if len(rows) == 1 and ((spec and not dimensions and len(metric_ids) == 1) or len(columns) == 1): + value = rows[0][columns.index(metric_ids[0])] if spec else rows[0][0] if value is None: # A scalar aggregate is NULL when the requested scope has no rows # ("watch hours in Q1 1990"). Reporting that as a successful answer @@ -1461,6 +1678,12 @@ def _query_metric( ) prepared: dict[str, Any] = { "metric": metric_name, + "metrics": metric_ids, + "values": values, + "filters": list(spec.user_filters) if spec else [], + "time_grain": spec.time_grain if spec else None, + "time_filter": spec.time_filter if spec else None, + "truncated": observation.truncated, "aggregation": (spec.aggregation if spec else resolution.get("aggregation")), "sql": sql, "columns": columns, @@ -1476,11 +1699,39 @@ def _query_metric( "aggregation": spec.aggregation, "base_table": spec.base_table, "group_by": list(spec.group_by), + "limit": spec.limit, + **spec.evidence, } if spec else None ), + "metric_contracts": spec.evidence.get("metric_contracts", {}) if spec else {}, + "ratio_components": spec.evidence.get("ratio_components", {}) if spec else {}, + "period_completeness": "unverified", } + if spec and spec.time_grain and dimensions and spec.evidence.get("time_dimension") == dimensions[0]: + metadatas = list(spec.evidence["metric_contracts"].values()) + for metadata in metadatas: + temporal = MetricTimeContract.model_validate(metadata["time"]) if metadata.get("time") else None + if not temporal or not temporal.require_complete_periods: + continue + requested = spec.evidence.get("requested_ranges", []) + try: + labels = {str(row[0]) for row in rows} + for label in labels: + require_complete_period(label, spec.time_grain, temporal) + for start, end in requested: + cursor = period_bounds(date.fromisoformat(start), spec.time_grain, temporal)[0] + while cursor <= date.fromisoformat(end): + label = period_label(cursor, spec.time_grain, temporal) + require_complete_period(label, spec.time_grain, temporal, requested) + if label not in labels: + raise DataAbsentError(f"data_absent: complete-period request is missing {label}") + cursor = period_bounds(cursor, spec.time_grain, temporal)[1] + timedelta(days=1) + except UnsupportedConstraint as exc: + raise UnsupportedAnalysisError(str(exc)) from exc + if all((metadata.get("time") or {}).get("require_complete_periods") for metadata in metadatas): + prepared["period_completeness"] = "complete" if degraded and degraded_reason: prepared["degraded_reason"] = degraded_reason return prepared @@ -1543,6 +1794,11 @@ def _compile_spec( dimensions: list[str], limit: int, resolution: dict[str, Any], + *, + metric_ids: list[str] | None = None, + user_filters: list[str] | None = None, + time_grain: str | None = None, + comparison_baseline: str | None = None, ) -> QuerySpec | None: """Compile the governed metric SQL, resolving dimension join paths. @@ -1567,18 +1823,29 @@ def _compile_spec( ) if metric is None: return None - paths, problems = self._dimension_join_paths( - model_context, metric.entity, dimensions - ) + selected = [next((m for m in model_context.model.metrics if m.name == name), None) + for name in (metric_ids or [metric_name])] + if any(m is None for m in selected): + raise UnsupportedAnalysisError("unsupported_metric: an undeclared metric was requested") + paths, problems = [], [] + for selected_metric in selected: + current_paths, current_problems = self._dimension_join_paths( + model_context, selected_metric.entity, dimensions + ) + paths.extend(current_paths) + problems.extend(current_problems) if problems: raise UnsupportedAnalysisError("; ".join(problems)) return QuerySpecCompiler.compile( semantic_model=model_context, - metric_matches=[MetricMatch(matched_term=metric_name, metric=metric)], + metric_matches=[MetricMatch(matched_term=m.name, metric=m) for m in selected], metric_join_paths=paths or None, requested_dimensions=dimensions, date_context=getattr(context, "date_context", None), limit=limit, + user_filters=user_filters, + time_grain=time_grain, + comparison_baseline=comparison_baseline, ) def _dimension_join_paths( @@ -1644,6 +1911,30 @@ def _compose_answer(self, step: PlanStep, state: "_ExecutionState") -> dict[str, if not state.evidence_payload(str(kind)): raise ValueError(f"missing_output: {kind}") metric_payload = state.evidence_payload("metric_value") + obligations = step.inputs.get("require_request") or {} + if obligations: + actual = metric_payload or {} + problems = [] + if not set(obligations.get("metric_ids") or []).issubset(actual.get("metrics") or [actual.get("metric")]): + problems.append("metrics") + if not set(obligations.get("filters") or []).issubset(actual.get("filters") or []): + problems.append("filters") + if not set(obligations.get("dimensions") or []).issubset(actual.get("dimensions") or []): + problems.append("dimensions") + baseline = obligations.get("comparison_baseline") + if baseline and (state.evidence_payload("period_comparison") or {}).get("comparison_baseline") != baseline: + problems.append("comparison_baseline") + if obligations.get("time_grain") and actual.get("time_grain") != obligations["time_grain"]: + problems.append("time_grain") + if obligations.get("time_range") and not actual.get("time_filter"): + problems.append("time_range") + if obligations.get("diagnosis"): + contribution = state.evidence_payload("contribution") or {} + delivered = set(contribution.get("by_metric") or ([actual.get("metric")] if contribution else [])) + if not set(obligations.get("metric_ids") or []).issubset(delivered) or not state.evidence_payload("metric_totals"): + problems.append("diagnosis") + if problems: + raise ToolDenied("request_incomplete: " + ", ".join(problems), tool="compose_answer") resolution = state.evidence_payload("metric_resolution") or {} quality = state.evidence_payload("data_quality") or {} findings: list[dict[str, Any]] = [] @@ -1673,12 +1964,42 @@ def _compose_answer(self, step: PlanStep, state: "_ExecutionState") -> dict[str, "question": state.plan.question, "findings": findings, "metric": metric_payload.get("metric") if metric_payload else None, + "metrics": metric_payload.get("metrics", [metric_payload.get("metric")]) if metric_payload else [], + "values": metric_payload.get("values", {}) if metric_payload else {}, + "columns": metric_payload.get("columns", []) if metric_payload else [], + "metric_contracts": metric_payload.get("metric_contracts", {}) if metric_payload else {}, + "ratio_components": metric_payload.get("ratio_components", {}) if metric_payload else {}, + "period_completeness": metric_payload.get("period_completeness", "unverified") if metric_payload else "unverified", "value": metric_payload.get("value") if metric_payload else None, "rows": metric_payload.get("rows") if metric_payload else None, + "comparisons": (state.evidence_payload("period_comparison") or {}).get("comparisons", {}), "evidence_ids": state.evidence_ids_for(required), "limitations": self._limitations(metric_payload, quality), "degraded": bool(metric_payload and metric_payload.get("degraded")), } + for kind in ("period_comparison", "contribution", "anomaly"): + computed = state.evidence_payload(kind) or {} + parts = list(computed.get("by_metric", {}).values()) or [computed] + for part in parts: + answer["limitations"].extend(part.get("limitations") or []) + if part.get("undefined_reason"): + answer["limitations"].append(f"{kind}: {part['undefined_reason']}") + answer["limitations"] = list(dict.fromkeys(answer["limitations"])) + contribution = state.evidence_payload("contribution") + if contribution: + answer["diagnosis"] = { + "interpretation": "arithmetic_decomposition_not_causal_attribution", + "comparison": state.evidence_payload("period_comparison"), + "contributions": contribution.get("by_metric") or {answer["metric"]: contribution}, + "anomalies": (state.evidence_payload("anomaly") or {}).get("by_metric") or { + answer["metric"]: state.evidence_payload("anomaly")}, + "quality": {"status": quality.get("status"), "counts": quality.get("counts"), + "time_checks": (metric_payload.get("query_spec") or {}).get("time_checks", []), + "grain_checks": (metric_payload.get("query_spec") or {}).get("grain_checks", [])}, + "period_completeness": answer["period_completeness"], + "evidence_ids": state.evidence_ids_for(["metric_value", "metric_totals", "data_quality", + "period_comparison", "contribution", "anomaly"]), + } state.answer = answer payload: dict[str, Any] = {"answer": answer, "required_evidence": required} evidence_layer = ( @@ -1752,10 +2073,11 @@ def _final_answer( Finding( kind="metric", statement=( - f"{metric_payload.get('metric')} over " + f"{', '.join(metric_payload.get('metrics') or [metric_payload.get('metric')])} over " f"{', '.join(metric_payload.get('dimensions') or []) or 'the full set'}" ), - numbers={}, + numbers={name: None for name in metric_payload.get("values", {})} + if len(metric_payload.get("metrics", [])) > 1 else {}, dimensions=[str(item) for item in metric_payload.get("dimensions") or []], evidence_ids=metric_ids, degraded=bool(metric_payload.get("degraded")), @@ -1784,6 +2106,12 @@ def _final_answer( payload = state.evidence_payload(evidence_kind) if not payload or not evidence_ids: continue + if evidence_kind == "period_comparison" and payload.get("comparisons"): + numbers = {f"comparisons.{name}.{key}": None for name, comparison in payload["comparisons"].items() + for key in ("current", "baseline", "delta", "relative_change") if isinstance(comparison.get(key), (int, float))} + if evidence_kind == "contribution" and payload.get("by_metric"): + numbers = {f"by_metric.{name}.{key}": None for name, part in payload["by_metric"].items() + for key in ("total_delta", "residual", "independent_current", "independent_baseline")} findings.append( Finding( kind=kind, @@ -1864,6 +2192,8 @@ def _limitations( "metric evidence is degraded: " + str(metric_payload.get("degraded_reason") or "bounded preview") ) + if metric_payload and metric_payload.get("time_grain") and metric_payload.get("period_completeness") != "complete": + limitations.append("period completeness is unverified: no enforced ingestion coverage contract") if quality: counts = quality.get("counts") or {} if counts.get("warning"): diff --git a/queryforge/orchestration/planner/plan.py b/queryforge/orchestration/planner/plan.py index 9439e67..23c5406 100644 --- a/queryforge/orchestration/planner/plan.py +++ b/queryforge/orchestration/planner/plan.py @@ -89,6 +89,8 @@ "filters": {"type": "array", "items": {"type": "object"}}, "time_range": _STRING, "time_grain": _STRING, + "comparison_baseline": _STRING, + "result_role": {"type": "string", "enum": ["metric_value", "metric_totals"]}, "limit": {"type": "integer", "minimum": 1, "maximum": 1000}, "sql": _STRING, "fallback_sql": _STRING, @@ -100,17 +102,25 @@ "properties": { "require_evidence": _STRING_LIST, "require_outputs": _STRING_LIST, + "require_request": {"type": "object"}, }, "additionalProperties": False, }, - "compare_periods": {"type": "object", "properties": {}, "additionalProperties": False}, + "compare_periods": { + "type": "object", "properties": { + "comparison_baseline": _STRING, "time_grain": _STRING, + "dataset_kind": {"type": "string", "enum": ["metric_value", "metric_totals"]}, + }, "additionalProperties": False, + }, "drill_down": {"type": "object", "properties": {}, "additionalProperties": False}, "calculate_contribution": { "type": "object", "properties": {}, "additionalProperties": False, }, - "detect_anomaly": {"type": "object", "properties": {}, "additionalProperties": False}, + "detect_anomaly": {"type": "object", "properties": { + "dataset_kind": {"type": "string", "enum": ["metric_value", "metric_totals"]}, + }, "additionalProperties": False}, "render_chart": {"type": "object", "properties": {}, "additionalProperties": False}, } @@ -250,7 +260,7 @@ def _check_actions( continue tool = ACTION_TOOL_MAP[step.action] try: - if tool == step.action: + if tool == step.action and "dataset_kind" not in step.inputs: # The action's inputs are the registered tool's own contract, # so the registry's validator is used verbatim. registry.validate_params(tool, step.inputs) @@ -337,7 +347,11 @@ def param_schema(action: str, registry: ToolRegistry) -> dict[str, Any]: tool = ACTION_TOOL_MAP.get(action) if tool is not None and tool == action and registry.has(tool): - return registry.resolve(tool).parameter_schema + schema = dict(registry.resolve(tool).parameter_schema) + if action in {"compare_periods", "detect_anomaly"}: + schema["properties"] = {**schema.get("properties", {}), + "dataset_kind": ACTION_PARAM_SCHEMAS[action]["properties"]["dataset_kind"]} + return schema return ACTION_PARAM_SCHEMAS.get(action, {"type": "object", "properties": {}}) diff --git a/queryforge/orchestration/tools/registry.py b/queryforge/orchestration/tools/registry.py index 018770d..3bf457e 100644 --- a/queryforge/orchestration/tools/registry.py +++ b/queryforge/orchestration/tools/registry.py @@ -1239,6 +1239,13 @@ def _analysis_spec( "current": _NUMBER_OR_NULL, "baseline": _NUMBER_OR_NULL, "label": _STRING_OR_NULL, + "comparison_baseline": { + "type": "string", + }, + "time_grain": { + "type": "string", + "enum": ["daily", "weekly", "monthly", "quarterly", "yearly"], + }, "method": { "type": ["string", "null"], "enum": list(COMPARISON_METHODS), diff --git a/queryforge/workflow/node/execute_sql_node.py b/queryforge/workflow/node/execute_sql_node.py index 2434160..a32aa87 100644 --- a/queryforge/workflow/node/execute_sql_node.py +++ b/queryforge/workflow/node/execute_sql_node.py @@ -6,6 +6,7 @@ from queryforge.workflow.node.base import Node from queryforge.core.schemas.models import Context, NodeResult from queryforge.domain.semantic import SemanticSQLValidator +from queryforge.domain.semantic.request_contract import validate_output_contract from queryforge.workflow.errors import record_error_category from queryforge.infrastructure.tools.database_tool import DatabaseTool @@ -24,6 +25,11 @@ def execute(self, context: Context) -> NodeResult: if context.sql_context is None: return self.failure("No generated SQL is available") context.execution_result = None + projection_error = validate_output_contract(context.task.question, context.sql_context.sql) + if projection_error: + context.task_context["output_contract_error"] = projection_error + record_error_category(context, projection_error) + return self.failure(projection_error) join_contract_error = self._validate_join_contract(context) if join_contract_error: record_error_category(context, join_contract_error) diff --git a/queryforge/workflow/node/gen_sql_node.py b/queryforge/workflow/node/gen_sql_node.py index df5e2f9..30446b5 100644 --- a/queryforge/workflow/node/gen_sql_node.py +++ b/queryforge/workflow/node/gen_sql_node.py @@ -401,6 +401,9 @@ def _build_prompt(context: Context) -> str: User question: {context.task.question} +Honor explicitly requested output column names and their order exactly. Aggregates +must contribute to the final projection; unused CTEs cannot satisfy a metric. + Regeneration feedback from a previous reflection (may be empty): {context.regeneration_feedback} diff --git a/queryforge/workflow/node/parallel_candidates_node.py b/queryforge/workflow/node/parallel_candidates_node.py index 859aa67..e285a23 100644 --- a/queryforge/workflow/node/parallel_candidates_node.py +++ b/queryforge/workflow/node/parallel_candidates_node.py @@ -39,6 +39,7 @@ def __init__( preview_limit: int = 20, preview_timeout_seconds: float = 10, selector_weights: dict[str, float] | None = None, + cancel_check=None, ) -> None: if candidate_count < 2 or candidate_count > self.MAX_CANDIDATES: raise ValueError( @@ -47,15 +48,19 @@ def __init__( self.llm = llm self.database_tool = database_tool self.candidate_count = candidate_count + self.cancel_check = cancel_check self.selector = SQLSelector( database_tool, max_preview=max_preview, preview_limit=preview_limit, timeout_seconds=preview_timeout_seconds, weights=selector_weights, + cancel_check=cancel_check, ) def execute(self, context: Context) -> NodeResult: + if self.cancel_check and self.cancel_check(): + return self.failure("Candidate generation cancelled.") prompt = GenSqlNode._build_prompt(context) candidates: list[dict | None] = [None] * self.candidate_count started = time.monotonic() @@ -68,6 +73,10 @@ def execute(self, context: Context) -> NodeResult: for index in range(self.candidate_count) } for future in as_completed(futures): + if self.cancel_check and self.cancel_check(): + for pending in futures: + pending.cancel() + return self.failure("Candidate generation cancelled.") index = futures[future] try: candidates[index] = future.result() @@ -136,10 +145,13 @@ def _selector_for(self, candidate_total: int) -> SQLSelector: preview_limit=self.selector.preview_limit, timeout_seconds=self.selector.timeout_seconds, weights=self.selector.weights, + cancel_check=self.cancel_check, ) def _generate_candidate(self, prompt: str, index: int) -> dict: started = time.monotonic() + if self.cancel_check and self.cancel_check(): + return self._generation_error(index, RuntimeError("Candidate generation cancelled."), started) try: payload = self.llm.generate_json( prompt diff --git a/queryforge/workflow/node/skill_selection_node.py b/queryforge/workflow/node/skill_selection_node.py index 7906f47..bb03ba1 100644 --- a/queryforge/workflow/node/skill_selection_node.py +++ b/queryforge/workflow/node/skill_selection_node.py @@ -49,11 +49,21 @@ def execute(self, context: Context) -> NodeResult: self.TARGET_NODE, subject_skill_names if subject_skill_names is not None else None, ) - catalog = self.skill_manager.context_for_node(self.TARGET_NODE, []) + eligible = self._eligible_skill_names(context) + catalog = self.skill_manager.context_for_node(self.TARGET_NODE, [], available_names=eligible) context.available_skills_context = catalog.available_skills + if not set(eligible) - set(defaults.loaded_skill_names): + selected = self.skill_manager.context_for_node( + self.TARGET_NODE, list(defaults.loaded_skill_names), available_names=eligible) + self._apply_context(context, selected) + context.skill_selection_mode = "auto" + context.task_context["skill_prefilter"] = {"router_called": False, "eligible": eligible} + context.skill_selection_reason = "No relevant optional skill; enabled defaults loaded without a model call." + return self.success(context.skill_selection_reason) try: + context.task_context["skill_prefilter"] = {"router_called": True, "eligible": eligible} payload = self.llm.generate_json(self._build_selection_prompt(context, catalog.available_skills)) - requested, reason = self._parse_selection(payload) + requested, reason = self._parse_selection(payload, eligible) except Exception as exc: self._apply_context(context, defaults) context.skill_selection_mode = "auto_fallback" @@ -70,7 +80,7 @@ def execute(self, context: Context) -> NodeResult: ) selected_names = self._scope_skill_names(context, selected_names) selected = self.skill_manager.context_for_node( - self.TARGET_NODE, selected_names + self.TARGET_NODE, selected_names, available_names=eligible ) self._apply_context(context, selected) context.skill_selection_mode = "auto" @@ -106,7 +116,16 @@ def _scope_skill_names( allowed_set = set(allowed) return [name for name in names if name in allowed_set] - def _parse_selection(self, payload: dict) -> tuple[list[str], str]: + def _eligible_skill_names(self, context: Context) -> list[str]: + question = " ".join(context.task.question.casefold().split()) + subject_names = self._subject_skill_names(context) + names = [skill.name for skill in self.skill_manager.registry.list_skills() + if skill.applies_to(self.TARGET_NODE) + and (subject_names is not None or skill.metadata.enabled or skill.metadata.selection_keywords is None + or any(keyword in question for keyword in skill.metadata.selection_keywords))] + return self._scope_skill_names(context, names) + + def _parse_selection(self, payload: dict, eligible: list[str] | None = None) -> tuple[list[str], str]: raw_names = payload.get("skills") if not isinstance(raw_names, list) or not all( isinstance(name, str) for name in raw_names @@ -117,6 +136,8 @@ def _parse_selection(self, payload: dict) -> tuple[list[str], str]: for skill in self.skill_manager.registry.list_skills() if skill.applies_to(self.TARGET_NODE) } + if eligible is not None: + available_names &= set(eligible) selected = [] for name in raw_names: normalized = name.strip() diff --git a/queryforge/workflow/report_generator.py b/queryforge/workflow/report_generator.py index 6237d80..f46a0fa 100644 --- a/queryforge/workflow/report_generator.py +++ b/queryforge/workflow/report_generator.py @@ -130,8 +130,8 @@ def generate( *self._evidence_sections(store, answer, completeness), ] self.output_dir.mkdir(parents=True, exist_ok=True) - report_path = self.output_dir / f"{context.run_id}.html" - manifest_path = self.output_dir / f"{context.run_id}.manifest.json" + from queryforge.infrastructure.storage.report_store import ReportStore + report_path, manifest_path = ReportStore(self.output_dir).paths(context.run_id) artifact = ReportArtifact( title=context.task.question, summary=summary, diff --git a/queryforge/workflow/sql_selector.py b/queryforge/workflow/sql_selector.py index 3adacc5..32f96a0 100644 --- a/queryforge/workflow/sql_selector.py +++ b/queryforge/workflow/sql_selector.py @@ -8,6 +8,7 @@ from queryforge.core.schemas.models import Context, SQLContext from queryforge.domain.semantic import SemanticSQLValidator, normalize_sql_signature +from queryforge.domain.semantic.request_contract import validate_output_contract from queryforge.infrastructure.tools.database_tool import DatabaseTool, UnsafeSQLError @@ -45,12 +46,14 @@ def __init__( preview_limit: int = 20, timeout_seconds: float = 10, weights: dict[str, float] | None = None, + cancel_check=None, ) -> None: self.database_tool = database_tool self.max_preview = min(max(max_preview, 1), self.MAX_PREVIEW) self.preview_limit = min(max(preview_limit, 1), 100) self.timeout_seconds = max(timeout_seconds, 0.001) self.weights = {**self.DEFAULT_WEIGHTS, **(weights or {})} + self.cancel_check = cancel_check def select( self, @@ -60,7 +63,12 @@ def select( started = time.monotonic() evaluations: list[dict[str, Any]] = [] seen_signatures: dict[str, int] = {} + preview_count = 0 for index, candidate in enumerate(candidates): + if self.cancel_check and self.cancel_check(): + return {"selected_index": None, "selected_sql": None, + "reason": "Candidate selection cancelled.", "evaluations": evaluations, + "preview_status": "cancelled"} sql = candidate.get("sql") signature = ( normalize_sql_signature(sql) @@ -86,7 +94,7 @@ def select( continue if signature: seen_signatures.setdefault(signature, index) - if index >= self.max_preview or time.monotonic() - started >= self.timeout_seconds: + if preview_count >= self.max_preview or time.monotonic() - started >= self.timeout_seconds: evaluations.append( { "candidate_index": index, @@ -98,8 +106,14 @@ def select( } ) continue - evaluations.append(self._evaluate(index, candidate, context)) + evaluation = self._evaluate(index, candidate, context) + preview_count += int(evaluation.get("preview_attempted", False)) + evaluations.append(evaluation) + if self.cancel_check and self.cancel_check(): + return {"selected_index": None, "selected_sql": None, + "reason": "Candidate selection cancelled.", "evaluations": evaluations, + "preview_status": "cancelled"} eligible = [ evaluation for evaluation in evaluations if evaluation.get("status") == "eligible" @@ -147,6 +161,10 @@ def _evaluate( } try: clean_sql = DatabaseTool.validate_readonly_sql(str(sql)) + projection_error = validate_output_contract(context.task.question, clean_sql) + if projection_error: + evaluation["rejection_reason"] = projection_error + return evaluation evaluation["ast_valid"] = True decision = self.database_tool.policy_engine.evaluate(clean_sql) evaluation["governance_allowed"] = decision.allowed @@ -163,6 +181,10 @@ def _evaluate( if validation is not None and validation.status == "violation": evaluation["rejection_reason"] = validation.error_message() return evaluation + if self.cancel_check and self.cancel_check(): + evaluation["rejection_reason"] = "Candidate selection cancelled." + return evaluation + evaluation["preview_attempted"] = True preview = self.database_tool.execute_sql_preview( clean_sql, self.preview_limit, diff --git a/queryforge/workflow/workflow_runner.py b/queryforge/workflow/workflow_runner.py index cafbafc..c3bbdd2 100644 --- a/queryforge/workflow/workflow_runner.py +++ b/queryforge/workflow/workflow_runner.py @@ -670,6 +670,7 @@ def _run_inner(self, task: SqlTask, run_id: str) -> tuple[dict, Context]: preview_limit=self.parallel_preview_limit, preview_timeout_seconds=self.parallel_preview_timeout_seconds, selector_weights=self.selector_weights, + cancel_check=self.cancel_check, ) if self.parallel_candidates > 1 else None diff --git a/sample_data/anime_streaming/README.md b/sample_data/anime_streaming/README.md index b53b288..99e57c0 100644 --- a/sample_data/anime_streaming/README.md +++ b/sample_data/anime_streaming/README.md @@ -21,6 +21,25 @@ The model demonstrates many-to-one relationships, a many-to-many bridge, self-referencing sequel and referral relationships, optional foreign keys, two role-playing user relationships, and governed multi-hop Join Paths. +`watch_hours`, `completion_rate`, `unique_viewers`, and `average_rating` also declare +units, additivity, event-time roles and enforced complete ingestion coverage for the +synthetic 2023–2025 dataset. Completion rate and average rating expose aggregate ratio +components. Multi-fact analysis aggregates each population separately; an analysis of +watch hours and average rating may use a shared month grain without joining playback +and rating detail rows. These sample coverage guarantees do not describe a live feed. + +Verified on 2026-10-10 with Python 3.12.11, SQLite 3.50.4, SQLGlot 28.10.1 and +Pydantic 2.13.4: + +| Independent monthly oracle | 2024-02 | 2025-02 | +| --- | ---: | ---: | +| watch_hours | 1115.8683333333333 | 1117.3080555555555 | +| average_rating | 7.38747680890538 | 7.261959957850369 | + +Reproduce the comparison and its independent SQL checks with +`LOG_LEVEL=CRITICAL .venv/bin/python -B -m unittest tests.test_analysis_semantics.AnalysisSemanticsTest.test_bundled_cross_fact_comparison_matches_independent_sql -q`. +This checks the deterministic analysis pipeline; it does not measure a model's capability. + ## Files - `anime_streaming.sqlite` — ready-to-query database; diff --git a/sample_data/anime_streaming/semantic_baseline.json b/sample_data/anime_streaming/semantic_baseline.json index 9f755e4..92a644f 100644 --- a/sample_data/anime_streaming/semantic_baseline.json +++ b/sample_data/anime_streaming/semantic_baseline.json @@ -3,7 +3,7 @@ "database": "sample_data/anime_streaming/anime_streaming.sqlite", "semantic_model": "sample_data/anime_streaming/semantic_model.yml", "model_name": "anime_streaming", - "fingerprint": "f8920a826149de8dcfb7376e45d4ff70b378609db7c109d88de69f3b9c5dbb50", + "fingerprint": "b439e27c06b3f6b0cbebe467f467c1ad0bf57159c5ebf1c590ed90cc4a704041", "sections": { "schema": [ { @@ -2382,7 +2382,7 @@ "description": "Mean user rating score on a one-to-ten scale.", "entity": "rating", "aggregation": "ratio", - "expression": "CAST(SUM(fact_rating.score) AS REAL) / NULLIF(COUNT(*), 0)", + "expression": "CAST(SUM(fact_rating.score) AS REAL) * 1.0 / NULLIF(COUNT(*), 0)", "synonyms": [ "average rating", "mean score", @@ -2397,7 +2397,25 @@ "calendar.year", "calendar.month" ], - "time_field": "fact_rating.rating_date_key" + "time_field": "fact_rating.rating_date_key", + "ratio": { + "numerator": "SUM(fact_rating.score)", + "denominator": "COUNT(*)", + "scale": 1.0 + }, + "analysis": { + "unit": "score_1_to_10", + "additivity": "non_additive", + "non_additive_dimensions": [], + "time": { + "role": "rating_event", + "timezone": "UTC", + "fiscal_year_start_month": 1, + "coverage_start": "2023-01-01", + "complete_through": "2025-12-31", + "require_complete_periods": true + } + } }, { "contract_version": "1.0", @@ -2431,7 +2449,7 @@ "description": "Completed playback sessions divided by all playback sessions.", "entity": "watch_session", "aggregation": "ratio", - "expression": "CAST(SUM(fact_watch_session.completed_flag) AS REAL) / NULLIF(COUNT(*), 0)", + "expression": "CAST(SUM(fact_watch_session.completed_flag) AS REAL) * 1.0 / NULLIF(COUNT(*), 0)", "synonyms": [ "completion rate", "completed view rate" @@ -2447,7 +2465,25 @@ "calendar.year", "calendar.month" ], - "time_field": "fact_watch_session.watch_date_key" + "time_field": "fact_watch_session.watch_date_key", + "ratio": { + "numerator": "SUM(fact_watch_session.completed_flag)", + "denominator": "COUNT(*)", + "scale": 1.0 + }, + "analysis": { + "unit": "fraction", + "additivity": "non_additive", + "non_additive_dimensions": [], + "time": { + "role": "watch_event", + "timezone": "UTC", + "fiscal_year_start_month": 1, + "coverage_start": "2023-01-01", + "complete_through": "2025-12-31", + "require_complete_periods": true + } + } }, { "contract_version": "1.0", @@ -2554,7 +2590,20 @@ "calendar.year", "calendar.month" ], - "time_field": "fact_watch_session.watch_date_key" + "time_field": "fact_watch_session.watch_date_key", + "analysis": { + "unit": "users", + "additivity": "non_additive", + "non_additive_dimensions": [], + "time": { + "role": "watch_event", + "timezone": "UTC", + "fiscal_year_start_month": 1, + "coverage_start": "2023-01-01", + "complete_through": "2025-12-31", + "require_complete_periods": true + } + } }, { "contract_version": "1.0", @@ -2589,7 +2638,20 @@ "calendar.year", "calendar.month" ], - "time_field": "fact_watch_session.watch_date_key" + "time_field": "fact_watch_session.watch_date_key", + "analysis": { + "unit": "hours", + "additivity": "additive", + "non_additive_dimensions": [], + "time": { + "role": "watch_event", + "timezone": "UTC", + "fiscal_year_start_month": 1, + "coverage_start": "2023-01-01", + "complete_through": "2025-12-31", + "require_complete_periods": true + } + } } ], "relationships": [ diff --git a/sample_data/anime_streaming/semantic_model.yml b/sample_data/anime_streaming/semantic_model.yml index 55c66d5..acd6cc8 100644 --- a/sample_data/anime_streaming/semantic_model.yml +++ b/sample_data/anime_streaming/semantic_model.yml @@ -1354,6 +1354,15 @@ metrics: - calendar.year - calendar.month time_field: fact_watch_session.watch_date_key + analysis: + unit: hours + additivity: additive + time: + role: watch_event + timezone: UTC + coverage_start: '2023-01-01' + complete_through: '2025-12-31' + require_complete_periods: true - contract_version: '1.0' owner: engagement-analytics sensitivity: internal @@ -1362,7 +1371,6 @@ metrics: description: Completed playback sessions divided by all playback sessions. entity: watch_session aggregation: ratio - expression: CAST(SUM(fact_watch_session.completed_flag) AS REAL) / NULLIF(COUNT(*), 0) synonyms: - completion rate - completed view rate @@ -1377,6 +1385,18 @@ metrics: - calendar.year - calendar.month time_field: fact_watch_session.watch_date_key + analysis: + unit: fraction + additivity: non_additive + time: + role: watch_event + timezone: UTC + coverage_start: '2023-01-01' + complete_through: '2025-12-31' + require_complete_periods: true + ratio: + numerator: SUM(fact_watch_session.completed_flag) + denominator: COUNT(*) - contract_version: '1.0' owner: engagement-analytics sensitivity: internal @@ -1401,6 +1421,15 @@ metrics: - calendar.year - calendar.month time_field: fact_watch_session.watch_date_key + analysis: + unit: users + additivity: non_additive + time: + role: watch_event + timezone: UTC + coverage_start: '2023-01-01' + complete_through: '2025-12-31' + require_complete_periods: true - contract_version: '1.0' owner: engagement-analytics sensitivity: internal @@ -1409,7 +1438,6 @@ metrics: description: Mean user rating score on a one-to-ten scale. entity: rating aggregation: ratio - expression: CAST(SUM(fact_rating.score) AS REAL) / NULLIF(COUNT(*), 0) synonyms: - average rating - mean score @@ -1423,6 +1451,18 @@ metrics: - calendar.year - calendar.month time_field: fact_rating.rating_date_key + analysis: + unit: score_1_to_10 + additivity: non_additive + time: + role: rating_event + timezone: UTC + coverage_start: '2023-01-01' + complete_through: '2025-12-31' + require_complete_periods: true + ratio: + numerator: SUM(fact_rating.score) + denominator: COUNT(*) - contract_version: '1.0' owner: monetization-analytics sensitivity: confidential diff --git a/scripts/audit_paired_benchmark.py b/scripts/audit_paired_benchmark.py new file mode 100644 index 0000000..9284902 --- /dev/null +++ b/scripts/audit_paired_benchmark.py @@ -0,0 +1,258 @@ +"""Recompute paired verdicts, source contracts and measured usage without model calls.""" +from __future__ import annotations + +import argparse +from collections import Counter, defaultdict +from datetime import datetime +import hashlib +from importlib.metadata import version +import json +import math +from pathlib import Path +import platform +import sqlite3 +import sys + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +from queryforge.evaluation import TaskTrace, evaluate_task, load_spec_splits +from queryforge.evaluation.paired import summarize_pairs + + +def digest_json(value): + return hashlib.sha256(json.dumps(value, sort_keys=True).encode()).hexdigest() + + +def case_key(record): + return record['task_id'], record['repeat'], record['arm'] + + +def reconcile_usage(calls, trace, record): + """Reconcile reported responses; an estimated failed call stays unknown.""" + reported = sum(c['total_tokens'] for c in calls) + if not (trace.usage or {}).get('estimated'): + if reported != (record.get('measured_tokens') or 0): + raise ValueError(f'provider/trace token mismatch: {case_key(record)}') + return reported, 0 + spans = [s for s in trace.model_dump().get('model_spans', []) if s.get('kind') == 'model'] + if not spans or len(spans) != trace.usage.get('model_calls'): + raise ValueError('mixed usage requires complete model spans') + known, unknown = [], 0 + for span in spans: + usage = span.get('usage') + if not usage or usage.get('estimated'): + unknown += 1 + continue + fields = ('prompt_tokens', 'completion_tokens', 'total_tokens') + if any(type(usage.get(key)) is not int or usage[key] < 0 for key in fields): + raise ValueError('mixed usage has malformed reported span') + if usage['total_tokens'] != usage['prompt_tokens'] + usage['completion_tokens']: + raise ValueError('mixed usage reported span totals differ') + known.append(tuple(usage[key] for key in fields)) + observed = Counter((c.get('prompt_tokens'), c.get('completion_tokens'), c['total_tokens']) for c in calls) + if observed != Counter(known) or len(known) != trace.usage.get('measured_calls'): + raise ValueError(f'provider/trace token mismatch: {case_key(record)}') + return reported, unknown + + +def priced_cost(calls, trace, prices): + if prices is None: + return None + if not calls: + return 0.0 if trace.usage and trace.usage.get('model_calls') == 0 else None + total = 0.0 + for call in calls: + fields = ('prompt_tokens', 'completion_tokens', 'total_tokens', + 'prompt_cache_hit_tokens', 'prompt_cache_miss_tokens') + if any(type(call.get(key)) is not int or call[key] < 0 for key in fields): + return None + if (call['prompt_tokens'] != call['prompt_cache_hit_tokens'] + call['prompt_cache_miss_tokens'] + or call['total_tokens'] != call['prompt_tokens'] + call['completion_tokens']): + return None + if call.get('provider') != prices['provider'] or call.get('model') != prices['model']: + raise ValueError('price provider/model mismatch') + measured_at = datetime.fromisoformat(call['at_utc']) + if not (datetime.fromisoformat(prices['valid_from_utc']) <= measured_at + < datetime.fromisoformat(prices['valid_until_utc'])): + raise ValueError('provider usage falls outside the frozen price window') + total += (call['prompt_cache_hit_tokens'] * prices['input_cache_hit_per_million'] + + call['prompt_cache_miss_tokens'] * prices['input_cache_miss_per_million'] + + call['completion_tokens'] * prices['output_per_million']) / 1_000_000 + return total + + +def validate_prices(prices): + if prices is None: + return + if not prices.get('version') or prices.get('currency') != 'CNY': + raise ValueError('prices require a version and CNY currency') + for key in ('input_cache_hit_per_million', 'input_cache_miss_per_million', 'output_per_million'): + rate = prices.get(key) + if isinstance(rate, bool) or not isinstance(rate, (int, float)) or not math.isfinite(rate) or rate < 0: + raise ValueError('price rates must be finite non-negative numbers') + start, end = (datetime.fromisoformat(prices[key]) for key in ('valid_from_utc', 'valid_until_utc')) + if start.tzinfo is None or end.tzinfo is None or end <= start: + raise ValueError('price window must be ordered and timezone-aware') + + +def audit_report(report, reference_specs, scoring_specs, usage, *, prices=None, excluded_tasks=None): + """Preserve prespecified results and separately score an opt-in source contract.""" + validate_prices(prices) + if not report.get('summary', {}).get('complete'): + raise ValueError('audit requires a completed original experiment') + manifest = report['manifest'] + if not report['summary'].get('provenance_stable'): + raise ValueError('original execution provenance was not stable') + schedule = manifest['schedule'] + expected = {(item['task_id'], item['repeat'], arm) + for item in schedule for arm in item['order']} + records = report['records'] + if len(expected) != manifest['case_executions'] or len(records) != len(expected): + raise ValueError('manifest/record count mismatch') + if len({case_key(r) for r in records}) != len(records) or {case_key(r) for r in records} != expected: + raise ValueError('manifest cases missing or duplicated') + task_ids = list(dict.fromkeys(item['task_id'] for item in schedule)) + excluded_tasks = dict(excluded_tasks or {}) + if not excluded_tasks.keys() <= set(task_ids) or any(not isinstance(reason, str) or not reason.strip() + for reason in excluded_tasks.values()): + raise ValueError('sensitivity exclusions require known task ids and explicit reasons') + if set(task_ids) <= excluded_tasks.keys(): + raise ValueError('sensitivity analysis excludes all tasks') + reference = {s.task_id: s for s in reference_specs} + scoring = {s.task_id: s for s in scoring_specs} + if not set(task_ids) <= reference.keys() or not set(task_ids) <= scoring.keys(): + raise ValueError('missing reference or scoring task') + gold = [reference[task_id].model_dump() for task_id in task_ids] + # The source field did not exist in the preserved live-v1 execution model. + legacy_gold = [{k: v for k, v in item.items() if k != 'required_sql_tables'} for item in gold] + if manifest['provenance']['gold_sha256'] not in {digest_json(gold), digest_json(legacy_gold)}: + raise ValueError('reference tasks differ from original execution gold') + for task_id in task_ids: + old, new = reference[task_id], scoring[task_id] + permitted = {'required_sql_tables', 'template_id', 'notes'} + if old.model_dump(exclude=permitted) != new.model_dump(exclude=permitted): + raise ValueError(f'scoring changed model input or result contract: {task_id}') + if not new.required_sql_tables: + raise ValueError(f'scoring task has no declared source contract: {task_id}') + by_case = defaultdict(list) + for call in usage: + key = case_key(call) + if key not in expected: + raise ValueError('provider response has no original case') + if call.get('provider') != manifest['provider'] or call.get('model') != manifest['model']: + raise ValueError('provider response does not match the experiment') + by_case[key].append(call) + audited, priced, source_failures, newly_rejected, unknown_usage_cases = [], [], [], [], [] + reported_costs = [] + for record in records: + key = case_key(record) + trace = TaskTrace.model_validate(record['raw_trace']) + original = evaluate_task(reference[record['task_id']], trace, price_table=manifest.get('price_table')) + if original.passed != record['passed'] or [c.model_dump() for c in original.checks] != record['checks']: + raise ValueError(f'original verdict cannot be reproduced: {key}') + calls = by_case[key] + if any(type(c.get('total_tokens')) is not int or c['total_tokens'] < 0 for c in calls): + raise ValueError(f'provider usage is not measurable: {key}') + reported_tokens, unknown_calls = reconcile_usage(calls, trace, record) + fresh = evaluate_task(scoring[record['task_id']], trace, price_table=manifest.get('price_table')) + result = dict(record, **fresh.model_dump(), original_passed=record['passed'], + original_failure_class=record.get('failure_class')) + reported_cost = priced_cost(calls, trace, prices) + reported_costs.append(reported_cost) + cost = None if unknown_calls else reported_cost + result['cost_cny'] = cost + result['reported_response_tokens'] = reported_tokens + result['reported_response_cost_cny'] = reported_cost + result['unknown_usage_calls'] = unknown_calls + if unknown_calls: + unknown_usage_cases.append({'case': list(key), 'reported_response_tokens': reported_tokens, + 'unknown_calls': unknown_calls, + 'note': 'Failed/estimated calls have no provider usage. Reported responses reconcile; total case cost remains unknown.'}) + audited.append(result) + # summarize_pairs uses one generic cost slot; expose the result as CNY. + priced.append(dict(result, cost_usd=cost, cost_basis='priced' if cost is not None else None)) + check = fresh.check('sql_sources') + if check is not None and not check.passed: + source_failures.append({'case': list(key), 'original_passed': record['passed'], + 'source_check': check.model_dump()}) + if record['passed'] and not fresh.passed: + newly_rejected.append(list(key)) + summary = summarize_pairs(audited, repeats=manifest['repeats'], seed=manifest['seed']) + summary['execution_provenance_stable'] = True + sensitivity = ([r for r in audited if r['task_id'] not in excluded_tasks] if excluded_tasks else None) + sensitivity_summary = (summarize_pairs(sensitivity, repeats=manifest['repeats'], seed=manifest['seed']) + if sensitivity is not None else None) + return {'benchmark': 'post_hoc_source_contract_audit', 'manifest': manifest, + 'execution_final_provenance': report['final_provenance'], + 'execution_observer': report.get('execution_observer'), + 'original_summary': report['summary'], 'summary': summary, 'records': audited, + 'sensitivity_summary': sensitivity_summary, + 'audit': {'new_model_calls': 0, 'verdicts_recomputed': len(records), + 'verdict_mismatches': [], 'token_mismatches': [], + 'provider_responses': len(usage), 'price': prices, + 'priced_executions': sum(r['cost_cny'] is not None for r in audited), + 'estimated_cost_cny': sum(r['cost_cny'] for r in audited) if all(r['cost_cny'] is not None for r in audited) else None, + 'reported_response_tokens': sum(r['reported_response_tokens'] for r in audited), + 'reported_response_cost_cny': sum(reported_costs) if all(c is not None for c in reported_costs) else None, + 'unknown_usage_cases': unknown_usage_cases, + 'cost_cny': summarize_pairs(priced, repeats=manifest['repeats'], seed=manifest['seed'])['cost_usd'], + 'sensitivity_cost_cny': (summarize_pairs([r for r in priced if r['task_id'] not in excluded_tasks], + repeats=manifest['repeats'], seed=manifest['seed'])['cost_usd'] + if excluded_tasks else None), + 'source_failures': source_failures, 'newly_rejected_cases': newly_rejected}, + 'scoring_policy': {'kind': 'post_hoc', 'required_sql_tables': True, + 'sensitivity_excluded_tasks': excluded_tasks, + 'note': 'Added after inspecting live-v1 traces. Necessary source coverage, not proof of full SQL semantics; original verdicts are preserved.'}} + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('input_report', type=Path) + parser.add_argument('--reference-tasks-dir', type=Path, required=True) + parser.add_argument('--tasks-dir', type=Path, required=True) + parser.add_argument('--usage', type=Path, required=True) + parser.add_argument('--prices', type=Path) + parser.add_argument('--exclude-task', action='append', default=[], help='Separate post-hoc sensitivity analysis; primary results retain every task') + parser.add_argument('--exclusion-reason', help='Required rationale for sensitivity exclusions') + parser.add_argument('--report', type=Path, required=True) + args = parser.parse_args(argv) + if args.exclude_task and not args.exclusion_reason: + parser.error('--exclude-task requires --exclusion-reason') + if args.report.exists(): + parser.error('output report already exists; original evidence must not be overwritten') + try: + original = json.loads(args.input_report.read_text()) + usage = [json.loads(line) for line in args.usage.read_text().splitlines() if line.strip()] + prices = json.loads(args.prices.read_text()) if args.prices else None + report = audit_report(original, load_spec_splits(args.reference_tasks_dir), + load_spec_splits(args.tasks_dir), usage, prices=prices, + excluded_tasks={task: args.exclusion_reason for task in args.exclude_task}) + def digest(path): + return hashlib.sha256(path.read_bytes()).hexdigest() + evaluator_files = sorted((ROOT / 'queryforge/evaluation').glob('*.py')) + report['scoring_provenance'] = { + 'input_report': str(args.input_report.resolve()), + 'input_report_sha256': digest(args.input_report), 'usage_sha256': digest(args.usage), + 'price_sha256': digest(args.prices) if args.prices else None, + 'script_sha256': digest(Path(__file__)), + 'evaluator_sha256': digest_json({p.name: digest(p) for p in evaluator_files}), + 'gold_sha256': digest_json([s.model_dump() for s in load_spec_splits(args.tasks_dir)]), + 'tasks_dir': str(args.tasks_dir.resolve()), + 'versions': {'python': platform.python_version(), 'sqlite': sqlite3.sqlite_version, + 'sqlglot': version('sqlglot'), 'pydantic': version('pydantic')}} + args.report.parent.mkdir(parents=True, exist_ok=True) + with args.report.open('x') as target: + json.dump(report, target, ensure_ascii=False, indent=2) + target.write('\n') + print(json.dumps({'report': str(args.report), 'executions': len(report['records']), + 'summary': report['summary'], 'newly_rejected_cases': len(report['audit']['newly_rejected_cases']), + 'sensitivity_summary': report['sensitivity_summary'], + 'new_model_calls': 0}, ensure_ascii=False)) + return 0 + except (ValueError, TypeError, KeyError, OSError) as exc: + print(f'audit failed: {exc}', file=sys.stderr) + return 1 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/scripts/benchmark_agent.py b/scripts/benchmark_agent.py index c6865cd..a7e93f4 100644 --- a/scripts/benchmark_agent.py +++ b/scripts/benchmark_agent.py @@ -85,6 +85,9 @@ def parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace: ) parser.add_argument("--retrieval-corpus", action="append", default=[], help="JSONL knowledge corpus to audit for holdout contamination") parser.add_argument("--repeat", type=int, default=1, help="Repetitions per task") + parser.add_argument("--parallel-candidates", type=int, choices=(1, 2, 3), default=None, + help="Force the same candidate count for every workflow task") + parser.add_argument("--skill-mode", choices=("auto", "off"), default="auto") parser.add_argument("--provider", default=None, help="Tier 3 model provider") parser.add_argument("--model", default=None, help="Tier 3 model name") parser.add_argument("--limit", type=int, default=0, help="Cap the task count") @@ -121,6 +124,8 @@ class BenchmarkContext: runner: str = "planner" skipped: list[dict[str, str]] = field(default_factory=list) repeats: int = 1 + parallel_candidates: int | None = None + skill_mode: str = "auto" # --------------------------------------------------------------------- helpers @@ -163,6 +168,20 @@ def _tool_calls_from_payload(payload: dict[str, Any]) -> list[dict[str, Any]]: """Derive the tool-call trace from a recorded planner payload.""" from queryforge.orchestration.planner.plan import ACTION_TOOL_MAP + spans = (payload.get("observability") or {}).get("spans") or [] + tool_spans = [span for span in spans if span.get("kind") == "tool"] + if tool_spans: + # A query step can also validate dates and several join grains. Counting + # one call per step hides these governed tool invocations; parallel step + # counters can overlap. The individual spans provide their real identity. + return [{"step_id": span.get("attributes", {}).get("step_id"), + "action": span.get("attributes", {}).get("action"), + "tool": span.get("attributes", {}).get("tool"), + "ok": span.get("attributes", {}).get("tool_status") == "succeeded", + "status": span.get("attributes", {}).get("tool_status"), + "duration_ms": span.get("duration_ms"), + "error_category": span.get("attributes", {}).get("error_category")} + for span in tool_spans] calls: list[dict[str, Any]] = [] for step in payload.get("steps") or []: if not isinstance(step, dict): @@ -246,6 +265,8 @@ def run_analysis_task( "cost_usd": _cost_usd(usage, context.prices), "provider": context.provider, "model": context.model, + "controls": {"parallel_candidates": context.parallel_candidates, "skill_mode": context.skill_mode, + "history_top_k": 0, "vector_kb": False, "today": "2024-12-31"}, "runner": context.runner, "error": error, } @@ -436,6 +457,10 @@ def digest(path): return hashlib.sha256(Path(path).read_bytes()).hexdigest() sources = sorted([*PROJECT_ROOT.glob("queryforge/**/*.py"), *PROJECT_ROOT.glob("scripts/*.py"), PROJECT_ROOT/"pyproject.toml"]) source_digest = hashlib.sha256("\n".join(f"{p.relative_to(PROJECT_ROOT)}:{digest(p)}" for p in sources).encode()).hexdigest() + assets = sorted([PROJECT_ROOT / "models.yml", PROJECT_ROOT / "queryforge/core/default_models.yml", + *(p for p in (PROJECT_ROOT / "queryforge/bundled_skills").rglob("*") + if p.is_file() and p.suffix in {".md", ".yml", ".yaml", ".json", ".py"})]) + asset_digest = hashlib.sha256("\n".join(f"{p.relative_to(PROJECT_ROOT)}:{digest(p)}" for p in assets).encode()).hexdigest() by_task = {} for o in outcomes: by_task.setdefault(o.task_id, []).append(o.passed) @@ -457,6 +482,8 @@ def digest(path): "runner": context.runner, "provider": context.provider, "model": context.model, + "controls": {"parallel_candidates": context.parallel_candidates, "skill_mode": context.skill_mode, + "history_top_k": 0, "vector_kb": False, "today": "2024-12-31"}, "repeats": repeats, "ablations": list(ablations), "state_root": str(context.state_root), @@ -466,7 +493,10 @@ def digest(path): "thresholds": thresholds.get(_tier_key(tier)) or {}, "price_table": context.prices, "provenance": {"source_sha256": source_digest, + "assets_sha256": asset_digest, "datasets_sha256": {k: digest(_project_path(v["database"])) for k,v in context.datasets.items()}, + "contracts_sha256": {k: {f: digest(_project_path(v[f])) for f in ("semantic_model", "sql_policy")} + for k,v in context.datasets.items()}, "gold_sha256": hashlib.sha256(json.dumps([s.model_dump() for s in specs],sort_keys=True).encode()).hexdigest(), "threshold_sha256": hashlib.sha256(json.dumps(thresholds,sort_keys=True).encode()).hexdigest(), "git_head": subprocess.run(["git","rev-parse","HEAD"],cwd=PROJECT_ROOT,capture_output=True,text=True).stdout.strip(), @@ -497,6 +527,7 @@ def ablation_sweep( provider=context.provider, model=context.model, runner=context.runner, repeats=context.repeats, + parallel_candidates=context.parallel_candidates, skill_mode=context.skill_mode, ) baseline_outcomes, _ = run_suite(specs, baseline_context, tier=1) baseline_metrics = aggregate(baseline_outcomes, thresholds={}) @@ -519,6 +550,7 @@ def ablation_sweep( provider=context.provider, model=context.model, runner=context.runner, repeats=context.repeats, + parallel_candidates=context.parallel_candidates, skill_mode=context.skill_mode, ablations=frozenset({feature}), ) outcomes, _ = run_suite(specs, ablated, tier=1) @@ -720,8 +752,9 @@ def main(argv: Sequence[str] | None = None) -> int: from queryforge.evaluation import load_spec_splits all_specs = load_spec_splits(_project_path(args.tasks_dir)) - from queryforge.evaluation.isolation import audit_splits, audit_corpus + from queryforge.evaluation.isolation import audit_splits, audit_corpus, audit_dataset_schemas audit_splits(all_specs) + audit_dataset_schemas(all_specs, datasets, PROJECT_ROOT) for corpus in args.retrieval_corpus: audit_corpus(all_specs, _project_path(corpus)) specs = select_specs( @@ -746,6 +779,7 @@ def main(argv: Sequence[str] | None = None) -> int: repeats=args.repeat, provider=args.provider, model=args.model, + parallel_candidates=args.parallel_candidates, skill_mode=args.skill_mode, ) outcomes, traces = run_suite(specs, context, tier=args.tier) report = build_report( diff --git a/scripts/benchmark_runners.py b/scripts/benchmark_runners.py index f155b97..bfa5cf7 100644 --- a/scripts/benchmark_runners.py +++ b/scripts/benchmark_runners.py @@ -3,6 +3,7 @@ from dataclasses import replace from datetime import date +from functools import partial from pathlib import Path import time from uuid import uuid4 @@ -40,7 +41,9 @@ def run_workflow_task(spec, dataset: dict, context) -> dict: semantic_model_path=dataset["semantic_model"], sql_policy_path=dataset["sql_policy"], today_provider=lambda: date(2024, 12, 31), show_run_summary=True, max_retries=0 if "fix_loop" in context.ablations else 2, - parallel_candidates=1 if "multi_candidate" in context.ablations else 2 if context.provider else 1) + parallel_candidates=1 if "multi_candidate" in context.ablations else + context.parallel_candidates if context.parallel_candidates is not None else 2 if context.provider else 1, + selected_skills=[] if context.skill_mode == "off" else None) if not context.provider: kwargs["llm_factory"] = lambda _: ScriptedModel(spec.reference_sql) started = time.perf_counter() @@ -53,8 +56,12 @@ def run_workflow_task(spec, dataset: dict, context) -> dict: from queryforge.application import AgentService, AgentOptions options = AgentOptions(database=dataset["database"], semantic_model_path=dataset["semantic_model"], sql_policy_path=dataset["sql_policy"], session_id="eval-session", complexity_mode="simple", - history_top_k=0, show_run_summary=True, orchestration_state_root=str(context.state_root/'runs')) - service_kwargs = {"config_loader": lambda **_: config} + history_top_k=0, show_run_summary=True, orchestration_state_root=str(context.state_root/'runs'), + enable_vector_kb=False, vector_top_k=0, max_retries=kwargs["max_retries"], + parallel_candidates=kwargs["parallel_candidates"], + skills=kwargs["selected_skills"]) + service_kwargs = {"config_loader": lambda **_: config, + "runner_factory": partial(WorkflowRunner, today_provider=kwargs["today_provider"])} if not context.provider: service_kwargs["llm_factory"] = lambda _: ScriptedModel(spec.reference_sql) service = AgentService(**service_kwargs) diff --git a/scripts/check_local_studio.py b/scripts/check_local_studio.py new file mode 100644 index 0000000..bbdc93f --- /dev/null +++ b/scripts/check_local_studio.py @@ -0,0 +1,197 @@ +"""Exercise production Studio routes against an explicitly offline local fixture. + +Start tests.studio_fixture_server and Studio with isolated STUDIO_STATE_DIR first. +This script refuses a real provider backend, even when credentials are configured. +""" +from __future__ import annotations + +import argparse +import hashlib +import json +import os +from io import BytesIO +import time +import uuid +from pathlib import Path +from urllib.error import HTTPError +from urllib.parse import urlencode, urlsplit +from urllib.request import Request, ProxyHandler, build_opener + + +CSV = (Path(__file__).resolve().parents[1] / "tests/fixtures/studio_records.csv").read_bytes() +CONTRACT = { + "version": 1, "entity": "uploaded_record", "description": "Disposable offline records", + "owner": "Local acceptance", "grain": "record_id", "primaryKey": "record_id", + "sensitivity": "internal", "dimensions": ["record_id", "entity_id", "recorded_at"], + "metrics": [ + {"name": "uploaded_record_count", "description": "Number of records", "aggregation": "count", "expression": "COUNT(DISTINCT uploaded_record.record_id)"}, + {"name": "uploaded_amount_sum", "description": "Total amount", "aggregation": "sum", "expression": "SUM(uploaded_record.amount)"}, + ], +} + + +class StudioCheck: + def __init__(self, base: str): + parsed = urlsplit(base) + if parsed.scheme != "http" or parsed.hostname not in {"localhost", "127.0.0.1", "::1"} or parsed.username: + raise ValueError("Acceptance must use a loopback HTTP address.") + self.base = base.rstrip("/") + self.opener = build_opener(ProxyHandler({})) + self.checks: list[str] = [] + + def request(self, path, payload=None, *, headers=None, expected=200, raw=None): + body = raw if raw is not None else json.dumps(payload).encode() if payload is not None else None + request_headers = {"content-type": "application/json"} if payload is not None else {} + request_headers.update(headers or {}) + request = Request(self.base + path, data=body, headers=request_headers) + try: + response = self.opener.open(request, timeout=45) + except HTTPError as error: + response = error + with response: + raw_response = response.read() + try: + data = json.loads(raw_response) + except json.JSONDecodeError: + data = {"detail": raw_response.decode(errors="replace")[:500]} + assert response.status == expected, (path, response.status, data) + return data + + def check(self, name, condition): + assert condition, name + self.checks.append(name) + + def events(self, options, *, disconnect=False): + request = Request(self.base + "/api/queryforge/ask/stream", data=json.dumps(options).encode(), + headers={"content-type": "application/json"}) + events = [] + with self.opener.open(request, timeout=35) as response: + assert response.headers.get("x-queryforge-event-protocol") == "1" + for line in response: + if not line.startswith(b"data: "): + continue + event = json.loads(line[6:]) + events.append(event) + if disconnect and event["event_type"] == "node_started" and event["node_name"] == "gen_sql": + break + return events + + def upload(self, domain, *, reviewed=True, csv=CSV, filename="records.csv", expected=201): + boundary = "queryforge-" + uuid.uuid4().hex + fields = {"domain_id": domain, "reviewed": str(reviewed).lower(), "reviewed_by": "local-acceptance", "semantic_contract": json.dumps(CONTRACT)} + parts = [] + for key, value in fields.items(): + parts.append(f'--{boundary}\r\nContent-Disposition: form-data; name="{key}"\r\n\r\n{value}\r\n'.encode()) + parts.append(f'--{boundary}\r\nContent-Disposition: form-data; name="files"; filename="{filename}"\r\nContent-Type: application/octet-stream\r\n\r\n'.encode() + csv + b"\r\n") + parts.append(f"--{boundary}--\r\n".encode()) + return self.request("/api/studio/upload", raw=b"".join(parts), headers={"content-type": f"multipart/form-data; boundary={boundary}"}, expected=expected) + + def run(self): + health = self.request("/api/queryforge/health") + self.check("explicit_offline_fixture", health.get("offline_fixture") is True) + # Only after this guard is it safe to start a workflow. + domain = self.request("/api/studio/domains", {"name": "Local acceptance " + uuid.uuid4().hex[:8], "description": "Disposable offline acceptance"}, expected=201)["domain"]["id"] + other = self.request("/api/studio/domains", {"name": "Unpublished " + uuid.uuid4().hex[:8]}, expected=201)["domain"]["id"] + self.upload(domain, reviewed=False, expected=400) + self.check("unreviewed_upload_denied", True) + rejected = self.upload(other, csv=CSV.replace(b"record_id,", b"missing_id,"), expected=422) + self.check("invalid_contract_not_published", rejected["source"]["status"] == "publish_failed") + invalid_binary = self.upload(other, csv=b"invalid parquet", filename="invalid.parquet", expected=422) + self.check("invalid_parquet_physically_rejected", invalid_binary["source"]["pythonPublish"]["status"] == "failed") + import pyarrow as pa + import pyarrow.parquet as pq + binary = BytesIO() + pq.write_table(pa.table({"record_id": [1, 2, 3], "entity_id": [11, 12, 13], "recorded_at": ["2024-01-01", "2024-01-02", "2024-01-03"], "amount": [10, 20, 30]}), binary) + parquet_domain = self.request("/api/studio/domains", {"name": "Parquet acceptance " + uuid.uuid4().hex[:8]}, expected=201)["domain"]["id"] + binary_result = self.upload(parquet_domain, csv=binary.getvalue(), filename="records.parquet")["source"] + self.check("parquet_physical_publication", binary_result["status"] == "ready" and binary_result["pythonPublish"]["status"] == "published" and binary_result["semanticModel"]["validation"]["files"][0]["validation_status"] == "not_verified_server_side") + published = self.upload(domain)["source"] + version = published["pythonPublish"]["data_version"] + self.check("physical_publication", published["status"] == "ready" and bool(version)) + domains = self.request("/api/studio/domains")["domains"] + self.check("ready_domain_after_publication", next(item for item in domains if item["id"] == domain)["status"] == "ready") + options = {"domain_id": domain, "complexity_mode": "simple", "report": True} + count = self.request("/api/queryforge/ask", {**options, "question": "How many uploaded records? Return a single column named n."}) + self.check("physical_count_oracle", count["status"] == "success" and count["rows"] == [[3]]) + total = self.request("/api/queryforge/ask", {**options, "question": "What is uploaded_amount_sum? Return only amount."}) + self.check("physical_sum_oracle", total["status"] == "success" and total["rows"] == [[60]]) + self.request("/api/queryforge/ask", {"domain_id": other, "question": "Count rows", "complexity_mode": "simple"}, expected=400) + self.check("unpublished_domain_denied", True) + self.request("/api/queryforge/ask", {**options, "question": "Count rows", "database": "sample_data/anime_streaming/anime_streaming.sqlite"}, expected=400) + self.check("domain_path_override_denied", True) + blocked = self.request("/api/queryforge/ask", {**options, "question": "Delete uploaded records. Return only n."}, expected=422) + self.check("write_sql_denied", "SQL_SECURITY_ERROR" in blocked["detail"] and "query_executed': False" in blocked["detail"]) + count_after = self.request("/api/queryforge/ask", {**options, "question": "How many uploaded records? Return a single column named n."}) + self.check("write_rejection_keeps_data", count_after["rows"] == [[3]]) + execution = count + snapshot = {"runId": count["run_id"], "status": count["status"], "provenance": "live", "mode": "live-request", + "columns": execution["columns"], "rows": execution["rows"], "rowCount": execution["row_count"], + "sql": count["sql"], "explanation": "Offline fixture with real governed execution", "planText": "", "detail": "", "output": count} + saved = {"id": count["run_id"], "domainId": domain, "question": "How many uploaded records? Return a single column named n.", "status": "success", "model": "offline-browser-fixture", "rowCount": 1, "duration": "offline", "snapshot": snapshot, "dataVersion": version} + self.request("/api/studio/runs", saved, expected=201) + calls_before = self.request("/api/queryforge/health")["offline_model_calls"] + replay_path = "/api/studio/runs?" + urlencode({"run_id": count["run_id"], "domain_id": domain}) + replay = self.request(replay_path) + self.check("snapshot_replay", replay["run"] == snapshot and replay["data_version"] == version) + self.check("replay_zero_model_calls", calls_before == self.request("/api/queryforge/health")["offline_model_calls"]) + self.request("/api/studio/runs?" + urlencode({"run_id": count["run_id"], "domain_id": other}), expected=404) + self.request("/api/studio/runs", {**saved, "domainId": other}, expected=409) + self.check("cross_domain_replay_and_id_conflict_denied", True) + self.request("/api/studio/domains", headers={"Origin": "https://untrusted.example"}, expected=403) + self.check("cross_origin_denied", True) + streamed = self.events({**options, "question": "How many uploaded records? Return a single column named n."}) + terminal = [event for event in streamed if event["event_type"] == "final_result"] + self.check("sse_terminal_protocol_and_oracle", len(terminal) == 1 and terminal[0]["outcome"] == "success" and terminal[0]["result"]["rows"] == [[3]]) + self.check("sse_gapless_sequence", [event["sequence"] for event in streamed] == list(range(1, len(streamed) + 1))) + cancelled = self.events({**options, "question": "Slow count of uploaded records. Return a single column named n."}, disconnect=True) + cancelled_id = cancelled[0]["run_id"] + fixture_root = Path("/tmp/queryforge_phase4_fixture/backend") + state_path = fixture_root / "runs" / cancelled_id / "state.json" + deadline = time.monotonic() + 30 + state = {} + while time.monotonic() < deadline: + if state_path.is_file(): + state = json.loads(state_path.read_text()) + if state.get("status") in {"cancelled", "completed", "failed", "blocked"}: + break + time.sleep(0.2) + self.check("sse_disconnect_persisted_cancelled", state.get("status") == "cancelled") + self.check("cancelled_run_has_no_execution_artifact", not any(item.get("artifact_type") == "execution_result" for item in state.get("artifacts", []))) + # Only disposable reports under the explicitly offline fixture are aged. + report_id = "local_expiry_" + uuid.uuid4().hex + report_root = fixture_root / "reports" + report_root.mkdir(parents=True, exist_ok=True) + html = report_root / (report_id + ".html") + manifest = report_root / (report_id + ".manifest.json") + html.write_text("Disposable offline expiry fixture") + manifest.write_text('{"evidence":"preserved"}') + old = time.time() - 31 * 86400 + os.utime(html, (old, old)) + backend = StudioCheck("http://127.0.0.1:8000") + self.check("backend_offline_guard", backend.request("/health").get("offline_fixture") is True) + backend.request("/report/" + report_id, expected=404) + preview = backend.request("/reports/expire", {"dry_run": True}) + self.check("expired_report_denied_dry_run_preserves", report_id in preview["expired"] and html.exists() and manifest.exists()) + cleanup = backend.request("/reports/expire", {"dry_run": False}) + self.check("expired_report_reversibly_quarantined", report_id in cleanup["expired"] and not html.exists() and len(list((report_root / ".expired").glob(report_id + "*/*"))) == 2) + return {"mode": "offline_model_real_studio_and_database", "checks": self.checks, "passed": len(self.checks), + "domain_id": domain, "unpublished_domain_id": other, "run_id": count["run_id"], "data_version": version, + "parquet_domain_id": parquet_domain, + "cancelled_run_id": cancelled_id, "cancelled_state": str(state_path), + "fixture_sha256": hashlib.sha256(CSV).hexdigest(), "oracle": {"count": 3, "sum": 60}, "real_provider_calls": 0} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--studio", default="http://localhost:3000") + parser.add_argument("--report", default="/tmp/queryforge_phase4_studio_acceptance.json") + arguments = parser.parse_args() + started = time.monotonic() + result = StudioCheck(arguments.studio).run() + result["duration_seconds"] = round(time.monotonic() - started, 3) + Path(arguments.report).write_text(json.dumps(result, indent=2) + "\n") + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/scripts/evaluate_sql.py b/scripts/evaluate_sql.py index b3f37d0..1d00f99 100644 --- a/scripts/evaluate_sql.py +++ b/scripts/evaluate_sql.py @@ -6,25 +6,21 @@ query case whose generated SQL is rejected counts as a false positive. Result comparison policy (declared, deterministic): -- Row ORDER is ignored (multiset comparison); DUPLICATE rows are preserved — - the comparison never deduplicates with a set. -- Column ORDER is tolerated when the column name sets match. -- Column SETS may differ when the widths differ: comparison is done on the - columns the two projections share by name, so an answer that is correct but - projects a different *number* of columns is not scored semantically wrong. - The difference itself is reported per case as ``extra_columns`` / - ``missing_columns`` and in aggregate as ``projection_difference_rate``. - Equal widths with disjoint names keep the positional fallback, so a renamed - column holding the same values is not penalised. Different widths *and* no - shared column name is a different query shape and is not equivalent. -- NULL compares equal to NULL only. -- Floats: integral floats compare equal to ints; non-integral floats are - rounded to 10 decimal places before comparison (float-noise tolerance); - non-finite floats compare as the strings "Infinity"/"-Infinity"/"NaN". -- Every run uses an ISOLATED state root (history/orchestration/vector) so - evaluation never pollutes production retrieval or session state. - -Token and cost values are deterministic estimates, not provider-reported billing usage. +- All reference columns are required by default. Shared columns cannot hide an + omitted metric. Auxiliary reference columns and additional output columns + require an explicit result_contract. +- Column names align positions; cells inside a row are never permuted. Outer + rows are compared as multisets preserving duplicates, unless an ordered + contract or reference ORDER BY requires delivery order. +- Empty results obey the declared empty policy. Only a successful run can + receive a correct-result verdict. +- NULL and booleans remain distinct from numbers; non-finite numbers fail. + Finite floats use 1e-9 relative and absolute tolerance. +- Legacy equal-width, completely renamed projections retain positional alias + matching only without an explicit contract. +- Every run uses an ISOLATED state root (history/orchestration/vector). + +Token and cost reports distinguish measured provider usage from fallback estimates. """ from __future__ import annotations @@ -53,6 +49,7 @@ from queryforge.infrastructure.db.sqlite_connector import SQLiteConnector from queryforge.infrastructure.models.factory import ModelFactory from queryforge.infrastructure.tools.database_tool import DatabaseTool +from queryforge.evaluation.results import ResultContract, compare_results, cells_match # Comparison tolerance for non-integral floats (see module docstring). FLOAT_COMPARISON_ROUNDING = 10 @@ -370,11 +367,12 @@ def _evaluate_query( # a false positive; trusting the expected SQL would make precision # tautologically 1.0. policy_rejected = _generated_policy_outcome(output) - semantic_correct = _semantic_equivalent( + semantic_correct = output.get("status") == "success" and _semantic_equivalent( output.get("rows", []), output.get("columns"), expected_rows, expected_columns, + contract=_case_result_contract(case), ) extra_columns, missing_columns = _projection_difference( output.get("columns"), expected_columns @@ -386,6 +384,7 @@ def _evaluate_query( database, expected_rows, expected_columns, + contract=_case_result_contract(case), ) return { "id": case.get("id", index), @@ -684,86 +683,35 @@ def _candidate_correct( database: Path, expected_rows: list[list[Any]], expected_columns: list[str], + *, contract: ResultContract | None = None, ) -> bool | None: if not sql: return None try: columns, rows = _execute_expected(database, sql) - return _semantic_equivalent(rows, columns, expected_rows, expected_columns) + return _semantic_equivalent(rows, columns, expected_rows, expected_columns, contract=contract) except Exception: return False def _semantic_equivalent( - actual_rows: list[list[Any]], - actual_columns: list[str] | None, - expected_rows: list[list[Any]], - expected_columns: list[str], + actual_rows: list[list[Any]], actual_columns: list[str] | None, + expected_rows: list[list[Any]], expected_columns: list[str], *, + contract: ResultContract | None = None, ) -> bool: - """Compare result sets by content, tolerant to column order and row order. - - Comparison happens on the columns the two projections **share by name**: - - * Equal name sets in a different order are reordered and compared in full. - * Different column counts (the defect this rule exists for) compare on the - shared columns only, so an answer that is correct but projects a - different *number* of columns is not scored as semantically wrong. The - difference is reported separately by the caller (see - ``_projection_difference``) rather than silently ignored. - * Equal column counts with disjoint names fall back to positional - comparison — this keeps the historical behaviour for a renamed column - (``anime_count`` vs ``action_anime_count``) with identical values. - * When the two projections share no column name *and* their counts differ, - this is a different query shape, not a projection difference, so the - result is not equivalent. - - Known limitation: a renamed column whose count also differs cannot be - matched by name and is still scored as wrong. Alias normalisation is not - attempted here. - - Row order is never significant and duplicate rows are preserved. When - column names are unavailable on the actual side, comparison falls back to - positional values (the historical behaviour). - """ - actual_columns = list(actual_columns or []) - if actual_columns and expected_columns: - if set(actual_columns) == set(expected_columns): - reordered = _reorder_columns(actual_columns, actual_rows, expected_columns) - return _canonical_rows(reordered) == _canonical_rows(expected_rows) - if len(actual_columns) == len(expected_columns) and not ( - set(actual_columns) & set(expected_columns) - ): - # Same width, completely different names: not a projection - # difference. Keep the positional comparison so a renamed column - # holding the same values is not newly penalised. - return _canonical_rows(actual_rows) == _canonical_rows(expected_rows) - actual_projection, expected_projection = _shared_column_projection( - actual_columns, expected_columns - ) - if not actual_projection: - # Different widths AND no shared column name: the two results do not - # describe the same quantity, so this is a genuine mismatch. - return False - actual_rows = [[row[index] for index in actual_projection] for row in actual_rows] - expected_rows = [ - [row[index] for index in expected_projection] for row in expected_rows - ] - return _canonical_rows(actual_rows) == _canonical_rows(expected_rows) - - -def _shared_column_projection( - actual_columns: list[str], - expected_columns: list[str], -) -> tuple[list[int], list[int]]: - """Index positions of the shared column names, in the expected order.""" + """Compare the entire required projection; auxiliary columns need a contract.""" + return compare_results(actual_rows, actual_columns, expected_rows, expected_columns, + contract=contract, positional_aliases=contract is None, + cell_match=cells_match) + - actual_positions: list[int] = [] - expected_positions: list[int] = [] - for position, column in enumerate(expected_columns): - if column in actual_columns: - expected_positions.append(position) - actual_positions.append(actual_columns.index(column)) - return actual_positions, expected_positions +def _case_result_contract(case: dict[str, Any]) -> ResultContract | None: + if case.get("result_contract") is not None: + return ResultContract.model_validate(case["result_contract"]) + # ORDER BY in the reference is an observable delivery obligation. + import sqlglot + tree = sqlglot.parse_one(case["expected_sql"], read="sqlite") + return ResultContract(row_order="ordered") if tree.args.get("order") else None def _projection_difference( @@ -1219,9 +1167,8 @@ def _build_report( "token_source_measured_cases": sum( 1 for item in results if item.get("token_source") == "measured" ), - # Projection tolerance (see module docstring): semantic_correctness_rate - # compares the shared columns, so a differing projection is reported - # here instead of being silently absorbed into the correctness rate. + # Diagnostic only: required projections are checked independently. + # An explicit contract can declare legitimate auxiliary columns. "projection_difference_rate": _rate( [ bool(item.get("extra_columns") or item.get("missing_columns")) diff --git a/scripts/freeze_diagnostic_tasks.py b/scripts/freeze_diagnostic_tasks.py new file mode 100644 index 0000000..cf3119d --- /dev/null +++ b/scripts/freeze_diagnostic_tasks.py @@ -0,0 +1,71 @@ +"""Freeze phase-3 diagnostic gold from independent, explicit read-only SQL oracles.""" +from __future__ import annotations + +import json +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +if str(ROOT) not in sys.path: + sys.path.insert(0, str(ROOT)) +from scripts.evaluate_sql import _execute_expected +from scripts.benchmark_agent import load_datasets + + +CASES = ( + ('anime_streaming', 'dev', 'watch_hours', 'fact_watch_session', 'watch_date_key', 'device_type', + 'SUM(watch_seconds)/3600.0', (202402, 202502), + 'Explain watch hours monthly for February 2025 year over year by device', 'complete'), + ('retail_orders', 'regression', 'net_revenue', 'fact_order', 'order_date_key', 'sales_channel', + 'SUM(net_amount_usd)', (202402, 202403), + 'Explain net revenue monthly for March 2024 month over month by sales channel', 'unverified'), + ('support_tickets', 'holdout', 'ticket_volume', 'fact_ticket', 'created_date_key', 'priority', + 'COUNT(DISTINCT ticket_id)', (202402, 202403), + 'Explain ticket volume monthly for March 2024 month over month by priority', 'unverified'), +) + + +def build_tasks(): + datasets, tasks = load_datasets(), {} + for dataset, split, metric, table, time, category, expression, periods, question, completeness in CASES: + scope = f'{time}/100 IN ({periods[0]}, {periods[1]})' + sql = (f'SELECT printf(\'%04d-%02d\', {time}/10000, {time}/100%100) AS "calendar.month", ' + f'{category}, {expression} AS {metric} FROM {table} WHERE {scope} GROUP BY 1,2 ORDER BY 1,2') + database = ROOT / datasets[dataset]['database'] + columns, rows = _execute_expected(database, sql) + total_sql = f'SELECT {time}/100 AS period, {expression} AS value FROM {table} WHERE {scope} GROUP BY 1 ORDER BY 1' + _, total_rows = _execute_expected(database, total_sql) + totals = dict(total_rows) + prefix = f'answer.diagnosis.contributions.{metric}' + tasks[split] = dict(task_id=f'{dataset}_{split}_diagnostic', split=split, dataset=dataset, + template_id=f'{dataset}_diagnostic_{category}', question=question, runner='planner', + coverage=['business_diagnosis', 'time_category_grain', 'independent_reconciliation', 'required_projection'], + expected_outcome='analysis', expected_status=['succeeded'], + allowed_tools=['resolve_metric', 'check_data_quality', 'execute_sql', 'compare_periods', 'calculate_contribution', 'detect_anomaly'], + required_steps=['resolve_metric', 'check_data_quality', 'query_metric', 'compare_periods', 'calculate_contribution', 'detect_anomaly', 'compose_answer'], + required_evidence=['metric_resolution', 'data_quality', 'metric_value', 'metric_totals', 'period_comparison', 'contribution', 'anomaly'], + expected_values={'answer.columns': columns, 'answer.rows': rows, + prefix+'.independent_baseline': totals[periods[0]], prefix+'.independent_current': totals[periods[1]], + prefix+'.total_delta': totals[periods[1]]-totals[periods[0]], prefix+'.residual': 0, + prefix+'.residual_current': 0, prefix+'.residual_baseline': 0, prefix+'.residual_explained': True, + 'answer.diagnosis.interpretation': 'arithmetic_decomposition_not_causal_attribution', + 'answer.diagnosis.period_completeness': completeness, 'final_answer.status': 'success'}, + result_contract={'required_columns': columns, 'columns_path': 'answer.columns', 'rows_path': 'answer.rows', + 'row_order': 'ordered', 'empty': 'forbid'}, + values_absolute_tolerance={prefix+'.'+key: 1e-9 for key in ('residual', 'residual_current', 'residual_baseline')}, + answer_must_reference_evidence=True, reference_sql=sql, totals_reference_sql=total_sql, + oracle_path='answer.rows', max_tool_calls=40, + notes='Independent base-table SQL; no compiler or generated outputs are used to freeze expected values. Anomaly history has only two points and must be reported as insufficient_data.') + return tasks + + +def main(): + directory = ROOT / 'evaluation/diagnostics' + directory.mkdir(parents=True, exist_ok=True) + for split, task in build_tasks().items(): + (directory / f'{split}.jsonl').write_text(json.dumps(task, ensure_ascii=False) + '\n') + print('Frozen 3 diagnostic tasks on 3 physical schemas; model accuracy is not measured.') + + +if __name__ == '__main__': + main() diff --git a/scripts/freeze_live_tasks.py b/scripts/freeze_live_tasks.py new file mode 100644 index 0000000..fce6486 --- /dev/null +++ b/scripts/freeze_live_tasks.py @@ -0,0 +1,117 @@ +"""Freeze explicit live-evaluation questions against unchanged control-flow SQL oracles.""" +from __future__ import annotations + +import argparse +import json +from pathlib import Path +import sqlite3 +import sys + +import sqlglot + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +from queryforge.evaluation import TaskSpec, load_spec_splits +from queryforge.evaluation.isolation import audit_splits, audit_dataset_schemas +from queryforge.evaluation.results import compare_results +from queryforge.evaluation.sources import check_sql_sources +from scripts.benchmark_agent import load_datasets + +QUESTIONS = { + 'anime_streaming_dev_1': 'How many user accounts are stored? Return a single column named n.', + 'anime_streaming_dev_2': 'For each playback device type, show its total number of watch sessions over all stored dates. Return device_type and n, sorted by device_type.', + 'anime_streaming_dev_3': 'Count user accounts by country, including every country. Return country and n, sorted by country.', + 'anime_streaming_dev_4': 'What is the smallest stored episode identifier? Return one column named n.', + 'anime_streaming_dev_5': 'Return the identifier of the user whose user identifier is -1, if any. Return only user_id.', + 'anime_streaming_dev_6': 'What is the largest stored studio identifier? Return one column named n.', + 'support_tickets_holdout_1': 'How many support case records are stored? Return one column named n.', + 'support_tickets_holdout_2': 'Count all stored support cases by priority. Return priority and n, sorted by priority.', + 'support_tickets_holdout_3': 'For each support queue with at least one recorded case, show the queue name and number of cases. Return queue_name and n, sorted by queue_name.', + 'support_tickets_holdout_4': 'How many stored customer satisfaction survey responses have a NULL score? Return one column named n.', + 'support_tickets_holdout_5': 'List the identifiers of all recorded SLA breaches. Return only breach_id.', + 'support_tickets_holdout_6': 'How many support cases have been reopened? Count cases whose reopened flag is 1 and return one column named n.', + 'retail_orders_regression_1': 'How many order records are stored? Return one column named n.', + 'retail_orders_regression_2': 'Show the total net receipt amount in USD for each store region over all stored dates. Return region and amount, sorted by region.', + 'retail_orders_regression_3': 'Using a CTE, count all recorded receipt line items across all orders. Return one column named n.', + 'retail_orders_regression_4': 'For every outlet, return store_id and its position using dense rank by floor area, with the largest area ranked first. Include all outlets and sort the output by store_id.', + 'retail_orders_regression_5': 'Count receipt records with order dates from January 1 through March 31, 2024 inclusive. Return one column named n.', + 'retail_orders_regression_6': 'Count receipt records and receipt line records independently so that joining them does not inflate either count. Return orders and lines, in that order.', + 'retail_orders_regression_7': 'Show the three receipts with the largest net amounts. Return order_id and net_amount_usd, sorted by net_amount_usd descending, then order_id ascending for ties.', + 'retail_orders_regression_8': 'How many distinct payment methods occur in the stored receipts? Return one column named n.', + 'retail_orders_regression_9': 'Return the identifier of the store whose store identifier is -100, if any. Return only store_id.', + 'retail_orders_regression_10': 'Show the earliest and latest recorded receipt calendar keys. Return first_day and last_day in one row.', + 'retail_orders_regression_followup': '再查询一次刚才的订单数量,仍只返回 order_count 列。', +} + + +def frozen_tasks(*, source_contract=False, corrected_questions=False): + source_contract = source_contract or corrected_questions + datasets = load_datasets(ROOT / 'evaluation/datasets.json') + specs = load_spec_splits(ROOT / 'evaluation/tasks') + sources = {spec.task_id: spec for spec in specs if spec.runner == 'scripted_workflow'} + if set(sources) != set(QUESTIONS): + raise ValueError('Live question mapping must cover exactly the workflow fixtures') + records = {split: [] for split in ('dev', 'regression', 'holdout')} + live_specs = [] + for task_id, spec in sources.items(): + db = (ROOT / datasets[spec.dataset]['database']).resolve() + with sqlite3.connect(db.as_uri() + '?mode=ro', uri=True) as connection: + connection.execute('PRAGMA query_only=ON') + cursor = connection.execute(spec.reference_sql) + rows = [list(row) for row in cursor.fetchall()] + columns = [item[0] for item in cursor.description] + if not compare_results(rows, columns, spec.expected_values['rows'], columns): + raise ValueError(f'Source oracle drift: {task_id}') + # Preserve live-v1 bytes: the source field was absent at execution time. + record = spec.model_dump(mode='json', exclude_none=True, exclude={'required_sql_tables'}) + contract_version = 3 if corrected_questions else 2 if source_contract else 1 + record.update(task_id='live_' + task_id, template_id=f'live_v{contract_version}_' + spec.template_id, + question=QUESTIONS[task_id], expected_values={'rows': rows, 'columns': columns}, + result_contract={'required_columns': columns, 'allow_extra_columns': False, + 'row_order': 'ordered' if sqlglot.parse_one(spec.reference_sql, read='sqlite').args.get('order') else 'multiset', + 'empty': 'allow' if not rows else 'forbid'}, + notes='Live v1: explicit question/output contract; unchanged source reference SQL and data. Independent read-only SQLite oracle; original fixture retained.') + if source_contract: + record['required_sql_tables'] = list(spec.expected_tables) + record['notes'] = 'Live v2: unchanged v1 question, reference SQL, data and output contract; adds independent physical source coverage for post-hoc trace auditing.' + source_check = check_sql_sources(spec.reference_sql, spec.expected_tables) + if not source_check.passed: + raise ValueError(f'Reference source contract is unverified: {task_id}') + if corrected_questions: + record['notes'] = 'Live v3: retains reference SQL, data, output and source contracts; disambiguates store ranking across every store_format. No v3 model results claimed.' + if task_id == 'retail_orders_regression_4': + record['question'] = 'For every store, regardless of its store_format, return store_id and its position using dense rank by floor area, with the largest area ranked first. Include all stores and sort the output by store_id.' + if getattr(spec, 'follow_up_context', None): + record['follow_up_context'] = ['How many distinct orders are stored? Return one column named order_count.'] + live = TaskSpec.model_validate(record) + live_specs.append(live) + records[spec.split].append(record) + audit_splits(live_specs) + audit_dataset_schemas(live_specs, datasets, ROOT) + return {split: ''.join(json.dumps(record, ensure_ascii=False, sort_keys=True) + '\n' for record in sorted(items, key=lambda r: r['task_id'])) + for split, items in records.items()} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--check', action='store_true', help='Check frozen files without writing') + parser.add_argument('--source-contract', action='store_true', help='Freeze separate live-v2 source contracts; never changes live-v1') + parser.add_argument('--correct-questions', action='store_true', help='Freeze separate live-v3 source contracts and corrected all-store ranking wording; no model calls') + args = parser.parse_args() + contract_version = 3 if args.correct_questions else 2 if args.source_contract else 1 + target = ROOT / ('evaluation/live_tasks_v3' if args.correct_questions else + 'evaluation/live_tasks_v2' if args.source_contract else 'evaluation/live_tasks') + frozen = frozen_tasks(source_contract=args.source_contract, corrected_questions=args.correct_questions) + if args.check: + for split, text in frozen.items(): + if (target / f'{split}.jsonl').read_text() != text: + raise SystemExit(f'Frozen live task drift: {split}') + else: + target.mkdir(parents=True, exist_ok=True) + for split, text in frozen.items(): + (target / f'{split}.jsonl').write_text(text) + print(f'Live tasks v{contract_version}: 23 independent SQL oracles and explicit contracts verified') + + +if __name__ == '__main__': + main() diff --git a/scripts/run_paired_benchmark.py b/scripts/run_paired_benchmark.py new file mode 100644 index 0000000..7638696 --- /dev/null +++ b/scripts/run_paired_benchmark.py @@ -0,0 +1,160 @@ +"""Balanced, repeated A/B experiments; tier 1 is control-flow QA, tier 3 costs API spend.""" +from __future__ import annotations + +import argparse +import json +import platform +import random +import sqlite3 +import sys +import tempfile +from dataclasses import replace +from importlib.metadata import version +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +if str(ROOT) not in sys.path: + sys.path.insert(0, str(ROOT)) + +from scripts import benchmark_agent as harness +from scripts.evaluate_sql import _environment_error_reason +from queryforge.evaluation import load_spec_splits +from queryforge.evaluation.isolation import audit_splits, audit_corpus, audit_dataset_schemas +from queryforge.evaluation.paired import summarize_pairs + + +def parse_args(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--tier', type=int, choices=(1, 3), default=1) + parser.add_argument('--feature', choices=('candidates', 'skills'), default='candidates') + parser.add_argument('--repeat', type=int, default=5) + parser.add_argument('--seed', type=int, default=17) + parser.add_argument('--parallel-candidates', type=int, choices=(1, 2, 3), default=1, + help='Fixed count in a skills experiment; candidate experiment always compares 1 vs 2') + parser.add_argument('--datasets', default=harness.DEFAULT_DATASETS) + parser.add_argument('--tasks-dir', default=harness.DEFAULT_TASKS_DIR) + parser.add_argument('--split', action='append', choices=('dev', 'regression', 'holdout')) + parser.add_argument('--task', action='append', default=[]) + parser.add_argument('--retrieval-corpus', action='append', default=[]) + parser.add_argument('--provider') + parser.add_argument('--model') + parser.add_argument('--prices') + parser.add_argument('--dry-run', action='store_true', help='Write the exact experiment manifest without calling a model') + parser.add_argument('--report', required=True) + return parser.parse_args(argv) + + +def error_text(value): + if isinstance(value, dict): + for key, child in value.items(): + if key in {'error', 'exception', 'error_message'} and isinstance(child, str): + yield child + else: + yield from error_text(child) + elif isinstance(value, list): + for child in value: + yield from error_text(child) + + +def provider_contract_error(text): + text = text.casefold() + return 'generate_with_messages' in text and any(marker in text for marker in + ('unexpected keyword argument', 'required positional argument', 'positional arguments but')) + + +def run(args): + if args.repeat < 2: + raise ValueError('paired experiments require --repeat >= 2') + if args.tier == 3 and not (args.provider and args.model): + raise ValueError('tier 3 requires explicit --provider and --model') + if args.tier == 1 and (args.provider or args.model): + raise ValueError('tier 1 cannot use a real provider') + datasets = harness.load_datasets(args.datasets) + all_specs = load_spec_splits(harness._project_path(args.tasks_dir)) + audit_splits(all_specs) + schema_hashes = audit_dataset_schemas(all_specs, datasets, ROOT) + for corpus in args.retrieval_corpus: + audit_corpus(all_specs, harness._project_path(corpus)) + selected = harness.select_specs(all_specs, splits=args.split or ['dev', 'regression', 'holdout'], + task_ids=args.task, datasets=[], limit=0) + specs = [s for s in selected if harness.spec_runner(s) in {'workflow', 'scripted_workflow'}] + if not specs: + raise ValueError('no workflow tasks selected for the paired experiment') + if args.tier == 1 and any(harness.spec_runner(s) != 'scripted_workflow' for s in specs): + raise ValueError('offline pairs require scripted_workflow tasks') + prices = json.loads(harness._project_path(args.prices).read_text()) if args.prices else None + if prices and not prices.get('version'): + raise ValueError('price table must include a version') + arms = ({'baseline': {'parallel_candidates': 1, 'skill_mode': 'auto'}, + 'treatment': {'parallel_candidates': 2, 'skill_mode': 'auto'}} if args.feature == 'candidates' else + {'baseline': {'parallel_candidates': args.parallel_candidates, 'skill_mode': 'off'}, + 'treatment': {'parallel_candidates': args.parallel_candidates, 'skill_mode': 'auto'}}) + rng = random.Random(args.seed) + starts = {s.task_id: rng.randrange(2) for s in specs} + schedule = [{'task_id': s.task_id, 'repeat': repeat, + 'order': ['baseline', 'treatment'] if (starts[s.task_id] + repeat) % 2 == 0 else ['treatment', 'baseline']} + for repeat in range(args.repeat) for s in specs] + manifest = {'tier': args.tier, 'mode': 'control_flow_only' if args.tier == 1 else 'model_e2e', + 'feature': args.feature, 'provider': args.provider, 'model': args.model, 'arms': arms, + 'fixed_controls': {'history_top_k': 0, 'vector_kb': False, 'today': '2024-12-31', 'fix_retries': 2}, + 'task_count': len(specs), 'case_executions': len(schedule) * 2, 'repeats': args.repeat, + 'seed': args.seed, 'schema_sha256': schema_hashes, 'schedule': schedule, + 'excluded_tasks': [s.task_id for s in selected if s not in specs], + 'price_table': prices, 'api_spend': 'none' if args.tier == 1 or args.dry_run else 'requires human authorization under AGENTS.md'} + with tempfile.TemporaryDirectory(prefix='qf_paired_') as state: + context = harness.BenchmarkContext(datasets, Path(state), prices=prices, provider=args.provider, model=args.model) + provenance = harness.build_report(tier=args.tier, specs=specs, outcomes=[], traces=[], context=context, + thresholds={}, ablations=[], repeats=args.repeat)['provenance'] + manifest['provenance'] = provenance + manifest['versions'] = {'python': platform.python_version(), 'sqlite': sqlite3.sqlite_version, + 'sqlglot': version('sqlglot'), 'pydantic': version('pydantic')} + if args.dry_run: + return {'benchmark': 'paired_manifest', 'manifest': manifest, 'executed': False} + records = [] + by_id = {s.task_id: s for s in specs} + for scheduled in schedule: + for arm in scheduled['order']: + arm_context = replace(context, **arms[arm]) + outcomes, traces = harness.run_suite([by_id[scheduled['task_id']]], arm_context, tier=args.tier) + if len(outcomes) != 1: + raise ValueError('pair execution did not produce exactly one outcome') + record = outcomes[0].model_dump() + errors = ' '.join(error_text(traces[0])) + reason = _environment_error_reason(RuntimeError(errors)) if not record['passed'] else None + record.update(arm=arm, repeat=scheduled['repeat'], environment_error=reason is not None, + environment_error_reason=reason, + provider_contract_error=not record['passed'] and provider_contract_error(errors), + raw_trace=traces[0]) + records.append(record) + final_provenance = harness.build_report(tier=args.tier, specs=specs, outcomes=[], traces=[], context=context, + thresholds={}, ablations=[], repeats=args.repeat)['provenance'] + stable = all(provenance[key] == final_provenance[key] for key in + ('source_sha256', 'assets_sha256', 'datasets_sha256', 'contracts_sha256', 'gold_sha256')) + summary = summarize_pairs(records, repeats=args.repeat, seed=args.seed) + summary['provenance_stable'] = stable + summary['complete'] = summary['complete'] and stable + return {'benchmark': 'paired_agent_tasks', 'manifest': manifest, 'summary': summary, 'records': records, + 'executed': True, 'final_provenance': final_provenance, + 'offline_gate_passed': args.tier == 1 and all(r['passed'] for r in records)} + + +def main(argv=None): + args = parse_args(argv) + try: + report = run(args) + path = Path(args.report).expanduser().resolve() + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n') + except (ValueError, OSError) as exc: + print(f'Paired benchmark refused: {exc}', file=sys.stderr) + return 2 + print(json.dumps({'report': str(path), 'executed': report['executed'], + 'tasks': report['manifest']['task_count'], 'case_executions': report['manifest']['case_executions'], + 'summary': report.get('summary')}, ensure_ascii=False)) + if args.dry_run: + return 0 + return 0 if report['summary']['complete'] and (args.tier == 3 or report['offline_gate_passed']) else 1 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/tests/fixtures/studio_records.csv b/tests/fixtures/studio_records.csv new file mode 100644 index 0000000..cb4a0d0 --- /dev/null +++ b/tests/fixtures/studio_records.csv @@ -0,0 +1,4 @@ +record_id,entity_id,recorded_at,amount +1,11,2024-01-01,10 +2,12,2024-01-02,20 +3,13,2024-01-03,30 diff --git a/tests/studio_fixture_server.py b/tests/studio_fixture_server.py new file mode 100644 index 0000000..cf090ec --- /dev/null +++ b/tests/studio_fixture_server.py @@ -0,0 +1,50 @@ +"""Explicit offline browser fixture. Never loads .env or calls a provider API. + +Run: .venv/bin/python -m tests.studio_fixture_server +Storage: /tmp/queryforge_phase4_fixture/backend; listens only on 127.0.0.1:8000. +""" +import time +from pathlib import Path + +from queryforge.application import AgentService +from queryforge.core.config import Config +from queryforge.interfaces.api.app import create_app +from scripts.benchmark_runners import ScriptedModel + + +class BrowserFixtureModel(ScriptedModel): + calls = 0 + + def generate_json(self, prompt): + type(self).calls += 1 + question = prompt.partition("User question:\n")[2].split("\n\n", 1)[0].lower() + if "generate one" in prompt.lower() or "alternative" in prompt.lower(): + if "slow" in question: + time.sleep(20) + self.sql = "DELETE FROM uploaded_record" if "delete" in question else ( + "SELECT SUM(amount) AS amount FROM uploaded_record" if "uploaded_amount_sum" in question + else "SELECT COUNT(DISTINCT record_id) AS n FROM uploaded_record") + return super().generate_json(prompt) + + +class FixtureService(AgentService): + def health(self): + return {**super().health(), "offline_fixture": True, "offline_model_calls": BrowserFixtureModel.calls} + + +def fixture_service(root: Path): + config = Config("scripted", None, "offline-browser-fixture", None, + "sample_data/anime_streaming/anime_streaming.sqlite", + orchestration_state_root=str(root / "runs"), + domain_registry_path=str(root / "registry.json"), + history_db_path=str(root / "history.db"), report_output_dir=str(root / "reports"), + allowed_database_paths=(str(root), str(Path("sample_data").resolve())),) + return FixtureService(config_loader=lambda **_: config, + llm_factory=lambda _: BrowserFixtureModel("SELECT COUNT(*) AS n FROM uploaded_record")) + + +if __name__ == "__main__": + import uvicorn + root = Path("/tmp/queryforge_phase4_fixture/backend") + root.mkdir(parents=True, exist_ok=True) + uvicorn.run(create_app(fixture_service(root)), host="127.0.0.1", port=8000) diff --git a/tests/test_agent_evaluator.py b/tests/test_agent_evaluator.py index 2003e77..ddcac24 100644 --- a/tests/test_agent_evaluator.py +++ b/tests/test_agent_evaluator.py @@ -494,7 +494,7 @@ def test_reference_trace_passes_every_check(self): self.assertTrue(all(item.passed for item in outcome.checks)) self.assertEqual( [item.name for item in outcome.checks], - [name for name in CHECK_NAMES if name not in {"budget"}] + [name for name in CHECK_NAMES if name not in {"budget", "sql_sources"}] + ["budget"] + [], ) @@ -1673,6 +1673,7 @@ def test_check_names_and_failure_classes_are_the_frozen_vocabulary(self): "required_evidence", "forbidden_evidence", "expected_values", + "sql_sources", "evidence_anchor", "tool_legality", "tool_validity", diff --git a/tests/test_analysis_diagnostics.py b/tests/test_analysis_diagnostics.py new file mode 100644 index 0000000..a9ea540 --- /dev/null +++ b/tests/test_analysis_diagnostics.py @@ -0,0 +1,256 @@ +"""Diagnosis outcomes checked against independent SQLite populations.""" +import contextlib +import importlib.util +import io +import json +import sqlite3 +import unittest +from unittest.mock import patch + +import yaml + +from tests.test_analysis_planner import Fixture +from queryforge.domain.analysis.diagnostics import reconcile_buckets +from queryforge.orchestration.planner import AnalysisPlan + + +QUESTION = "Explain item amount monthly year over year by category" + + +class AnalysisDiagnosticsTest(unittest.TestCase): + def setUp(self): + self.fixture = Fixture() + with sqlite3.connect(self.fixture.database) as db: + db.execute("ALTER TABLE items ADD COLUMN happened TEXT") + db.execute("DELETE FROM items") + db.executemany("INSERT INTO items VALUES (?,?,?,?,?,?)", [ + (1, "baseline a", "a", 30, 1, "2024-02-05"), + (2, "baseline b", "b", 20, 2, "2024-02-10"), + (3, "current a", "a", 10, 1, "2025-02-05"), + (4, "current b", "b", 50, 2, "2025-02-10"), + (5, "history", "a", 10, 1, "2024-01-01"), + (6, "history", "a", 15, 1, "2025-01-01"), + ]) + model = yaml.safe_load(self.fixture.semantic_model.read_text()) + model["entities"][0]["dimensions"].append({"name": "event_date", "column": "happened"}) + for metric in model["metrics"]: + metric.update(time_field="items.happened", analysis={ + "unit": "USD" if metric["aggregation"] == "sum" else "rows", "additivity": "additive", + "time": {"role": "sale", "coverage_start": "2024-01-01", "complete_through": "2025-12-31", "require_complete_periods": True}, + }) + metric["allowed_dimensions"].append("items.event_date") + self.save(model) + + def tearDown(self): + self.fixture.cleanup() + + def save(self, model): + self.fixture.semantic_model.write_text(yaml.safe_dump(model)) + + def analyze(self, question=QUESTION, **kwargs): + return self.fixture.analyze(question, max_replans=0, **kwargs) + + @staticmethod + def output(payload, step_id): + return next(s["outputs"] for s in payload["steps"] if s["step_id"] == step_id) + + def oracle(self): + with sqlite3.connect(f"file:{self.fixture.database}?mode=ro", uri=True) as db: + return db.execute("SELECT substr(happened,1,7), category, SUM(amount) FROM items " + "WHERE substr(happened,1,7) IN ('2024-02','2025-02') GROUP BY 1,2 ORDER BY 1,2").fetchall() + + def test_independent_totals_and_offsetting_contributions_reconcile(self): + result = self.analyze() + self.assertEqual(result["status"], "succeeded") + self.assertEqual(self.oracle(), [("2024-02", "a", 30.0), ("2024-02", "b", 20.0), ("2025-02", "a", 10.0), ("2025-02", "b", 50.0)]) + diagnosis = result["answer"]["diagnosis"] + part = diagnosis["contributions"]["item_amount"] + self.assertEqual((part["independent_current"], part["independent_baseline"], part["total_delta"]), (60, 50, 10)) + by_category = {x["category"]: x for x in part["contributions"]} + self.assertEqual((by_category['["a"]']["delta"], by_category['["b"]']["delta"]), (-20, 30)) + self.assertEqual((by_category['["a"]']["share_pct"], by_category['["b"]']["share_pct"]), (-200, 300)) + self.assertEqual((part["residual_current"], part["residual_baseline"], part["residual"]), (0, 0, 0)) + self.assertTrue(part["residual_explained"]) + self.assertEqual(part["unit"], "USD") + self.assertEqual(diagnosis["quality"]["status"], "ok") + self.assertTrue(diagnosis["quality"]["time_checks"]) + self.assertEqual(diagnosis["period_completeness"], "complete") + self.assertIn("not_causal", diagnosis["interpretation"]) + known = {e.get("evidence_id", e.get("id")) for e in result["evidence"]} + self.assertEqual(len(diagnosis["evidence_ids"]), 6) + self.assertTrue(set(diagnosis["evidence_ids"]).issubset(known)) + self.assertEqual(result["final_answer"]["status"], "success") + + def test_every_requested_metric_has_independent_diagnosis(self): + result = self.analyze("Explain item count and item amount monthly year over year by category") + self.assertEqual(result["status"], "succeeded") + parts = result["answer"]["diagnosis"]["contributions"] + self.assertEqual(set(parts), {"item_count", "item_amount"}) + self.assertEqual(parts["item_count"]["total_delta"], 0) + self.assertEqual(parts["item_amount"]["total_delta"], 10) + self.assertEqual(set(result["answer"]["diagnosis"]["anomalies"]), set(parts)) + self.assertEqual(result["final_answer"]["status"], "success") + + def test_missing_category_is_zero_only_with_complete_coverage(self): + with sqlite3.connect(self.fixture.database) as db: + db.execute("UPDATE items SET category='new' WHERE item_id=4") + result = self.analyze() + self.assertEqual(result["status"], "succeeded") + part = result["answer"]["diagnosis"]["contributions"]["item_amount"] + self.assertEqual(len(part["empty_buckets"]), 2) + self.assertEqual(part["total_delta"], 10) + model = yaml.safe_load(self.fixture.semantic_model.read_text()) + model["metrics"][1]["analysis"]["time"]["require_complete_periods"] = False + self.save(model) + blocked = self.analyze() + self.assertNotEqual(blocked["status"], "succeeded") + self.assertIsNone(blocked["answer"]) + self.assertTrue(any("unverified_empty_bucket" in (s.get("error") or "") for s in blocked["steps"])) + + def test_null_category_remains_a_distinct_auditable_bucket(self): + with sqlite3.connect(self.fixture.database) as db: + db.execute("UPDATE items SET category=NULL WHERE category='a'") + result = self.analyze() + self.assertEqual(result["status"], "succeeded") + part = result["answer"]["diagnosis"]["contributions"]["item_amount"] + self.assertTrue(any(x["category"] == "[null]" for x in part["contributions"])) + self.assertEqual(part["total_delta"], 10) + + def test_orphan_dimension_rows_cannot_hide_behind_zero_delta_residual(self): + with sqlite3.connect(self.fixture.database) as db: + db.execute("INSERT INTO brands VALUES (1,'a')") + db.execute("UPDATE items SET amount=20 WHERE item_id=4") + model = yaml.safe_load(self.fixture.semantic_model.read_text()) + model["metrics"][1]["allowed_dimensions"].append("brands.brand_name") + self.save(model) + result = self.analyze("Explain item amount monthly year over year by brand_name") + self.assertNotEqual(result["status"], "succeeded") + self.assertIsNone(result["answer"]) + self.assertTrue(any("independent period totals" in (s.get("error") or "") for s in result["steps"])) + + def test_zero_total_change_keeps_opposing_drivers_without_percentage(self): + with sqlite3.connect(self.fixture.database) as db: + db.execute("UPDATE items SET amount=40 WHERE item_id=4") + result = self.analyze() + self.assertEqual(result["status"], "succeeded") + part = result["answer"]["diagnosis"]["contributions"]["item_amount"] + self.assertEqual(part["total_delta"], 0) + self.assertEqual(sorted(c["delta"] for c in part["contributions"]), [-20, 20]) + self.assertTrue(all(c["share_pct"] is None for c in part["contributions"])) + + def test_dimension_specific_non_additivity_refuses_contribution(self): + model = yaml.safe_load(self.fixture.semantic_model.read_text()) + model["metrics"][1]["analysis"]["non_additive_dimensions"] = ["items.category"] + self.save(model) + result = self.analyze() + self.assertNotEqual(result["status"], "succeeded") + self.assertIsNone(result["answer"]) + + def test_non_additive_metric_is_not_summed_into_drivers(self): + model = yaml.safe_load(self.fixture.semantic_model.read_text()) + model["metrics"][1].update(aggregation="ratio", expression="CAST(SUM(items.amount) AS REAL) / COUNT(*)") + model["metrics"][1]["analysis"]["additivity"] = "non_additive" + self.save(model) + result = self.analyze() + self.assertNotEqual(result["status"], "succeeded") + self.assertIsNone(result["answer"]) + + def test_query_cap_cannot_produce_complete_contribution(self): + plan = AnalysisPlan.model_validate(self.analyze()["plan"]) + plan.step("query_metric").inputs["limit"] = 2 + result = self.analyze(plan=plan) + self.assertNotEqual(result["status"], "succeeded") + self.assertIsNone(result["answer"]) + + def test_insufficient_anomaly_history_is_an_explicit_limitation(self): + result = self.analyze("Explain item amount monthly year over year by category for February 2025") + self.assertEqual(result["status"], "succeeded") + self.assertEqual(result["answer"]["diagnosis"]["anomalies"]["item_amount"]["state"], "insufficient_data") + self.assertTrue(any("insufficient_data" in x for x in result["answer"]["limitations"])) + + def test_resume_preserves_distinct_total_and_bucket_evidence(self): + first = self.analyze(run_id="diagnostic-resume") + # Simulate a crash after steps were recorded, before terminal commit. + journal = self.fixture.root / ".queryforge" / "runs" / "diagnostic-resume" / "execution.json" + record = json.loads(journal.read_text()) + record.update(status="running", terminal_outcome=None, terminal_at=None) + journal.write_text(json.dumps(record)) + resumed = self.analyze(run_id="diagnostic-resume", resume=True) + self.assertEqual(first["status"], resumed["status"]) + self.assertEqual(first["answer"]["diagnosis"], resumed["answer"]["diagnosis"]) + self.assertIn("query_totals", resumed["reused_steps"]) + self.assertIn("query_metric", resumed["reused_steps"]) + + def test_custom_plan_cannot_omit_requested_diagnosis(self): + preview = self.analyze() + plan = AnalysisPlan.model_validate(preview["plan"]) + plan.steps = [s for s in plan.steps if s.action not in {"calculate_contribution", "detect_anomaly"}] + compose = plan.steps[-1] + compose.depends_on = ["query_metric", "compare_periods"] + compose.validation["require_evidence"] = ["metric_resolution", "metric_value", "period_comparison", "data_quality", "metric_totals"] + result = self.analyze(plan=plan) + self.assertNotEqual(result["status"], "succeeded") + self.assertTrue(any("request_incomplete: diagnosis" in (s.get("error") or "") for s in result["steps"])) + + def test_cli_delivers_diagnosis_and_anchored_evidence(self): + from queryforge.cli import main + with patch("queryforge.application.analysis_planner.AnalysisPlannerService", return_value=self.fixture.service()), patch("sys.argv", [ + "queryforge", "--analyze", "--question", QUESTION, "--database", str(self.fixture.database), + "--semantic-model", str(self.fixture.semantic_model), + ]): + stream = io.StringIO() + with contextlib.redirect_stdout(stream): + code = main() + self.assertEqual(code, 0) + self.assertEqual(json.loads(stream.getvalue())["answer"]["diagnosis"]["contributions"]["item_amount"]["total_delta"], 10) + + def test_reconciliation_rejects_duplicate_and_mismatched_populations(self): + result = self.analyze() + buckets, totals = self.output(result, "query_metric"), self.output(result, "query_totals") + with self.assertRaisesRegex(ValueError, "different populations"): + reconcile_buckets({**buckets, "filters": ["items.amount>0"]}, totals, "item_amount", "2025-02", "2024-02") + with self.assertRaisesRegex(ValueError, "duplicate category"): + reconcile_buckets({**buckets, "rows": buckets["rows"] + [buckets["rows"][-1]]}, totals, "item_amount", "2025-02", "2024-02") + + @unittest.skipUnless(importlib.util.find_spec("fastapi") and importlib.util.find_spec("httpx"), "API extras absent") + def test_rest_delivers_the_same_reconciled_diagnosis(self): + from fastapi.testclient import TestClient + from queryforge.application import AgentService + from queryforge.interfaces.api.app import create_app + config = self.fixture.config() + with TestClient(create_app(AgentService(config_loader=lambda **_: config))) as client: + response = client.post("/analyze", json={"question": QUESTION, "database": str(self.fixture.database), + "semantic_model_path": str(self.fixture.semantic_model)}) + self.assertEqual(response.status_code, 200) + payload = response.json() + self.assertEqual(payload["status"], "succeeded") + self.assertEqual(payload["final_answer"]["status"], "success") + self.assertEqual(payload["answer"]["diagnosis"]["contributions"]["item_amount"]["total_delta"], 10) + + +class DiagnosticGoldTest(unittest.TestCase): + def test_frozen_gold_matches_independent_sql_and_all_schemas_execute(self): + import tempfile + from pathlib import Path + from queryforge.evaluation import load_spec_splits + from queryforge.evaluation.isolation import audit_splits, audit_dataset_schemas + from scripts import benchmark_agent as harness + from scripts.freeze_diagnostic_tasks import build_tasks + root = Path(__file__).resolve().parents[1] + specs = load_spec_splits(root / "evaluation/diagnostics") + regenerated = build_tasks() + for spec in specs: + self.assertEqual(spec.model_dump(exclude_unset=True), regenerated[spec.split]) + audit_splits(specs) + self.assertEqual(len(set(audit_dataset_schemas(specs, harness.load_datasets(), root).values())), 3) + with tempfile.TemporaryDirectory() as directory: + outcomes, traces = harness.run_suite(specs, harness.BenchmarkContext(harness.load_datasets(), Path(directory))) + self.assertEqual(len(outcomes), 3) + self.assertTrue(all(o.passed for o in outcomes), [(o.task_id, o.checks) for o in outcomes if not o.passed]) + for trace in traces: + diagnosis = trace["payload"]["answer"]["diagnosis"] + self.assertTrue(all(a["state"] == "insufficient_data" for a in diagnosis["anomalies"].values())) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_analysis_intent_regressions.py b/tests/test_analysis_intent_regressions.py new file mode 100644 index 0000000..c74ddbc --- /dev/null +++ b/tests/test_analysis_intent_regressions.py @@ -0,0 +1,315 @@ +"""Review regressions: verify complete answers against independent fixture data.""" + +import contextlib +import importlib.util +import io +import json +import sqlite3 +import unittest +from unittest.mock import patch + +import yaml + +from tests.test_analysis_planner import Fixture +from queryforge.domain.semantic.sql_validator import QuerySpecCompiler + + +class AnalysisIntentRegressionTest(unittest.TestCase): + def setUp(self): + self.fixture = Fixture() + + def tearDown(self): + self.fixture.cleanup() + + def time_fixture(self, periods=("2024-02-01", "2025-01-01", "2025-02-01")): + with sqlite3.connect(self.fixture.database) as db: + db.execute("ALTER TABLE items ADD COLUMN month TEXT") + db.executemany( + "UPDATE items SET month = ? WHERE item_id = ?", + [(period, index) for index, period in enumerate(periods, 1)], + ) + model = yaml.safe_load(self.fixture.semantic_model.read_text()) + model["entities"][0]["dimensions"].append( + {"name": "month", "column": "month", "description": "Event month"} + ) + model["metrics"][1]["time_field"] = "items.month" + model["metrics"][1]["allowed_dimensions"].append("items.month") + self.fixture.semantic_model.write_text(yaml.safe_dump(model)) + + @staticmethod + def metric_result(payload): + return next(s["outputs"] for s in payload["steps"] if s["action"] == "query_metric") + + def test_all_requested_metrics_are_returned_with_evidence(self): + payload = self.fixture.analyze("Show item count and total amount") + self.assertEqual(payload["status"], "succeeded") + self.assertEqual(set(payload["answer"]["metrics"]), {"item_count", "item_amount"}) + self.assertEqual(payload["answer"]["values"], {"item_count": 3, "item_amount": 60.0}) + self.assertTrue(payload["answer"]["evidence_ids"]) + composed = next(s["outputs"] for s in payload["steps"] if s["action"] == "compose_answer") + self.assertEqual(composed["validation_problems"], []) + + def test_multiple_metrics_by_category_match_fixture_rows(self): + payload = self.fixture.analyze("Show item count and total amount by category") + self.assertEqual(payload["status"], "succeeded") + result = self.metric_result(payload) + names = result["columns"] + actual = {row[0]: (row[names.index("item_count")], row[names.index("item_amount")]) + for row in result["rows"]} + self.assertEqual(actual, {"a": (2, 40.0), "b": (1, 20.0)}) + + def test_different_metric_scopes_are_aggregated_independently(self): + model = yaml.safe_load(self.fixture.semantic_model.read_text()) + model["metrics"][1]["default_filters"] = ["items.amount > 10"] + self.fixture.semantic_model.write_text(yaml.safe_dump(model)) + payload = self.fixture.analyze("Show item count and total amount") + self.assertEqual(payload["status"], "succeeded") + self.assertEqual(payload["answer"]["values"], {"item_count": 3, "item_amount": 50.0}) + self.assertEqual(self.metric_result(payload)["metric_contracts"]["item_amount"]["population_filters"], ["items.amount > 10"]) + + def test_explicit_filter_returns_requested_slice_not_full_total(self): + payload = self.fixture.analyze("Show total amount where item_id = 1") + self.assertEqual(payload["status"], "succeeded") + self.assertEqual(payload["answer"]["value"], 10.0) + self.assertTrue(payload["analysis_request"]["filters"]) + self.assertIn("items.item_id = 1", self.metric_result(payload)["sql"]) + + def test_filter_columns_are_not_inferred_as_grouping_dimensions(self): + for clause in ("where category = 'a' AND amount >= 20", "for category = 'a' AND amount >= 20"): + with self.subTest(clause=clause): + payload = self.fixture.analyze("Show total amount " + clause) + self.assertEqual(payload["status"], "succeeded") + self.assertEqual(payload["answer"]["value"], 30.0) + self.assertEqual(payload["analysis_request"]["dimensions"], []) + + def test_filter_and_grouping_are_both_preserved(self): + payload = self.fixture.analyze("Show total amount where amount >= 20 by category") + self.assertEqual(payload["status"], "succeeded") + self.assertEqual(self.metric_result(payload)["rows"], [["a", 30.0], ["b", 20.0]]) + + def test_literal_filter_operators_match_independent_fixture_values(self): + cases = (("item_id IN (1, 3)", 40.0), ("amount BETWEEN 10 AND 20", 30.0), + ("(category = 'a' OR category = 'b') AND amount > 10", 50.0), + ("NOT (category = 'b')", 40.0), ("amount >= -1", 60.0)) + for clause, expected in cases: + with self.subTest(clause=clause): + payload = self.fixture.analyze("Show total amount where " + clause) + self.assertEqual(payload["status"], "succeeded") + self.assertEqual(payload["answer"]["value"], expected) + + def test_quoted_filter_values_do_not_change_time_or_grouping_intent(self): + value = "by supplier 2024 monthly yoy" + with sqlite3.connect(self.fixture.database) as db: + db.execute("UPDATE items SET name = ? WHERE item_id = 1", (value,)) + payload = self.fixture.analyze(f"Show total amount where name = '{value}'") + self.assertEqual(payload["status"], "succeeded") + self.assertEqual(payload["answer"]["value"], 10.0) + request = payload["analysis_request"] + self.assertEqual(request["dimensions"], []) + self.assertIsNone(request["time_range"]) + self.assertIsNone(request["time_grain"]) + self.assertIsNone(request["comparison_baseline"]) + + def test_null_filter_and_empty_multi_metric_scope_are_explicit(self): + with sqlite3.connect(self.fixture.database) as db: + db.execute("UPDATE items SET category = NULL WHERE item_id = 1") + payload = self.fixture.analyze("Show total amount where category IS NULL") + self.assertEqual(payload["status"], "succeeded") + self.assertEqual(payload["answer"]["value"], 10.0) + empty = self.fixture.analyze("Show item count and total amount where item_id = 999", max_replans=0) + self.assertEqual(empty["status"], "partial") + self.assertIsNone(empty["answer"]) + + def test_unknown_or_unsupported_filters_do_not_execute_sql(self): + clauses = ("item_id = 1; DROP TABLE items", "supplier_code = 1", + "item_id IN (SELECT item_id FROM items)", "item_id = 1 -- ignore", + "item_id = ABS(-1)", "category is popular") + for clause in clauses: + with self.subTest(clause=clause): + payload = self.fixture.analyze("Show total amount where " + clause) + self.assertEqual(payload["status"], "needs_clarification") + self.assertEqual(payload["steps"], []) + self.assertIsNone(payload["answer"]) + with sqlite3.connect(self.fixture.database) as db: + self.assertEqual(db.execute("SELECT COUNT(*) FROM items").fetchone()[0], 3) + + def test_informal_filter_clauses_are_clarified_instead_of_ignored(self): + for clause in ("for category a", "with supplier_code 'x'", "for popular items"): + with self.subTest(clause=clause): + payload = self.fixture.analyze("Show total amount " + clause) + self.assertEqual(payload["status"], "needs_clarification") + self.assertEqual(payload["steps"], []) + + def test_for_a_calendar_year_remains_a_time_window(self): + self.time_fixture() + payload = self.fixture.analyze("Show item amount for 2024") + self.assertEqual(payload["status"], "succeeded") + self.assertEqual(payload["answer"]["value"], 10.0) + self.assertEqual(payload["analysis_request"]["filters"], []) + + def test_time_window_without_governed_time_cannot_return_full_total(self): + payload = self.fixture.analyze("Show total amount for 2024") + self.assertEqual(payload["status"], "needs_clarification") + self.assertEqual(payload["steps"], []) + + def test_explicit_sql_cannot_bypass_the_requested_time_window(self): + from queryforge.orchestration.planner import AnalysisPlan + self.time_fixture() + planned = self.fixture.analyze("Show item amount") + plan = AnalysisPlan.model_validate(planned["plan"]) + next(s for s in plan.steps if s.action == "query_metric").inputs["sql"] = ( + "SELECT SUM(items.amount) AS item_amount FROM items LIMIT 100" + ) + payload = self.fixture.analyze("Show item amount for 2024", plan=plan) + self.assertNotEqual(payload["status"], "succeeded") + self.assertIsNone(payload["answer"]) + + def test_yoy_uses_same_month_last_year_not_previous_month(self): + self.time_fixture() + payload = self.fixture.analyze("Show item amount monthly trend year over year") + self.assertEqual(payload["status"], "succeeded") + comparison = next(s["outputs"] for s in payload["steps"] if s["action"] == "compare_periods") + self.assertEqual(comparison["current"], 30.0) + self.assertEqual(comparison["baseline"], 10.0) + self.assertEqual(comparison["percent_change"], 200.0) + self.assertEqual(comparison["comparison_baseline"], "same_period_last_year") + self.assertEqual(payload["final_answer"]["status"], "success") + + def test_missing_yoy_baseline_never_falls_back_to_previous_month(self): + self.time_fixture(("2025-01-01", "2025-02-01", "2025-03-01")) + payload = self.fixture.analyze("Show item amount monthly trend year over year") + self.assertNotEqual(payload["status"], "succeeded") + self.assertTrue(any("baseline" in (s.get("error") or "") for s in payload["steps"])) + + def test_missing_previous_calendar_month_never_uses_last_observed_month(self): + self.time_fixture(("2024-02-01", "2025-01-01", "2025-03-01")) + payload = self.fixture.analyze("Show item amount monthly trend mom") + self.assertNotEqual(payload["status"], "succeeded") + + def test_monthly_grain_aggregates_days_before_comparison(self): + self.time_fixture(("2025-01-01", "2025-01-15", "2025-02-01")) + payload = self.fixture.analyze("Show item amount monthly trend mom") + self.assertEqual(payload["status"], "succeeded") + comparison = next(s["outputs"] for s in payload["steps"] if s["action"] == "compare_periods") + self.assertEqual((comparison["baseline"], comparison["current"]), (30.0, 30.0)) + + def test_quarterly_comparison_crosses_the_year_boundary(self): + self.time_fixture(("2024-07-01", "2024-10-01", "2025-01-01")) + payload = self.fixture.analyze("Show item amount quarterly trend qoq") + self.assertEqual(payload["status"], "succeeded") + comparison = next(s["outputs"] for s in payload["steps"] if s["action"] == "compare_periods") + self.assertEqual(comparison["label"], "2024-Q4 -> 2025-Q1") + self.assertEqual((comparison["baseline"], comparison["current"]), (20.0, 30.0)) + + def test_daily_comparison_crosses_the_year_boundary(self): + self.time_fixture(("2024-12-30", "2024-12-31", "2025-01-01")) + payload = self.fixture.analyze("Show item amount daily trend vs previous day") + self.assertEqual(payload["status"], "succeeded") + comparison = next(s["outputs"] for s in payload["steps"] if s["action"] == "compare_periods") + self.assertEqual(comparison["label"], "2024-12-31 -> 2025-01-01") + self.assertEqual((comparison["baseline"], comparison["current"]), (20.0, 30.0)) + + def test_time_grain_without_governed_time_is_clarified(self): + payload = self.fixture.analyze("Show total amount monthly") + self.assertEqual(payload["status"], "needs_clarification") + self.assertEqual(payload["steps"], []) + + def test_comparison_without_a_calendar_grain_is_clarified(self): + self.time_fixture() + payload = self.fixture.analyze("Show item amount trend 环比") + self.assertEqual(payload["status"], "needs_clarification") + self.assertEqual(payload["steps"], []) + + def test_mom_abbreviation_has_an_explicit_monthly_grain(self): + self.time_fixture(("2025-01-01", "2025-01-15", "2025-02-01")) + payload = self.fixture.analyze("Show item amount mom") + self.assertEqual(payload["status"], "succeeded") + self.assertEqual(payload["analysis_request"]["time_grain"], "monthly") + comparison = next(s["outputs"] for s in payload["steps"] if s["action"] == "compare_periods") + self.assertEqual((comparison["baseline"], comparison["current"]), (30.0, 30.0)) + + def test_bounded_time_series_cannot_claim_to_compare_the_latest_period(self): + self.time_fixture() + with sqlite3.connect(self.fixture.database) as db: + db.executemany( + "INSERT INTO items (item_id, name, category, amount, brand_id, month) VALUES (?, 'item', 'a', 1, 1, ?)", + [(100 + i, f"{2000 + i // 12:04d}-{i % 12 + 1:02d}-01") for i in range(101)], + ) + payload = self.fixture.analyze("Show item amount monthly trend year over year") + self.assertNotEqual(payload["status"], "succeeded") + self.assertTrue(any("bounded series" in (s.get("error") or "") for s in payload["steps"])) + + def test_result_missing_requested_metric_is_never_success(self): + original = QuerySpecCompiler.compile + def omit_metric(**kwargs): + spec = original(**kwargs) + return spec.model_copy(update={"sql": "SELECT SUM(items.amount) AS item_amount FROM items LIMIT 100"}) + with patch.object(QuerySpecCompiler, "compile", side_effect=omit_metric): + payload = self.fixture.analyze("Show item count and total amount") + self.assertNotEqual(payload["status"], "succeeded") + + def test_dropped_or_optional_filter_in_compiled_sql_is_refused(self): + original = QuerySpecCompiler.compile + for where in ("", " WHERE items.item_id = 1 OR items.amount > 0"): + with self.subTest(where=where): + def omit_filter(**kwargs): + spec = original(**kwargs) + return spec.model_copy(update={"sql": f"SELECT SUM(items.amount) AS item_amount FROM items{where} LIMIT 100"}) + with patch.object(QuerySpecCompiler, "compile", side_effect=omit_filter): + payload = self.fixture.analyze("Show total amount where item_id = 1") + self.assertNotEqual(payload["status"], "succeeded") + self.assertTrue(any("mandatory filter" in (s.get("error") or "") for s in payload["steps"])) + + def test_caller_plan_omitting_requested_filters_cannot_complete(self): + from queryforge.orchestration.planner import AnalysisPlan + planned = self.fixture.analyze("Show total amount") + plan = AnalysisPlan.model_validate(planned["plan"]) + payload = self.fixture.analyze("Show total amount where item_id = 1", plan=plan) + self.assertEqual(payload["status"], "blocked") + self.assertIsNone(payload["answer"]) + self.assertTrue(any("request_incomplete: filters" in (s.get("error") or "") for s in payload["steps"])) + + def test_multi_metric_filtered_run_resumes_without_querying_or_spending_again(self): + question = "Show item count and total amount where item_id = 1" + first = self.fixture.analyze(question, run_id="intent-resume") + self.assertEqual(first["status"], "succeeded") + journal = self.fixture.root / ".queryforge/runs/intent-resume/execution.json" + state = json.loads(journal.read_text()) + state.update(status="running", terminal_outcome=None, terminal_at=None) + journal.write_text(json.dumps(state)) + resumed = self.fixture.analyze(question, run_id="intent-resume", resume=True) + self.assertEqual(resumed["status"], "succeeded") + self.assertEqual(resumed["answer"]["values"], {"item_count": 1, "item_amount": 10.0}) + self.assertEqual(set(resumed["reused_steps"]), {"resolve_metric", "check_data_quality", "query_metric", "compose_answer"}) + self.assertEqual(resumed["recomputed_steps"], []) + self.assertEqual(resumed["budgets"]["usage"], first["budgets"]["usage"]) + + def test_cli_filtered_analysis_returns_the_same_number(self): + from queryforge.cli import main + with patch("queryforge.application.analysis_planner.AnalysisPlannerService", return_value=self.fixture.service()): + output = io.StringIO() + with patch("sys.argv", ["queryforge", "--analyze", "--question", "Show total amount where item_id = 1", + "--database", str(self.fixture.database), + "--semantic-model", str(self.fixture.semantic_model)]): + with contextlib.redirect_stdout(output): + code = main() + self.assertEqual(code, 0) + self.assertEqual(json.loads(output.getvalue())["answer"]["value"], 10.0) + + @unittest.skipUnless(importlib.util.find_spec("fastapi") and importlib.util.find_spec("httpx"), "API extras absent") + def test_rest_filtered_multi_metric_analysis_and_clarification(self): + from fastapi.testclient import TestClient + from queryforge.application import AgentService + from queryforge.interfaces.api.app import create_app + config = self.fixture.config() + client = TestClient(create_app(AgentService(config_loader=lambda **_: config))) + response = client.post("/analyze", json={"question": "Show item count and total amount where item_id = 1"}) + self.assertEqual(response.status_code, 200) + self.assertEqual(response.json()["answer"]["values"], {"item_count": 1, "item_amount": 10.0}) + rejected = client.post("/analyze", json={"question": "Show total amount where unknown_column = 1"}) + self.assertEqual(rejected.status_code, 400) + self.assertEqual(rejected.json()["detail"]["status"], "needs_clarification") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_analysis_planner.py b/tests/test_analysis_planner.py index bdde6fa..c0794f1 100644 --- a/tests/test_analysis_planner.py +++ b/tests/test_analysis_planner.py @@ -733,9 +733,12 @@ def test_grouped_report_reuses_the_compiled_query_spec(self): self.assertIn("GROUP BY items.category", value_evidence["payload"]["sql"]) self.assertIsNotNone(value_evidence["payload"]["query_spec"]) - def test_data_absence_triggers_bounded_replan_to_a_legal_dimension(self): + def test_data_absence_replans_but_cannot_complete_a_different_dimension(self): payload = self.fixture.analyze("How many items are there by brand_name?") - self.assertEqual(payload["status"], "succeeded") + self.assertEqual(payload["status"], "blocked") + self.assertIsNone(payload["answer"]) + compose = next(s for s in payload["steps"] if s["action"] == "compose_answer") + self.assertIn("request_incomplete: dimensions", compose["error"]) self.assertEqual(len(payload["replan_reasons"]), 1) self.assertIn("brands.brand_name", payload["replan_reasons"][0]) self.assertIn("items.category", payload["replan_reasons"][0]) @@ -957,7 +960,7 @@ def test_a_single_ordered_time_dimension_still_compares_periods(self): comparison = next( item for item in payload["evidence"] if item["kind"] == "period_comparison" ) - self.assertEqual(comparison["payload"]["label"], "November -> December") + self.assertEqual(comparison["payload"]["label"], "2024-11 -> 2024-12") # Independent oracle: the same two periods computed straight from SQLite. connection = sqlite3.connect(database) diff --git a/tests/test_analysis_semantics.py b/tests/test_analysis_semantics.py new file mode 100644 index 0000000..3703cf9 --- /dev/null +++ b/tests/test_analysis_semantics.py @@ -0,0 +1,577 @@ +"""Phase 2: public analysis results checked against independent populations.""" +from datetime import date +import contextlib +import importlib.util +import io +import json +from pathlib import Path +import sqlite3 +import unittest +from unittest.mock import patch + +import yaml +from pydantic import ValidationError + +from tests.test_analysis_planner import Fixture +from queryforge.core.schemas.models import DateContext, DateRange +from queryforge.domain.semantic import SemanticContractValidator, SemanticModelLoader +from queryforge.domain.semantic.schemas import MetricMatch, SemanticMetric, SemanticModelContext +from queryforge.domain.semantic.sql_validator import QuerySpecCompiler, SemanticSQLValidator +from queryforge.domain.semantic.periods import period_bounds, period_label +from queryforge.domain.semantic.query_constraints import require_filter_predicates, UnsupportedConstraint +from queryforge.infrastructure.db.sqlite_connector import SQLiteConnector + + +class AnalysisSemanticsTest(unittest.TestCase): + def setUp(self): + self.fixture = Fixture() + + def tearDown(self): + self.fixture.cleanup() + + def model(self): + return yaml.safe_load(self.fixture.semantic_model.read_text()) + + def save(self, model): + self.fixture.semantic_model.write_text(yaml.safe_dump(model)) + + def load(self): + with SQLiteConnector(str(self.fixture.database)) as db: + schemas = [db.describe_table(t) for t in db.list_tables()] + return SemanticModelLoader.load_and_validate(self.fixture.semantic_model, schemas, "") + + @staticmethod + def dataset(payload): + return next(s["outputs"] for s in payload["steps"] if s["action"] == "query_metric") + + def cross_fact(self): + with sqlite3.connect(self.fixture.database) as db: + db.executemany("INSERT INTO brands VALUES (?, ?)", [(1, "a"), (2, "b")]) + db.execute("CREATE TABLE charges (id INTEGER PRIMARY KEY, brand_id INTEGER, amount REAL)") + db.executemany("INSERT INTO charges VALUES (?, ?, ?)", [(1, 1, 5), (2, 1, 7), (3, 2, 3)]) + model = self.model() + model["entities"].append({"name": "charges", "table": "charges", "entity_type": "fact", "primary_key": ["id"]}) + model["relationships"].append({"name": "charges_to_brands", "from": "charges.brand_id", "to": "brands.brand_id", "relationship_type": "many_to_one"}) + model["metrics"][1]["allowed_dimensions"].append("brands.brand_name") + model["metrics"][1]["analysis"] = {"unit": "USD", "additivity": "additive"} + model["metrics"].append({"name": "charge_total", "description": "Independent charges.", "entity": "charges", "aggregation": "sum", "expression": "SUM(charges.amount)", "synonyms": ["charge total"], "allowed_dimensions": ["brands.brand_name"], "analysis": {"unit": "USD", "additivity": "additive"}}) + self.save(model) + + def timed(self, days, *, timezone="UTC", fiscal=1, complete=None, start="2024-01-01", strict=False): + with sqlite3.connect(self.fixture.database) as db: + db.execute("ALTER TABLE items ADD COLUMN happened TEXT") + db.execute("ALTER TABLE items ADD COLUMN shipped TEXT") + db.executemany("UPDATE items SET happened=?, shipped='2030-01-01' WHERE item_id=?", [(day, i) for i, day in enumerate(days, 1)]) + model = self.model() + model["entities"][0]["dimensions"].extend([{"name": "event_date", "column": "happened"}, {"name": "ship_date", "column": "shipped"}]) + metric = model["metrics"][1] + metric["time_field"] = "items.happened" + metric["allowed_dimensions"].extend(["items.event_date", "items.ship_date"]) + temporal = {"role": "order_created", "timezone": timezone, "fiscal_year_start_month": fiscal, "require_complete_periods": strict} + if complete: + temporal.update(coverage_start=start, complete_through=complete) + metric["analysis"] = {"unit": "USD", "additivity": "additive", "time": temporal} + self.save(model) + + def ratio(self): + model = self.model() + model["metrics"].append({"name": "mean_amount", "description": "Amount per item.", "entity": "items", "aggregation": "ratio", "ratio": {"numerator": "SUM(items.amount)", "denominator": "COUNT(items.item_id)"}, "allowed_dimensions": ["items.category"], "synonyms": ["mean amount"], "analysis": {"unit": "USD/item", "additivity": "non_additive"}}) + self.save(model) + + def test_cross_fact_scalar_has_no_raw_fact_join(self): + self.cross_fact() + result = self.fixture.analyze("Show item amount and charge total") + self.assertEqual(result["status"], "succeeded") + self.assertEqual(result["answer"]["values"], {"item_amount": 60.0, "charge_total": 15.0}) + self.assertEqual(len(self.dataset(result)["query_spec"]["metric_queries"]), 2) + + def test_cross_fact_shared_grain_matches_independent_totals(self): + self.cross_fact() + result = self.fixture.analyze("Show item amount and charge total by brand_name") + self.assertEqual(result["status"], "succeeded") + dataset = self.dataset(result) + indexes = [0, dataset["columns"].index("item_amount"), dataset["columns"].index("charge_total")] + self.assertEqual([[row[i] for i in indexes] for row in dataset["rows"]], [["a", 40.0, 12.0], ["b", 20.0, 3.0]]) + self.assertTrue(result["answer"]["evidence_ids"]) + + def test_shared_filter_governs_every_fact_branch(self): + self.cross_fact() + result = self.fixture.analyze("Show item amount and charge total where brands.brand_name = 'a'") + self.assertEqual(result["status"], "succeeded") + self.assertEqual(result["answer"]["values"], {"item_amount": 40.0, "charge_total": 12.0}) + dataset = self.dataset(result) + require_filter_predicates(dataset["sql"], dataset["filters"], metric_ctes=dataset["query_spec"]["metric_ctes"]) + broken = dataset["sql"].replace("WHERE (brands.brand_name = 'a')", "", 1) + with self.assertRaises(UnsupportedConstraint): + require_filter_predicates(broken, dataset["filters"], metric_ctes=dataset["query_spec"]["metric_ctes"]) + + def test_cross_fact_local_filter_is_clarified(self): + self.cross_fact() + result = self.fixture.analyze("Show item amount and charge total where amount > 10") + self.assertEqual(result["status"], "needs_clarification") + self.assertEqual(result["steps"], []) + + def test_aggregate_join_validator_rejects_changed_wrapper(self): + self.cross_fact() + context = self.load() + matches = [MetricMatch(metric=m, matched_term=m.name) for m in context.model.metrics if m.name in {"item_amount", "charge_total"}] + spec = QuerySpecCompiler.compile(semantic_model=context, metric_matches=matches, requested_dimensions=["brands.brand_name"]) + validator = SemanticSQLValidator(context, matches, requested_dimensions=["brands.brand_name"]) + self.assertEqual(validator.validate(spec.sql).status, "passed") + cases = [spec.sql.replace(" IS ", " != ", 1), + spec.sql.replace("UNION SELECT", "UNION ALL SELECT"), + spec.sql.replace("SUM(charges.amount)", "COUNT(charges.amount)"), + spec.sql.replace("items.brand_id = brands.brand_id", "items.item_id = brands.brand_id"), + spec.sql.replace("GROUP BY brands.brand_name", "GROUP BY brands.brand_id", 1)] + for sql in cases: + with self.subTest(sql=sql): + self.assertNotEqual(validator.validate(sql).status, "passed") + + def test_aggregate_join_validator_requires_every_default_filter(self): + self.cross_fact() + model = self.model() + model["metrics"][-1]["default_filters"] = ["charges.amount > 3"] + self.save(model) + context = self.load() + matches = [MetricMatch(metric=m, matched_term=m.name) for m in context.model.metrics if m.name in {"item_amount", "charge_total"}] + spec = QuerySpecCompiler.compile(semantic_model=context, metric_matches=matches) + validator = SemanticSQLValidator(context, matches) + self.assertEqual(validator.validate(spec.sql).status, "passed") + self.assertNotEqual(validator.validate(spec.sql.replace("WHERE (charges.amount > 3)", "")).status, "passed") + + def test_aggregate_join_validator_rejects_optional_time_window(self): + import sqlglot + from sqlglot import exp + self.timed(["2024-02-01", "2025-01-01", "2025-02-01"]) + model = self.model() + model["metrics"][0]["time_field"] = "items.happened" + self.save(model) + context = self.load() + matches = [MetricMatch(metric=m, matched_term=m.name) for m in context.model.metrics] + dates = DateContext(reference_date="2025-03-01", source="rule", ranges=[DateRange(expression="February 2025", start_date="2025-02-01", end_date="2025-02-28")]) + spec = QuerySpecCompiler.compile(semantic_model=context, metric_matches=matches, date_context=dates) + validator = SemanticSQLValidator(context, matches, date_context=dates) + self.assertEqual(validator.validate(spec.sql).status, "passed") + tree = sqlglot.parse_one(spec.sql, read="sqlite") + branch = next(tree.find_all(exp.CTE)).this + branch.set("where", exp.Where(this=exp.or_(branch.args["where"].this, exp.EQ(this=exp.Literal.number(1), expression=exp.Literal.number(1))))) + self.assertNotEqual(validator.validate(tree.sql(dialect="sqlite")).status, "passed") + + def test_missing_fact_group_is_not_invented_zero(self): + self.cross_fact() + with sqlite3.connect(self.fixture.database) as db: + db.execute("DELETE FROM charges WHERE brand_id = 2") + result = self.fixture.analyze("Show item amount and charge total by brand_name", max_replans=0) + self.assertNotEqual(result["status"], "succeeded") + self.assertIsNone(result["answer"]) + + def test_duplicate_dimension_keys_fail_runtime_grain_check(self): + self.cross_fact() + with sqlite3.connect(self.fixture.database) as db: + db.execute("ALTER TABLE brands RENAME TO old_brands") + db.execute("CREATE TABLE brands (brand_id INTEGER, brand_name TEXT)") + db.execute("INSERT INTO brands SELECT * FROM old_brands") + db.execute("INSERT INTO brands VALUES (1, 'duplicate')") + result = self.fixture.analyze("Show item amount and charge total by brand_name", max_replans=0) + self.assertNotEqual(result["status"], "succeeded") + self.assertTrue(any("unverified_join_grain" in (s.get("error") or "") for s in result["steps"])) + + def test_many_to_many_dimension_contract_is_rejected(self): + self.cross_fact() + model = self.model() + model["relationships"][1]["relationship_type"] = "many_to_many" + self.save(model) + with self.assertRaisesRegex(ValueError, "fan-out"): + self.load() + + def test_forbidden_dimension_does_not_return_a_total(self): + self.cross_fact() + result = self.fixture.analyze("Show item amount and charge total by category", max_replans=0) + self.assertNotEqual(result["status"], "succeeded") + self.assertIsNone(result["answer"]) + + def test_weighted_ratio_recomputes_components_at_each_grain(self): + self.ratio() + with sqlite3.connect(self.fixture.database) as db: + db.execute("UPDATE items SET amount=100 WHERE item_id=2") + scalar = self.fixture.analyze("Show mean amount") + grouped = self.fixture.analyze("Show mean amount by category") + self.assertEqual(scalar["status"], "succeeded") + self.assertAlmostEqual(scalar["answer"]["value"], 140 / 3) + self.assertEqual(grouped["status"], "succeeded") + self.assertEqual(self.dataset(grouped)["rows"], [["a", 20.0, 40.0, 2], ["b", 100.0, 100.0, 1]]) + self.assertNotAlmostEqual(scalar["answer"]["value"], (20 + 100) / 2) + self.assertFalse(any(s["action"] == "drill_down" for s in grouped["steps"])) + self.assertEqual(scalar["answer"]["metric_contracts"]["mean_amount"]["unit"], "USD/item") + + def test_zero_denominator_cannot_be_successful(self): + self.ratio() + model = self.model() + model["metrics"][-1]["ratio"]["denominator"] = "SUM(items.amount)" + self.save(model) + with sqlite3.connect(self.fixture.database) as db: + db.execute("UPDATE items SET amount=0") + result = self.fixture.analyze("Show mean amount", max_replans=0) + self.assertEqual(result["status"], "partial") + self.assertIsNone(result["answer"]) + + def test_ratio_sql_gate_rejects_wrong_denominator_and_scale(self): + self.ratio() + model = self.model() + model["metrics"][-1]["ratio"]["denominator"] = "COUNT(*)" + self.save(model) + context = self.load() + metric = context.model.metrics[-1] + validator = SemanticSQLValidator(context, [MetricMatch(metric=metric, matched_term=metric.name)]) + correct = "SELECT CAST(SUM(i.amount) AS REAL) / NULLIF(COUNT(*), 0) AS mean_amount FROM items i" + self.assertEqual(validator.validate(correct).status, "passed") + self.assertEqual(validator.validate("SELECT ROUND(CAST(SUM(i.amount) AS REAL) / NULLIF(COUNT(*), 0), 6) AS mean_amount FROM items i").status, "passed") + for expression in ("CAST(SUM(i.amount) AS REAL) / NULLIF(COUNT(i.amount), 0)", + "CAST(COUNT(*) AS REAL) / NULLIF(SUM(i.amount), 0)", + "CAST(SUM(i.amount) AS REAL) * 100 / NULLIF(COUNT(*), 0)", + "ROUND(CAST(SUM(i.amount) AS REAL), 0) / NULLIF(COUNT(*), 0)"): + with self.subTest(expression=expression): + self.assertNotEqual(validator.validate(f"SELECT {expression} AS mean_amount FROM items i").status, "passed") + + def test_avg_equivalence_requires_same_null_population_and_scale(self): + self.ratio() + model = self.model() + model["metrics"][-1]["ratio"].update(denominator="COUNT(*)", scale=100.0) + self.save(model) + context = self.load() + metric = context.model.metrics[-1] + matches = [MetricMatch(metric=metric, matched_term=metric.name)] + sql = "SELECT AVG(i.amount) * 100 AS mean_amount FROM items i" + self.assertNotEqual(SemanticSQLValidator(context, matches).validate(sql).status, "passed") + proven = SemanticSQLValidator(context, matches, non_null_columns={("items", "amount")}) + self.assertEqual(proven.validate(sql).status, "passed") + self.assertEqual(proven.validate("SELECT ROUND(AVG(i.amount) * 100, 4) AS mean_amount FROM items i").status, "passed") + self.assertNotEqual(proven.validate("SELECT AVG(i.amount) AS mean_amount FROM items i").status, "passed") + + def test_nullable_avg_with_count_column_and_derived_aggregates(self): + self.ratio() + model = self.model() + model["metrics"][-1]["ratio"]["denominator"] = "COUNT(items.amount)" + self.save(model) + context = self.load() + metric = context.model.metrics[-1] + validator = SemanticSQLValidator(context, [MetricMatch(metric=metric, matched_term=metric.name)]) + self.assertEqual(validator.validate("SELECT AVG(i.amount) AS mean_amount FROM items i").status, "passed") + wrong = "WITH x AS (SELECT SUM(items.amount) AS amount FROM items GROUP BY category) SELECT AVG(x.amount) AS mean_amount FROM x" + self.assertNotEqual(validator.validate(wrong).status, "passed") + + def test_distinct_count_groups_are_never_summed(self): + model = self.model() + model["metrics"][0]["expression"] = "COUNT(DISTINCT items.brand_id)" + self.save(model) + result = self.fixture.analyze("Show item count by category") + self.assertEqual(result["status"], "succeeded") + self.assertFalse(any(s["action"] == "drill_down" for s in result["steps"])) + self.assertEqual(result["answer"]["metric_contracts"]["item_count"]["additivity"], "non_additive") + + def test_unique_row_count_can_be_added_across_disjoint_groups(self): + model = self.model() + model["metrics"][0]["expression"] = "COUNT(DISTINCT items.item_id)" + self.save(model) + result = self.fixture.analyze("Show item count by category") + self.assertEqual(result["status"], "succeeded") + self.assertEqual(result["answer"]["rows"], [["a", 2], ["b", 1]]) + drill = next(s["outputs"] for s in result["steps"] if s["action"] == "drill_down") + self.assertEqual(drill["total_value"], 3) + self.assertEqual(result["answer"]["metric_contracts"]["item_count"]["additivity_proof"], "unique_row_identity") + + def test_identity_additivity_requires_verified_fact_grain(self): + from queryforge.infrastructure.tools.data_quality_tool import QualityCheckResult + model = self.model() + model["metrics"][0]["expression"] = "COUNT(DISTINCT items.item_id)" + self.save(model) + with patch("queryforge.infrastructure.tools.data_quality_tool.DataQualityTool._grain_check", return_value=QualityCheckResult( + table="items", check="grain_unique", status="warning", reason="bounded_scan_incomplete")): + result = self.fixture.analyze("Show item count by category", max_replans=0) + self.assertNotEqual(result["status"], "succeeded") + self.assertTrue(any("unverified_additivity" in (s.get("error") or "") for s in result["steps"])) + + def test_requested_year_includes_yoy_baseline_automatically(self): + self.timed(["2024-02-01", "2025-01-01", "2025-02-01"]) + result = self.fixture.analyze("Show item amount monthly trend for February 2025 year over year") + self.assertEqual(result["status"], "succeeded") + comparison = next(s["outputs"] for s in result["steps"] if s["action"] == "compare_periods") + self.assertEqual((comparison["current"], comparison["baseline"]), (30.0, 10.0)) + self.assertEqual(comparison["percent_change"], 200.0) + self.assertEqual(len(self.dataset(result)["query_spec"]["query_ranges"]), 2) + + def test_missing_requested_current_never_uses_baseline_as_current(self): + self.timed(["2024-02-01", "2024-03-01", "2025-01-01"]) + result = self.fixture.analyze("Show item amount monthly trend for February 2025 year over year") + self.assertNotEqual(result["status"], "succeeded") + + def test_each_requested_metric_gets_its_own_period_comparison(self): + self.timed(["2024-02-01", "2025-01-01", "2025-02-01"]) + model = self.model() + model["metrics"][0].update(time_field="items.happened", analysis={"unit": "items", "additivity": "additive", "time": {"role": "order_created"}}) + model["metrics"][0]["allowed_dimensions"].append("items.event_date") + self.save(model) + result = self.fixture.analyze("Show item count and item amount monthly trend for February 2025 year over year") + self.assertEqual(result["status"], "succeeded") + comparisons = result["answer"]["comparisons"] + self.assertEqual(set(comparisons), {"item_count", "item_amount"}) + self.assertEqual(comparisons["item_count"]["delta"], 0) + self.assertEqual(comparisons["item_amount"]["delta"], 20.0) + self.assertEqual(result["final_answer"]["status"], "success") + self.assertEqual(next(s["outputs"] for s in result["steps"] if s["action"] == "compose_answer")["validation_problems"], []) + + def test_cross_fact_periods_use_each_metrics_event_role(self): + self.cross_fact() + self.timed(["2024-02-01", "2025-01-01", "2025-02-01"]) + with sqlite3.connect(self.fixture.database) as db: + db.execute("ALTER TABLE charges ADD COLUMN charged TEXT") + db.executemany("UPDATE charges SET charged=? WHERE id=?", [(d, i) for i, d in enumerate(["2024-02-01", "2025-01-01", "2025-02-01"], 1)]) + db.execute("CREATE TABLE calendar (day TEXT PRIMARY KEY, month TEXT)") + db.executemany("INSERT INTO calendar VALUES (?, ?)", [(d, d[:7]) for d in ["2024-02-01", "2025-01-01", "2025-02-01"]]) + model = self.model() + model["entities"].append({"name": "calendar", "table": "calendar", "primary_key": ["day"], "dimensions": [{"name": "month", "column": "month"}]}) + for entity, field in (("items", "happened"), ("charges", "charged")): + model["relationships"].append({"name": entity + "_calendar", "from": entity + "." + field, "to": "calendar.day", "relationship_type": "many_to_one"}) + model["metrics"][1]["allowed_dimensions"].append("calendar.month") + model["metrics"][-1].update(time_field="charges.charged", analysis={"unit": "USD", "additivity": "additive", "time": {"role": "charge_posted"}}) + model["metrics"][-1]["allowed_dimensions"].append("calendar.month") + self.save(model) + result = self.fixture.analyze("Show item amount and charge total monthly trend for February 2025 year over year") + self.assertEqual(result["status"], "succeeded", result["steps"]) + self.assertEqual(result["answer"]["comparisons"]["item_amount"]["delta"], 20.0) + self.assertEqual(result["answer"]["comparisons"]["charge_total"]["delta"], -2.0) + self.assertEqual(result["answer"]["metric_contracts"]["charge_total"]["time"]["role"], "charge_posted") + + def test_bundled_cross_fact_comparison_matches_independent_sql(self): + from queryforge.application.analysis_planner import AnalysisPlannerService + sample = Path(__file__).resolve().parents[1] / "sample_data" / "anime_streaming" + result = AnalysisPlannerService().analyze( + "Show watch hours and average rating monthly trend for February 2025 year over year", + database=str(sample / "anime_streaming.sqlite"), semantic_model_path=str(sample / "semantic_model.yml"), + sql_policy_path=str(sample / "sql_policy.yml")) + self.assertEqual(result["status"], "succeeded", result["steps"]) + with sqlite3.connect(f"file:{sample / 'anime_streaming.sqlite'}?mode=ro", uri=True) as db: + hours = dict(db.execute("SELECT watch_date_key / 100, SUM(watch_seconds)/3600.0 FROM fact_watch_session WHERE watch_date_key / 100 IN (202402,202502) GROUP BY watch_date_key / 100")) + scores = dict(db.execute("SELECT rating_date_key / 100, SUM(score)*1.0/COUNT(*) FROM fact_rating WHERE rating_date_key / 100 IN (202402,202502) GROUP BY rating_date_key / 100")) + for name, oracle in (("watch_hours", hours), ("average_rating", scores)): + comparison = result["answer"]["comparisons"][name] + self.assertAlmostEqual(comparison["baseline"], oracle[202402], places=9) + self.assertAlmostEqual(comparison["current"], oracle[202502], places=9) + self.assertAlmostEqual(comparison["delta"], oracle[202502] - oracle[202402], places=9) + self.assertEqual(result["answer"]["comparisons"]["watch_hours"]["unit"], "hours") + self.assertEqual(result["answer"]["period_completeness"], "complete") + + def test_event_role_and_timestamp_end_day_are_preserved(self): + self.timed(["2025-02-28 23:59:59", "2025-03-01", "2024-02-01"]) + result = self.fixture.analyze("Show item amount for February 2025") + self.assertEqual(result["status"], "succeeded") + self.assertEqual(result["answer"]["value"], 10.0) + self.assertEqual(result["answer"]["metric_contracts"]["item_amount"]["time"]["role"], "order_created") + + def test_fixed_timezone_moves_utc_timestamp_into_local_period(self): + self.timed(["2025-01-31 20:00:00", "2025-02-28 20:00:00", "2024-02-01"], timezone="+08:00") + result = self.fixture.analyze("Show item amount for February 2025") + self.assertEqual(result["status"], "succeeded") + self.assertEqual(result["answer"]["value"], 10.0) + + def test_weekly_monday_buckets_cross_year_correctly(self): + self.timed(["2024-12-23", "2024-12-30", "2025-01-01"]) + result = self.fixture.analyze("Show item amount weekly trend vs previous period") + self.assertEqual(result["status"], "succeeded") + self.assertEqual(self.dataset(result)["rows"], [["2024-12-23", 10.0], ["2024-12-30", 50.0]]) + comparison = next(s["outputs"] for s in result["steps"] if s["action"] == "compare_periods") + self.assertEqual((comparison["baseline"], comparison["current"]), (10.0, 50.0)) + + def test_fiscal_quarter_starts_and_month_end_are_correct(self): + self.timed(["2025-01-31", "2025-03-31", "2025-04-30"], fiscal=4) + result = self.fixture.analyze("Show item amount quarterly trend qoq") + self.assertEqual(result["status"], "succeeded") + self.assertEqual(self.dataset(result)["rows"], [["2025-01-01", 30.0], ["2025-04-01", 30.0]]) + + def test_fiscal_year_recomputes_before_comparison(self): + self.timed(["2024-03-31", "2024-04-01", "2025-04-01"], fiscal=4) + result = self.fixture.analyze("Show item amount yearly trend year over year") + self.assertEqual(result["status"], "succeeded") + self.assertEqual(self.dataset(result)["rows"], [["2023-04-01", 10.0], ["2024-04-01", 20.0], ["2025-04-01", 30.0]]) + + def test_complete_period_contract_allows_full_pair(self): + self.timed(["2024-02-01", "2025-01-01", "2025-02-01"], complete="2025-02-28", strict=True) + result = self.fixture.analyze("Show item amount monthly trend for February 2025 year over year") + self.assertEqual(result["status"], "succeeded") + self.assertEqual(result["answer"]["period_completeness"], "complete") + + def test_incomplete_current_period_is_blocked(self): + self.timed(["2024-02-01", "2025-01-01", "2025-02-01"], complete="2025-02-15", strict=True) + result = self.fixture.analyze("Show item amount monthly trend year over year") + self.assertNotEqual(result["status"], "succeeded") + self.assertTrue(any("incomplete_period" in (s.get("error") or "") for s in result["steps"])) + + def test_scalar_window_crossing_coverage_boundary_is_blocked(self): + self.timed(["2024-02-01", "2025-01-01", "2025-02-01"], complete="2025-02-15", strict=True) + result = self.fixture.analyze("Show item amount for February 2025", max_replans=0) + self.assertNotEqual(result["status"], "succeeded") + self.assertIsNone(result["answer"]) + + def test_semi_additive_time_rollup_is_unsupported(self): + self.timed(["2025-01-01", "2025-01-02", "2025-02-01"]) + model = self.model() + model["metrics"][1]["analysis"].update(additivity="semi_additive", non_additive_dimensions=["items.event_date"]) + self.save(model) + result = self.fixture.analyze("Show item amount monthly trend", max_replans=0) + self.assertNotEqual(result["status"], "succeeded") + + def test_incomplete_baseline_period_is_blocked(self): + self.timed(["2024-02-01", "2025-01-01", "2025-02-01"], complete="2025-02-28", start="2024-02-15", strict=True) + result = self.fixture.analyze("Show item amount monthly trend year over year") + self.assertNotEqual(result["status"], "succeeded") + + def test_missing_period_inside_strict_window_is_blocked(self): + self.timed(["2025-01-01", "2025-03-01", "2025-03-15"], complete="2025-12-31", strict=True) + result = self.fixture.analyze("Show item amount monthly trend for Q1 2025") + self.assertNotEqual(result["status"], "succeeded") + self.assertTrue(any("missing 2025-02" in (s.get("error") or "") for s in result["steps"])) + + def test_leap_day_yoy_has_no_silent_february_28_substitution(self): + self.timed(["2023-02-28", "2024-02-28", "2024-02-29"]) + result = self.fixture.analyze("Show item amount daily trend year over year") + self.assertNotEqual(result["status"], "succeeded") + self.assertTrue(any("leap day" in (s.get("error") or "") for s in result["steps"])) + + def test_unverified_periods_are_explicit_in_answer(self): + self.timed(["2024-02-01", "2025-01-01", "2025-02-01"]) + result = self.fixture.analyze("Show item amount monthly trend year over year") + self.assertEqual(result["status"], "succeeded") + self.assertEqual(result["answer"]["period_completeness"], "unverified") + self.assertTrue(any("completeness" in limitation for limitation in result["answer"]["limitations"])) + + def test_time_contract_publication_rejects_invalid_event_values(self): + self.timed(["bad-date", "2025-01-01", "2025-02-01"]) + report = SemanticContractValidator.validate(self.load().model, self.fixture.database) + self.assertFalse(report.passed) + self.assertEqual(report.blocking_failures[0].rule, "time_values") + + def test_invalid_calendar_day_blocks_publication_and_analysis(self): + self.timed(["2025-02-30", "2025-01-01", "2025-02-01"]) + report = SemanticContractValidator.validate(self.load().model, self.fixture.database) + self.assertFalse(report.passed) + result = self.fixture.analyze("Show item amount for February 2025", max_replans=0) + self.assertNotEqual(result["status"], "succeeded") + self.assertTrue(any("unverified_time_values" in (s.get("error") or "") for s in result["steps"])) + + def test_legacy_models_load_without_new_contracts(self): + loaded = self.load() + self.assertIsNone(loaded.model.metrics[0].analysis) + self.assertNotIn("analysis", loaded.model.metrics[0].model_dump(exclude_none=True)) + + def test_invalid_contracts_fail_authoring(self): + base = self.model()["metrics"][1] + cases = [ + {"unit": "USD", "additivity": "semi_additive"}, + {"unit": "USD", "additivity": "additive", "time": {"role": "created", "timezone": "America/New_York"}}, + {"unit": "USD", "additivity": "additive", "time": {"role": "created", "require_complete_periods": True}}, + {"unit": "USD", "additivity": "additive", "time": {"role": "created", "coverage_start": "2025-01-01", "complete_through": "2024-01-01"}}, + ] + for contract in cases: + with self.subTest(contract=contract), self.assertRaises(ValidationError): + SemanticMetric.model_validate({**base, "analysis": contract}) + + def test_bad_ratio_population_and_wrong_expression_fail_authoring(self): + for numerator in ("SUM(items.amount) / COUNT(items.item_id)", "AVG(items.amount)", "(SELECT SUM(items.amount) FROM items)", "SUM(amount)", "SUM(items.amount); SELECT 1", "SUM(items.amount) -- ignored"): + with self.subTest(numerator=numerator), self.assertRaises(ValidationError): + SemanticMetric.model_validate({"name": "x", "description": "x", "entity": "items", "aggregation": "ratio", "ratio": {"numerator": numerator, "denominator": "COUNT(*)"}}) + with self.assertRaises(ValidationError): + SemanticMetric.model_validate({"name": "x", "description": "x", "entity": "items", "aggregation": "ratio", "expression": "SUM(items.amount) / 2", "ratio": {"numerator": "SUM(items.amount)", "denominator": "COUNT(*)"}}) + + def test_calendar_bounds_include_leap_month_and_fiscal_year(self): + self.assertEqual(period_bounds(date(2024, 2, 15), "monthly"), (date(2024, 2, 1), date(2024, 2, 29))) + self.timed(["2025-01-01", "2025-01-02", "2025-01-03"], fiscal=4) + temporal = self.load().model.metrics[1].analysis.time + self.assertEqual(period_bounds(date(2025, 1, 31), "yearly", temporal), (date(2024, 4, 1), date(2025, 3, 31))) + + def test_changed_time_and_ratio_contracts_are_detected_as_drift(self): + from scripts.check_semantic_drift import semantic_snapshot, compare_snapshots + before, _ = semantic_snapshot(self.fixture.database, self.fixture.semantic_model) + self.ratio() + after, _ = semantic_snapshot(self.fixture.database, self.fixture.semantic_model) + report = compare_snapshots(before, after) + self.assertNotEqual(before["fingerprint"], after["fingerprint"]) + self.assertEqual(report[0]["section"], "metrics") + self.assertEqual(report[0]["added"], ["mean_amount"]) + + def test_changed_units_and_time_roles_are_detected_as_drift(self): + from scripts.check_semantic_drift import semantic_snapshot, compare_snapshots + self.timed(["2025-01-01", "2025-01-02", "2025-01-03"]) + before, _ = semantic_snapshot(self.fixture.database, self.fixture.semantic_model) + model = self.model() + model["metrics"][1]["analysis"]["unit"] = "CNY" + model["metrics"][1]["analysis"]["time"]["role"] = "payment_settled" + self.save(model) + after, _ = semantic_snapshot(self.fixture.database, self.fixture.semantic_model) + self.assertEqual(compare_snapshots(before, after), [{"section": "metrics", "added": [], "removed": [], "changed": ["item_amount"]}]) + + def test_resume_recomputes_when_ratio_contract_changes_at_same_version(self): + self.ratio() + result = self.fixture.analyze("Show mean amount", run_id="ratio-contract") + self.assertEqual(result["answer"]["value"], 20.0) + journal = self.fixture.root / ".queryforge" / "runs" / "ratio-contract" / "execution.json" + state = json.loads(journal.read_text()) + state.update(status="running", terminal_outcome=None, terminal_at=None) + journal.write_text(json.dumps(state)) + model = self.model() + model["metrics"][-1]["ratio"]["scale"] = 100.0 + model["metrics"][-1]["analysis"]["unit"] = "cents/item" + self.save(model) + resumed = self.fixture.analyze("Show mean amount", run_id="ratio-contract", resume=True) + self.assertEqual(resumed["status"], "succeeded") + self.assertEqual(resumed["answer"]["value"], 2000.0) + self.assertEqual(resumed["answer"]["metric_contracts"]["mean_amount"]["unit"], "cents/item") + self.assertIn("query_metric", resumed["recomputed_steps"]) + self.assertEqual(resumed["reused_steps"], []) + + def test_resume_recomputes_when_relative_window_resolves_differently(self): + self.timed(["2024-02-01", "2025-01-01", "2025-02-01"]) + january = DateRange(expression="last month", start_date="2025-01-01", end_date="2025-01-31") + february = DateRange(expression="last month", start_date="2025-02-01", end_date="2025-02-28") + with patch("queryforge.workflow.node.date_parser_node.DateParserNode.parse_rules", return_value=[january]): + first = self.fixture.analyze("Show item amount last month", run_id="relative-contract") + self.assertEqual(first["answer"]["value"], 20.0) + journal = self.fixture.root / ".queryforge" / "runs" / "relative-contract" / "execution.json" + state = json.loads(journal.read_text()) + state.update(status="running", terminal_outcome=None, terminal_at=None) + journal.write_text(json.dumps(state)) + with patch("queryforge.workflow.node.date_parser_node.DateParserNode.parse_rules", return_value=[february]): + resumed = self.fixture.analyze("Show item amount last month", run_id="relative-contract", resume=True) + self.assertEqual(resumed["answer"]["value"], 30.0) + self.assertEqual(resumed["reused_steps"], []) + + def test_cli_ratio_retains_components_and_unit(self): + self.ratio() + from queryforge.cli import main + with patch("queryforge.application.analysis_planner.AnalysisPlannerService", return_value=self.fixture.service()), patch("sys.argv", ["queryforge", "--analyze", "--question", "Show mean amount", + "--database", str(self.fixture.database), "--semantic-model", str(self.fixture.semantic_model)]): + output = io.StringIO() + with contextlib.redirect_stdout(output): + code = main() + self.assertEqual(code, 0) + answer = json.loads(output.getvalue())["answer"] + self.assertEqual(answer["value"], 20.0) + self.assertIn("mean_amount", answer["ratio_components"]) + self.assertEqual(answer["metric_contracts"]["mean_amount"]["unit"], "USD/item") + + @unittest.skipUnless(importlib.util.find_spec("fastapi") and importlib.util.find_spec("httpx"), "API extras absent") + def test_rest_cross_fact_delivery_contains_all_governed_metrics(self): + self.cross_fact() + from fastapi.testclient import TestClient + from queryforge.application import AgentService + from queryforge.interfaces.api.app import create_app + client = TestClient(create_app(AgentService(config_loader=lambda **_: self.fixture.config()))) + response = client.post("/analyze", json={"question": "Show item amount and charge total by brand_name"}) + self.assertEqual(response.status_code, 200) + answer = response.json()["answer"] + self.assertEqual(set(answer["metrics"]), {"item_amount", "charge_total"}) + self.assertEqual(answer["metric_contracts"]["charge_total"]["unit"], "USD") + self.assertTrue(answer["evidence_ids"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_evaluate_sql.py b/tests/test_evaluate_sql.py index e45287e..61788ad 100644 --- a/tests/test_evaluate_sql.py +++ b/tests/test_evaluate_sql.py @@ -500,10 +500,8 @@ def test_semantic_equivalence_is_tolerant_to_column_order(self): # ------------------------------------------------- projection tolerance (D-1) # - # The evaluator compares the columns the two projections share by name, so an - # answer that is correct but projects a different set of columns is no longer - # scored as semantically wrong. The difference is reported instead, as - # extra_columns / missing_columns and as projection_difference_rate. + # Auxiliary reference columns need an explicit task contract. Defaults + # require the full projection; no shared-column-only correctness verdict. # # Regression origin: 8 of the 40 cases in the Step 0 baseline asked only for # anime titles while the gold reference SQL additionally projected @@ -540,6 +538,7 @@ def ask(self, question, options): case["expected_sql"] = ( "SELECT title, studio_name, tier FROM anime WHERE tier = 'Major'" ) + case["result_contract"] = {"required_columns": ["title"]} report = self._run( NarrowProjectionService(), [case], database, root / "assets" ) @@ -576,6 +575,7 @@ def ask(self, question, options): connection.execute("INSERT INTO items VALUES (1, 10.0), (2, 20.0)") case = self._query_case(str(database)) case["expected_sql"] = "SELECT COUNT(*) AS n FROM items" + case["result_contract"] = {"required_columns": ["n"], "allow_extra_columns": True} report = self._run( WideProjectionService(), [case], database, root / "assets" ) diff --git a/tests/test_evaluation_contracts.py b/tests/test_evaluation_contracts.py new file mode 100644 index 0000000..fcc1a22 --- /dev/null +++ b/tests/test_evaluation_contracts.py @@ -0,0 +1,135 @@ +"""Mutation tests: incomplete answers cannot pass a complete task contract.""" +import sqlite3 +import tempfile +import unittest +from pathlib import Path +from types import SimpleNamespace + +from queryforge.evaluation.results import ResultContract, compare_results +from queryforge.evaluation.evaluator import _check_expected_values +from queryforge.evaluation.tasks import TaskSpec +from queryforge.evaluation.isolation import audit_dataset_schemas +from tests.test_evaluate_sql import evaluate_sql +from scripts import benchmark_agent + +ROOT = Path(__file__).resolve().parents[1] + + +class ResultContractTest(unittest.TestCase): + def test_shared_column_cannot_hide_missing_metric(self): + self.assertFalse(compare_results([[2]], ['count'], [[2, 60]], ['count', 'amount'])) + self.assertFalse(compare_results([[2, 9]], ['count', 'other'], [[2, 60]], ['count', 'amount'])) + + def test_column_alignment_preserves_values_inside_rows(self): + self.assertTrue(compare_results([[60, 2]], ['amount', 'count'], [[2, 60]], ['count', 'amount'])) + self.assertFalse(compare_results([[60, 2]], ['count', 'amount'], [[2, 60]], ['count', 'amount'])) + + def test_only_declared_auxiliary_projection_is_tolerated(self): + self.assertFalse(compare_results([[2, 60]], ['count', 'amount'], [[2]], ['count'])) + contract = ResultContract(required_columns=['count'], allow_extra_columns=True) + self.assertTrue(compare_results([[2, 60]], ['count', 'amount'], [[2]], ['count'], contract=contract)) + self.assertTrue(compare_results([[2]], ['count'], [[2, 60]], ['count', 'helper'], + contract=ResultContract(required_columns=['count']))) + + def test_order_is_explicit_and_duplicates_stay_significant(self): + self.assertTrue(compare_results([[2], [1]], ['n'], [[1], [2]], ['n'])) + self.assertFalse(compare_results([[2], [1]], ['n'], [[1], [2]], ['n'], contract=ResultContract(row_order='ordered'))) + self.assertFalse(compare_results([[1], [2]], ['n'], [[1], [1]], ['n'])) + + def test_empty_policy_and_shape_are_checked_even_without_values(self): + self.assertTrue(compare_results([], ['n'], [], ['n'])) + self.assertFalse(compare_results([], None, [], ['n'], positional_aliases=True)) + self.assertFalse(compare_results([], ['n'], [], ['n'], contract=ResultContract(empty='forbid'))) + self.assertFalse(compare_results([], ['wrong'], [], ['n'])) + self.assertFalse(compare_results([[1, 2]], ['n'], [[1]], ['n'])) + self.assertFalse(compare_results([[1, 2]], ['n', 'n'], [[1, 2]], ['n', 'x'])) + + def test_null_boolean_and_nonfinite_values_do_not_pass_as_numbers(self): + for actual, expected in [(True, 1), (False, 0), (None, 0), (float('nan'), float('nan')), (float('inf'), float('inf'))]: + self.assertFalse(compare_results([[actual]], ['n'], [[expected]], ['n'])) + self.assertTrue(compare_results([[None, .3]], ['n', 'v'], [[None, .1 + .2]], ['n', 'v'])) + + def spec(self, **contract): + return TaskSpec(task_id='mutation', split='dev', dataset='test', question='Both measures', + expected_outcome='query', expected_values={'rows': [[2, 60], [3, 70]], 'columns': ['count', 'amount']}, + result_contract=ResultContract(**contract)) + + def test_task_evaluator_honors_named_alignment_and_contract_order(self): + payload = {'columns': ['amount', 'count'], 'rows': [[60, 2], [70, 3]]} + self.assertTrue(_check_expected_values(self.spec(row_order='ordered'), payload).passed) + payload['rows'].reverse() + self.assertFalse(_check_expected_values(self.spec(row_order='ordered'), payload).passed) + self.assertTrue(_check_expected_values(self.spec(), payload).passed) + + def test_task_evaluator_rejects_missing_metric_and_accepts_declared_extra(self): + self.assertFalse(_check_expected_values(self.spec(), {'columns': ['count'], 'rows': [[2], [3]]}).passed) + payload = {'columns': ['count', 'amount', 'helper'], 'rows': [[2, 60, 0], [3, 70, 1]]} + self.assertFalse(_check_expected_values(self.spec(), payload).passed) + self.assertTrue(_check_expected_values(self.spec(allow_extra_columns=True), payload).passed) + + def test_legacy_nested_rows_do_not_permute_cell_positions(self): + spec = self.spec().model_copy(update={'result_contract': None}) + self.assertFalse(_check_expected_values(spec, {'columns': ['count', 'amount'], 'rows': [[60, 2], [70, 3]]}).passed) + + def test_zero_residual_tolerance_must_be_explicit_and_bounded(self): + spec = self.spec().model_copy(update={'result_contract': None, 'expected_values': {'residual': 0}}) + self.assertFalse(_check_expected_values(spec, {'residual': 1e-12}).passed) + spec.values_absolute_tolerance = {'residual': 1e-9} + self.assertTrue(_check_expected_values(spec, {'residual': 1e-12}).passed) + self.assertFalse(_check_expected_values(spec, {'residual': 1e-8}).passed) + + def test_nl2sql_end_to_end_requires_completion_and_reference_order(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + database = root / 'pairs.sqlite' + with sqlite3.connect(database) as db: + db.execute('CREATE TABLE pairs (count INT, amount INT)') + db.execute('INSERT INTO pairs VALUES (2,60), (3,70)') + case = {'id': 'complete', 'domain': 'test', 'category': 'metric', 'expected_outcome': 'query', + 'question': 'Both measures in order', 'database': str(database), + 'expected_sql': 'SELECT count, amount FROM pairs ORDER BY count'} + for status, columns, rows, correct in [ + ('success', ['count', 'amount'], [[2, 60], [3, 70]], True), + ('partial', ['count', 'amount'], [[2, 60], [3, 70]], False), + ('blocked', ['count', 'amount'], [[2, 60], [3, 70]], False), + ('success', ['count'], [[2], [3]], False), + ('success', ['count', 'amount'], [[3, 70], [2, 60]], False), + ]: + with self.subTest(status=status, columns=columns, rows=rows): + service = SimpleNamespace(ask=lambda *args: {'status': status, 'columns': columns, 'rows': rows, 'sql': case['expected_sql']}) + report = evaluate_sql.evaluate_cases([case], service=service, + environment=evaluate_sql.EvaluationEnvironment(root / f'case{status}{len(columns)}{rows[0][0]}'), + default_database=str(database)) + self.assertEqual(report['results'][0]['semantic_correct'], correct) + + +class SchemaIsolationTest(unittest.TestCase): + def test_tool_trace_counts_each_governed_call_inside_a_query_step(self): + spans = [{'kind': 'tool', 'duration_ms': 1, 'attributes': {'step_id': 'query_metric', + 'action': 'query_metric', 'tool': name, 'tool_status': 'succeeded'}} + for name in ('check_data_quality', 'execute_sql', 'execute_sql')] + payload = {'observability': {'spans': spans}, 'steps': [{'action': 'query_metric', 'tool_calls': 3}]} + calls = benchmark_agent._tool_calls_from_payload(payload) + self.assertEqual([c['tool'] for c in calls], ['check_data_quality', 'execute_sql', 'execute_sql']) + self.assertTrue(all(c['ok'] for c in calls)) + + def test_three_existing_schemas_have_independent_signatures(self): + from queryforge.evaluation import load_spec_splits + signatures = audit_dataset_schemas(load_spec_splits(ROOT / 'evaluation/tasks'), benchmark_agent.load_datasets(), ROOT) + self.assertEqual(len(set(signatures.values())), 3) + + def test_renamed_and_copied_dataset_cannot_evade_physical_schema_holdout(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + for name in ('train', 'test'): + with sqlite3.connect(root / f'{name}.sqlite') as db: + db.execute('CREATE TABLE numbers (n INT PRIMARY KEY)') + db.execute('INSERT INTO numbers VALUES (?)', (1 if name == 'train' else 2,)) + datasets = {name: {'database': str(root / f'{name}.sqlite'), 'split_scope': split} + for name, split in [('train', 'dev'), ('test', 'holdout')]} + specs = [SimpleNamespace(dataset=name, split=split) for name, split in [('train', 'dev'), ('test', 'holdout')]] + with self.assertRaisesRegex(ValueError, 'physical schema split leakage'): + audit_dataset_schemas(specs, datasets, root) + specs[1].split = 'dev' + with self.assertRaisesRegex(ValueError, 'split_scope mismatch'): + audit_dataset_schemas(specs, datasets, root) diff --git a/tests/test_local_productization.py b/tests/test_local_productization.py new file mode 100644 index 0000000..1dd7ae4 --- /dev/null +++ b/tests/test_local_productization.py @@ -0,0 +1,106 @@ +"""Local lifecycle, asset version invalidation and optional skill-call budgets.""" +import os +import importlib.util +import tempfile +import time +import unittest +from pathlib import Path +from unittest.mock import patch + +from queryforge.domain.skills import SkillManager, SkillRegistry, SkillRegistryError +from queryforge.infrastructure.storage.report_store import ReportStore +from queryforge.workflow.node.skill_selection_node import SkillSelectionNode +from tests.test_skill_selection_node import StaticSelectorLLM, sample_context + + +class LocalProductizationTest(unittest.TestCase): + def test_simple_count_needs_no_skill_router_call(self): + llm = StaticSelectorLLM(error=AssertionError("No optional skill is relevant")) + context = sample_context("How many rows? Return only n.") + self.assertTrue(SkillSelectionNode(llm, SkillManager()).execute(context).success) + self.assertEqual(llm.calls, 0) + self.assertEqual(context.loaded_skill_names, ["sql_best_practices"]) + self.assertEqual(context.skill_selection_mode, "auto") + self.assertFalse(context.task_context["skill_prefilter"]["router_called"]) + + def test_router_cannot_load_prefiltered_out_skill(self): + llm = StaticSelectorLLM({"skills": ["business_rules", "data_quality_testing"]}) + context = sample_context("Count rows with NULL values") + self.assertTrue(SkillSelectionNode(llm, SkillManager()).execute(context).success) + self.assertEqual(context.loaded_skill_names, ["sql_best_practices", "data_quality_testing"]) + self.assertNotIn('name="business_rules"', llm.prompt) + + def test_content_cache_reuses_same_version_and_invalidates_same_mtime_edit(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory); skill = root / "local_example"; skill.mkdir() + metadata = skill / "skill.yml" + metadata.write_text("name: local_example\ndescription: Local example\nallowed_nodes: [gen_sql]\nenabled: true\npriority: 1\n") + instructions = skill / "SKILL.md"; instructions.write_text("Version one") + manager = SkillManager(SkillRegistry(root)) + first = manager.context_for_node("gen_sql") + self.assertIs(first, manager.context_for_node("gen_sql")) + before = instructions.stat(); instructions.write_text("Version two") + os.utime(instructions, ns=(before.st_atime_ns, before.st_mtime_ns)) + second = manager.context_for_node("gen_sql") + self.assertIsNot(first, second) + self.assertIn("Version two", second.loaded_skills) + before = metadata.stat(); metadata.write_text(metadata.read_text().replace("enabled: true", "enabled: false")) + os.utime(metadata, ns=(before.st_atime_ns, before.st_mtime_ns)) + self.assertEqual(manager.context_for_node("gen_sql").loaded_skill_names, ()) + instructions.unlink() + with self.assertRaises(SkillRegistryError): manager.context_for_node("gen_sql") + + def test_skill_context_cache_separates_nodes_and_explicit_selection(self): + manager = SkillManager() + all_defaults = manager.context_for_node("gen_sql") + self.assertEqual(manager.context_for_node("gen_sql", []).loaded_skill_names, ()) + self.assertNotEqual(all_defaults, manager.context_for_node("reflect")) + self.assertLessEqual(len(manager._context_cache), 32) + + def test_reports_expire_and_cleanup_quarantines_both_files(self): + with tempfile.TemporaryDirectory() as directory: + store = ReportStore(directory, 1) + html, manifest = store.paths("run_old") + html.write_text("old report"); manifest.write_text('{"evidence": "preserved"}') + now = time.time(); os.utime(html, (now - 90000, now - 90000)) + with self.assertRaisesRegex(ValueError, "expired"): store.report_path("run_old", now=now) + self.assertEqual(store.expire(now=now)["expired"], ["run_old"]) + self.assertTrue(html.exists()) + self.assertEqual(store.expire(dry_run=False, now=now)["action"], "quarantined") + self.assertFalse(html.exists()) + retained = list((Path(directory) / ".expired").glob("*/*")) + self.assertEqual({path.name for path in retained}, {"run_old.html", "run_old.manifest.json"}) + self.assertTrue(any("preserved" in path.read_text() for path in retained)) + + def test_report_symlink_and_path_traversal_fail_closed(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory); store = ReportStore(root / "reports") + store.root.mkdir(); secret = root / "outside.html"; secret.write_text("outside") + (store.root / "run.html").symlink_to(secret) + for run_id in ("run", "../outside", "x/y", ""): + with self.subTest(run_id=run_id), self.assertRaises(ValueError): store.report_path(run_id) + self.assertEqual(len(store.expire(dry_run=False)["skipped"]), 1) + self.assertEqual(secret.read_text(), "outside") + + def test_repeated_skill_metadata_is_not_reparsed(self): + registry = SkillRegistry() + with patch.object(registry, "_read_metadata", wraps=registry._read_metadata) as parser: + registry.list_skills(); first_count = parser.call_count + for _ in range(10): registry.list_skills() + self.assertEqual(first_count, 10) + self.assertEqual(parser.call_count, first_count) + + @unittest.skipUnless(importlib.util.find_spec("fastapi"), "FastAPI not installed") + def test_local_api_denies_foreign_origin_before_publication(self): + from fastapi.testclient import TestClient + from queryforge.interfaces.api.app import create_app + from tests.studio_fixture_server import fixture_service + with tempfile.TemporaryDirectory() as directory: + client = TestClient(create_app(fixture_service(Path(directory))), base_url="http://127.0.0.1:8000") + response = client.post("/domains/local_fixture/publish", headers={"Origin": "https://untrusted.example"}) + self.assertEqual(response.status_code, 403) + self.assertIn("Cross-origin", response.json()["detail"]) + # Loopback CLI requests with no browser Origin still reach the + # endpoint's normal contract validation. + response = client.post("/domains/local_fixture/publish") + self.assertEqual(response.status_code, 400) diff --git a/tests/test_paired_benchmark.py b/tests/test_paired_benchmark.py new file mode 100644 index 0000000..7e64355 --- /dev/null +++ b/tests/test_paired_benchmark.py @@ -0,0 +1,157 @@ +"""Pair completeness, environment denominators, uncertainty and isolated execution.""" +import contextlib +import io +import json +import tempfile +import unittest +from pathlib import Path +from datetime import date +from unittest.mock import patch + +from queryforge.evaluation.paired import summarize_pairs +from scripts import run_paired_benchmark as paired +from scripts import benchmark_agent as harness +from scripts import benchmark_runners +from queryforge.evaluation import load_spec_splits + +ROOT = Path(__file__).resolve().parents[1] + + +def observations(repeats=2): + return [dict(task_id=task, dataset='schema' + task, repeat=repeat, arm=arm, + passed=(arm == 'treatment' if task == 'a' else arm == 'baseline'), wall_ms=10, + measured_tokens=None, cost_usd=None, cost_basis=None) + for task in ('a', 'b') for repeat in range(repeats) for arm in ('baseline', 'treatment')] + + +class PairedBenchmarkTest(unittest.TestCase): + def test_repeats_remain_in_task_clusters(self): + short = summarize_pairs(observations(2), repeats=2) + long = summarize_pairs(observations(10), repeats=10) + self.assertEqual(short['accuracy']['delta'], 0) + self.assertEqual(short['accuracy']['ci95'], [-1, 1]) + self.assertEqual(short['accuracy']['ci95'], long['accuracy']['ci95']) + self.assertEqual(long['accuracy']['unique_tasks'], 2) + self.assertEqual(long['total_pairs'], 20) + + def test_environment_failure_excludes_the_entire_pair(self): + records = observations() + records[1]['environment_error'] = True + result = summarize_pairs(records, repeats=2) + self.assertEqual((result['total_pairs'], result['evaluable_pairs']), (4, 3)) + self.assertEqual(result['excluded_environment_pairs'], [{'task_id': 'a', 'repeat': 0, 'arms': ['treatment']}]) + self.assertFalse(result['complete']) + + def test_provider_signature_failure_is_not_model_accuracy(self): + self.assertTrue(paired.provider_contract_error("TypeError: generate_with_messages() got an unexpected keyword argument 'tools'")) + self.assertFalse(paired.provider_contract_error("SQL syntax error near generate_with_messages")) + records = observations() + records[1]['provider_contract_error'] = True + result = summarize_pairs(records, repeats=2) + self.assertEqual(result['evaluable_pairs'], 3) + self.assertEqual(len(result['excluded_provider_contract_pairs']), 1) + self.assertFalse(result['complete']) + + def test_unknown_usage_and_cost_stay_unknown(self): + records = observations() + for r in records: + r.update(estimated_tokens=999, cost_usd=1, cost_basis='unknown') + result = summarize_pairs(records, repeats=2) + self.assertEqual(result['measured_tokens']['pairs'], 0) + self.assertIsNone(result['cost_usd']['delta']) + for r in records: + r.update(measured_tokens=100 if r['arm'] == 'baseline' else 150, cost_basis='priced') + result = summarize_pairs(records, repeats=2) + self.assertEqual(result['measured_tokens']['delta'], 50) + self.assertEqual(result['cost_usd']['delta'], 0) + + def test_missing_duplicate_or_mismatched_pairs_fail_closed(self): + for records, pattern in [(observations()[:-1], 'missing pair'), + ([*observations(), observations()[0]], 'duplicate pair arm')]: + with self.assertRaisesRegex(ValueError, pattern): + summarize_pairs(records, repeats=2) + records = observations() + records[1]['dataset'] = 'different' + with self.assertRaisesRegex(ValueError, 'dataset mismatch'): + summarize_pairs(records, repeats=2) + with self.assertRaisesRegex(ValueError, 'at least two'): + summarize_pairs(observations(), repeats=1) + + def args(self, directory, *extra): + return paired.parse_args(['--report', str(Path(directory) / 'paired.json'), '--repeat', '2', + '--task', 'anime_streaming_dev_1', '--task', 'support_tickets_holdout_1', *extra]) + + def test_dry_run_fixes_inputs_controls_versions_and_balanced_order(self): + with tempfile.TemporaryDirectory() as directory, patch.object(harness, 'run_suite', side_effect=AssertionError('dry run called runtime')): + report = paired.run(self.args(directory, '--dry-run')) + self.assertFalse(report['executed']) + manifest = report['manifest'] + self.assertEqual(manifest['arms']['baseline'], {'parallel_candidates': 1, 'skill_mode': 'auto'}) + self.assertEqual(manifest['arms']['treatment'], {'parallel_candidates': 2, 'skill_mode': 'auto'}) + for task in {s['task_id'] for s in manifest['schedule']}: + orders = [s['order'] for s in manifest['schedule'] if s['task_id'] == task] + self.assertEqual(orders[0], list(reversed(orders[1]))) + self.assertEqual(len(set(manifest['schema_sha256'].values())), 3) + self.assertIn('contracts_sha256', manifest['provenance']) + self.assertIn('sqlglot', manifest['versions']) + + def test_offline_repeated_pairs_close_the_execution_and_evaluation_loop(self): + with tempfile.TemporaryDirectory() as directory: + report = paired.run(self.args(directory)) + self.assertTrue(report['offline_gate_passed'], [(r['task_id'], r['checks']) for r in report['records'] if not r['passed']]) + self.assertEqual(report['summary']['total_pairs'], 4) + self.assertEqual(len(report['records']), 8) + self.assertEqual(report['summary']['accuracy']['delta'], 0) + self.assertIsNone(report['summary']['measured_tokens']['delta']) + roots = [r['raw_trace']['payload'].get('run_id') for r in report['records']] + self.assertEqual(len(set(roots)), len(roots)) + self.assertEqual(report['manifest']['mode'], 'control_flow_only') + + def test_live_manifest_can_be_reviewed_without_api_spend(self): + with tempfile.TemporaryDirectory() as directory, patch.object(harness, 'run_suite', side_effect=AssertionError('model called')): + report = paired.run(self.args(directory, '--tier', '3', '--provider', 'deepseek', '--model', 'deepseek-chat', '--dry-run', '--feature', 'skills')) + self.assertEqual(report['manifest']['arms'], {'baseline': {'parallel_candidates': 1, 'skill_mode': 'off'}, + 'treatment': {'parallel_candidates': 1, 'skill_mode': 'auto'}}) + self.assertEqual(report['manifest']['api_spend'], 'none') + + def test_cli_rejects_offline_provider_and_single_repeat(self): + with tempfile.TemporaryDirectory() as directory, contextlib.redirect_stderr(io.StringIO()): + for extra in (['--provider', 'test'], ['--repeat', '1']): + self.assertEqual(paired.main(['--report', str(Path(directory) / 'fail.json'), *extra]), 2) + + def test_workflow_controls_reach_runner_including_followup_sessions(self): + specs = load_spec_splits(ROOT / 'evaluation/tasks') + spec = next(s for s in specs if s.expected_outcome == 'query' and not getattr(s, 'follow_up_context', None)) + datasets = harness.load_datasets() + ds = {k: str(ROOT / v) if k in {'database', 'semantic_model', 'sql_policy'} else v for k, v in datasets[spec.dataset].items()} + with tempfile.TemporaryDirectory() as directory, patch.object(benchmark_runners, 'WorkflowRunner') as runner: + runner.return_value.run.return_value = {'status': 'success'} + context = harness.BenchmarkContext(datasets, Path(directory), parallel_candidates=3, skill_mode='off') + benchmark_runners.run_workflow_task(spec, ds, context) + kwargs = runner.call_args.kwargs + self.assertEqual((kwargs['parallel_candidates'], kwargs['selected_skills']), (3, [])) + followup = spec.model_copy(update={'follow_up_context': ['warmup']}) + with tempfile.TemporaryDirectory() as directory, patch('queryforge.application.AgentService') as service: + service.return_value.ask.return_value = {'status': 'success'} + context = harness.BenchmarkContext(datasets, Path(directory), parallel_candidates=2, skill_mode='auto') + benchmark_runners.run_workflow_task(followup, ds, context) + options = service.return_value.ask.call_args.args[1] + self.assertEqual(options.parallel_candidates, 2) + self.assertIsNone(options.skills) + self.assertFalse(options.enable_vector_kb) + self.assertEqual(options.vector_top_k, 0) + factory = service.call_args.kwargs['runner_factory'] + self.assertEqual(factory.keywords['today_provider'](), date(2024, 12, 31)) + + def test_followup_replay_uses_frozen_date_in_every_turn(self): + spec = next(s for s in load_spec_splits(ROOT / 'evaluation/tasks') if getattr(s, 'follow_up_context', None)) + datasets = harness.load_datasets() + ds = {k: str(ROOT / v) if k in {'database', 'semantic_model', 'sql_policy'} else v + for k, v in datasets[spec.dataset].items()} + with tempfile.TemporaryDirectory() as directory: + context = harness.BenchmarkContext(datasets, Path(directory), parallel_candidates=1, skill_mode='off') + trace = benchmark_runners.run_workflow_task(spec, ds, context) + self.assertIsNone(trace['error']) + payload = trace['payload'] + for turn in [*payload['previous_turns'], payload]: + self.assertEqual(turn['date_context']['reference_date'], '2024-12-31') diff --git a/tests/test_parallel_candidates.py b/tests/test_parallel_candidates.py index 5fb1f51..78cb393 100644 --- a/tests/test_parallel_candidates.py +++ b/tests/test_parallel_candidates.py @@ -7,6 +7,7 @@ import tempfile import time import unittest +from unittest.mock import patch from pathlib import Path from queryforge.workflow.node.parallel_candidates_node import ParallelCandidatesNode @@ -184,6 +185,49 @@ def test_selector_tie_is_deterministic_and_preview_budget_is_bounded(self): self.assertEqual(result["selected_index"], 0) self.assertEqual(result["evaluations"][1]["status"], "not_previewed") + def test_rejections_and_duplicates_do_not_spend_preview_budget(self): + tool = self.tool() + with patch.object(tool, "execute_sql_preview", wraps=tool.execute_sql_preview) as preview: + result = SQLSelector(tool, max_preview=1).select([ + {"sql": "DROP TABLE items"}, + {"sql": "DROP TABLE items"}, + {"sql": "SELECT name FROM items"}, + {"sql": "SELECT category FROM items"}, + ], self.context()) + self.assertEqual(result["selected_index"], 2) + self.assertEqual(preview.call_count, 1) + self.assertEqual([item["status"] for item in result["evaluations"]], + ["rejected", "duplicate", "eligible", "not_previewed"]) + + def test_cancelled_candidates_do_not_call_model_or_preview(self): + tool = self.tool() + llm = CandidateLLM([]) + with patch.object(llm, "generate_json") as model, patch.object(tool, "execute_sql_preview") as preview: + node = ParallelCandidatesNode(llm, tool, cancel_check=lambda: True) + self.assertFalse(node.execute(self.context()).success) + selection = node._selector_for(4).select([{"sql": "SELECT name FROM items"}], self.context()) + self.assertIsNone(selection["selected_sql"]) + self.assertEqual(selection["preview_status"], "cancelled") + model.assert_not_called() + preview.assert_not_called() + + def test_cancellation_after_preview_discards_winner(self): + tool = self.tool() + cancelled = False + original = tool.execute_sql_preview + + def execute(*args): + nonlocal cancelled + result = original(*args) + cancelled = True + return result + + with patch.object(tool, "execute_sql_preview", side_effect=execute): + result = SQLSelector(tool, cancel_check=lambda: cancelled).select( + [{"sql": "SELECT name FROM items"}], self.context()) + self.assertEqual(result["preview_status"], "cancelled") + self.assertIsNone(result["selected_sql"]) + def test_parallel_node_generates_two_and_records_selection(self): llm = CandidateLLM( [ diff --git a/tests/test_request_contract.py b/tests/test_request_contract.py new file mode 100644 index 0000000..ffdd95c --- /dev/null +++ b/tests/test_request_contract.py @@ -0,0 +1,159 @@ +"""Production request gates, including counterexamples against real SQLite.""" +import unittest +import importlib.util +from contextlib import redirect_stdout, redirect_stderr +from io import StringIO +from unittest.mock import patch + +from queryforge.application import AgentService +from queryforge.core.config import Config +from scripts.benchmark_runners import ScriptedModel + +from queryforge.core.schemas.models import SQLContext +from queryforge.domain.semantic import SemanticModelLoader, SemanticSQLValidator +from queryforge.domain.semantic.request_contract import output_contract, validate_output_contract +from queryforge.workflow.node.execute_sql_node import ExecuteSqlNode +from queryforge.workflow.sql_selector import SQLSelector +from tests.test_semantic_sql_validator import FixtureMixin + + +class RequestContractTest(FixtureMixin, unittest.TestCase): + def test_explicit_labels_and_chinese_followup(self): + for question, columns in ( + ("Count receipts. Return orders and lines, in that order.", ("orders", "lines")), + ("Return a single column named n.", ("n",)), + ("Return only breach_id.", ("breach_id",)), + ("Return region and amount, sorted by region.", ("region", "amount")), + ("仍只返回order_count列。", ("order_count",)), + ("Return net revenue by month", ()), + ): + with self.subTest(question=question): + self.assertEqual(output_contract(question), columns) + + def test_wrong_column_order_and_star_are_rejected(self): + question = "Count receipts. Return orders and lines, in that order." + for sql in ("SELECT 1 AS lines, 2 AS orders", "SELECT * FROM fact_sales", "SELECT 1 AS orders"): + with self.subTest(sql=sql): + self.assertIsNotNone(validate_output_contract(question, sql)) + self.assertIsNone(validate_output_contract(question, "SELECT 1 AS orders, 2 AS lines")) + + def test_output_label_cannot_create_metric_obligation(self): + semantic = self.load_model("Count rows. Return net_sales.") + self.assertEqual(SemanticModelLoader.match_metrics(semantic.model, "Count rows. Return net_sales."), []) + + def test_unused_cte_aggregate_cannot_satisfy_metric(self): + sql = "WITH unused AS (SELECT SUM(amount) AS n FROM fact_sales WHERE is_valid=1) SELECT COUNT(*) FROM fact_sales" + self.assertEqual(self.validate(sql).status, "violation") + + def test_active_cte_unselected_aggregate_cannot_satisfy_metric(self): + sql = "WITH a AS (SELECT SUM(amount) AS value, COUNT(*) AS n FROM fact_sales WHERE is_valid=1) SELECT n FROM a" + self.assertEqual(self.validate(sql).status, "violation") + + def test_selected_derived_and_scalar_aggregates_remain_valid(self): + for sql in ( + "WITH a AS (SELECT SUM(amount) AS value FROM fact_sales WHERE is_valid=1) SELECT value FROM a", + "SELECT (SELECT SUM(amount) FROM fact_sales WHERE is_valid=1) AS value", + ): + with self.subTest(sql=sql): + self.assertEqual(self.validate(sql).status, "passed") + self.assertEqual(self.rows(sql), [[60.0]]) + + def test_distinct_wrong_column_is_rejected(self): + result = self.validate("SELECT COUNT(DISTINCT item_id) FROM fact_sales WHERE is_valid=1", question="valid orders") + self.assertEqual(result.status, "violation") + + def test_count_star_requires_physical_single_nonnull_primary_key(self): + context = self.context("valid orders") + context.relevant_tables = self.schemas + sql = "SELECT COUNT(*) FROM fact_sales WHERE is_valid=1" + self.assertEqual(SemanticSQLValidator.for_context(context).validate(sql).status, "passed") + self.assertEqual(self.rows(sql), [[3]]) + context.relevant_tables = [] + self.assertEqual(SemanticSQLValidator.for_context(context).validate(sql).status, "violation") + + def test_count_star_self_join_cannot_use_uniqueness_proof(self): + context = self.context("valid orders") + context.relevant_tables = self.schemas + sql = "SELECT COUNT(*) FROM fact_sales a JOIN fact_sales b ON a.item_id=b.item_id WHERE a.is_valid=1" + self.assertEqual(SemanticSQLValidator.for_context(context).validate(sql).status, "violation") + + def test_projection_violation_prevents_execution_and_candidate_preview(self): + context = self.context("What are net sales? Return only amount.") + sql = "SELECT SUM(amount) AS wrong FROM fact_sales WHERE is_valid=1" + context.sql_context = SQLContext(sql=sql, explanation="fixture") + tool = self.tool() + self.assertFalse(ExecuteSqlNode(tool).execute(context).success) + self.assertIsNone(context.execution_result) + selection = SQLSelector(tool).select([{"sql": sql}], context) + self.assertIsNone(selection["selected_sql"]) + self.assertFalse(selection["evaluations"][0]["execution_success"]) + + def test_requested_null_predicate_cannot_be_omitted_or_weakened(self): + context = self.context("How many valid orders have NULL item_id? Return only n.") + context.relevant_tables = self.schemas + validator = SemanticSQLValidator.for_context(context) + prefix = "SELECT COUNT(DISTINCT sale_id) AS n FROM fact_sales WHERE is_valid=1" + correct = prefix + " AND item_id IS NULL" + self.assertEqual(validator.validate(correct).status, "passed") + self.assertEqual(self.rows(correct), [[0]]) + for wrong in (prefix, prefix + " AND item_id IS NOT NULL", prefix + " AND (item_id IS NULL OR 1=1)"): + with self.subTest(sql=wrong): + self.assertEqual(validator.validate(wrong).status, "violation") + + def test_detail_identifiers_cannot_be_an_aggregate_alias(self): + question = "List sale identifiers. Return only sale_id." + self.assertIsNone(validate_output_contract(question, "SELECT sale_id FROM fact_sales")) + for sql in ("SELECT COUNT(*) AS sale_id FROM fact_sales", + "WITH x AS (SELECT MAX(sale_id) AS sale_id FROM fact_sales) SELECT sale_id FROM x", + "WITH x AS (SELECT 1 AS sale_id) SELECT sale_id FROM x", + "WITH x AS (SELECT sale_id + 1 AS sale_id FROM fact_sales) SELECT sale_id FROM x", + "SELECT 1 AS sale_id"): + with self.subTest(sql=sql): + self.assertIsNotNone(validate_output_contract(question, sql)) + + def test_longer_metric_phrase_does_not_hide_separately_requested_metric(self): + model = self.load_model("valid orders").model.model_copy(deep=True) + model.metrics[0].synonyms = ["sales"] + model.metrics[1].synonyms = ["valid sales"] + matches = SemanticModelLoader.match_metrics(model, "Show valid sales and sales.") + self.assertEqual({item.metric.name for item in matches}, {"net_sales", "valid_order_count"}) + + def test_unused_grouped_cte_cannot_satisfy_requested_grain(self): + context = self.context("net sales by product category", requested=["item.category"]) + sql = "WITH unused AS (SELECT category FROM dim_item GROUP BY category) SELECT SUM(amount) FROM fact_sales WHERE is_valid=1" + self.assertEqual(SemanticSQLValidator.for_context(context).validate(sql).status, "violation") + + def service(self, sql): + config = Config("scripted", None, "fixture", None, str(self.database), + semantic_model_path=str(self.model_path), + history_db_path=str(self.root / "history.db"), + orchestration_state_root=str(self.root / "runs"), + allowed_database_paths=(str(self.root),)) + return AgentService(config_loader=lambda **_: config, + llm_factory=lambda _: ScriptedModel(sql)) + + @unittest.skipUnless(importlib.util.find_spec("fastapi"), "FastAPI not installed") + def test_rest_projection_gate_rejects_before_sql_execution(self): + from fastapi.testclient import TestClient + from queryforge.interfaces.api.app import create_app + service = self.service("SELECT SUM(amount) AS wrong FROM fact_sales WHERE is_valid=1") + with patch("queryforge.infrastructure.tools.database_tool.DatabaseTool.execute_sql", side_effect=AssertionError("Output violation reached SQL boundary")) as execute: + response = TestClient(create_app(service)).post("/ask", json={ + "question": "What are net sales? Return only amount.", "complexity_mode": "simple"}) + self.assertEqual(response.status_code, 422) + self.assertIn("Output contract", response.json()["detail"]) + execute.assert_not_called() + + def test_cli_projection_gate_rejects_before_sql_execution(self): + import main as cli + service = self.service("SELECT SUM(amount) AS wrong FROM fact_sales WHERE is_valid=1") + error = StringIO() + with patch.object(cli, "AgentService", return_value=service), patch.object(cli, "load_config", service.config_loader), \ + patch("sys.argv", ["queryforge", "--question", "What are net sales? Return only amount.", + "--database", str(self.database), "--semantic-model", str(self.model_path), "--complexity-mode", "simple"]), \ + patch("queryforge.infrastructure.tools.database_tool.DatabaseTool.execute_sql", side_effect=AssertionError("Output violation reached SQL boundary")) as execute, \ + redirect_stdout(StringIO()), redirect_stderr(error): + code = cli.main() + self.assertEqual(code, 1) + self.assertIn("Output contract", error.getvalue()) + execute.assert_not_called() diff --git a/tests/test_run_outcomes.py b/tests/test_run_outcomes.py index 0f3da61..fec5fac 100644 --- a/tests/test_run_outcomes.py +++ b/tests/test_run_outcomes.py @@ -102,11 +102,14 @@ def test_result_status_is_normalised_not_passed_through(self): derive_outcome(result_status="needs_clarification"), "needs_clarification" ) - def test_absent_or_unknown_status_defaults_to_succeeded(self): - """Explicit and testable, rather than an implicit ``or "success"``.""" - self.assertEqual(derive_outcome(), "succeeded") - self.assertEqual(derive_outcome(result_status=None), "succeeded") - self.assertEqual(derive_outcome(result_status="something-new"), "succeeded") + def test_absent_unknown_or_non_terminal_status_fails_closed(self): + for status in (None, "", "running", "something-new"): + with self.subTest(status=status): + self.assertEqual(derive_outcome(result_status=status), "failed") + + def test_unverifiable_results_are_blocked(self): + for status in ("unsupported", "unverified"): + self.assertEqual(derive_outcome(result_status=status), "blocked") if __name__ == "__main__": diff --git a/tests/test_source_contract.py b/tests/test_source_contract.py new file mode 100644 index 0000000..5ddde58 --- /dev/null +++ b/tests/test_source_contract.py @@ -0,0 +1,241 @@ +"""Source contracts reject coincidental values and preserve raw paid evidence.""" +from copy import deepcopy +import json +from pathlib import Path +import unittest + +from pydantic import ValidationError + +from queryforge.evaluation import TaskSpec, TaskTrace, evaluate_task +from queryforge.evaluation.results import ResultContract +from scripts.audit_paired_benchmark import audit_report, digest_json +from scripts.freeze_live_tasks import frozen_tasks + +ROOT = Path(__file__).resolve().parents[1] + + +def fixture_spec(**overrides): + values = dict(task_id='source', split='dev', dataset='fixture', question='Receipt date keys', + expected_outcome='query', expected_values={'rows': [[1, 10]], 'columns': ['first_day', 'last_day']}, + result_contract=ResultContract(required_columns=['first_day', 'last_day']), + answer_must_reference_evidence=False, expected_tables=['fact_order'], + reference_sql='SELECT MIN(date_key) AS first_day,MAX(date_key) AS last_day FROM fact_order') + values.update(overrides) + return TaskSpec(**values) + + +def fixture_trace(sql='SELECT MIN(date_key) AS first_day,MAX(date_key) AS last_day FROM dim_date'): + return TaskTrace(task_id='source', payload={'status': 'success', 'sql': sql, + 'rows': [[1, 10]], 'columns': ['first_day', 'last_day']}, + usage={'total_tokens': 10, 'measured_tokens': 10}, provider='deepseek', model='deepseek-flash') + + +class SourceContractTest(unittest.TestCase): + def test_bad_source_cannot_pass_matching_values(self): + legacy = evaluate_task(fixture_spec(), fixture_trace()) + strict = evaluate_task(fixture_spec(required_sql_tables=['fact_order']), fixture_trace()) + self.assertTrue(legacy.passed) + self.assertTrue(strict.check('expected_values').passed) + self.assertFalse(strict.passed) + self.assertEqual(strict.failure_class, 'unsupported_claim') + self.assertEqual(strict.check('sql_sources').actual['missing_tables'], ['fact_order']) + + def test_correct_source_passes_and_missing_sql_is_unverified(self): + spec = fixture_spec(required_sql_tables=['fact_order']) + correct = fixture_trace(spec.reference_sql) + self.assertTrue(evaluate_task(spec, correct).passed) + correct.payload.pop('sql') + check = evaluate_task(spec, correct).check('sql_sources') + self.assertFalse(check.passed) + self.assertFalse(check.actual['verified']) + self.assertEqual(check.actual['reason'], 'missing_sql') + + def test_legacy_spec_has_no_source_check(self): + self.assertIsNone(evaluate_task(fixture_spec(), fixture_trace()).check('sql_sources')) + + def test_malformed_source_constraints_cannot_silently_disable_check(self): + for value in (None, 'fact_order', [''], [' '], [None], [3], ['fact_order', 'FACT_ORDER'], ['K'], ['main.fact_order']): + with self.subTest(value=value), self.assertRaises(ValidationError): + fixture_spec(required_sql_tables=value) + self.assertEqual(fixture_spec(required_sql_tables=[' FACT_ORDER ']).required_sql_tables, ['fact_order']) + + +class PairedAuditTest(unittest.TestCase): + def fixture(self): + spec = fixture_spec() + trace = fixture_trace() + result = evaluate_task(spec, trace).model_dump() + records = [dict(result, repeat=r, arm=arm, raw_trace=trace.model_dump()) + for r in range(2) for arm in ('baseline', 'treatment')] + manifest = {'provider': 'deepseek', 'model': 'deepseek-flash', 'repeats': 2, 'seed': 17, + 'task_count': 1, 'case_executions': 4, + 'schedule': [{'task_id': 'source', 'repeat': r, 'order': ['baseline', 'treatment']} for r in range(2)], + 'provenance': {'gold_sha256': digest_json([spec.model_dump(exclude={'required_sql_tables'})])}} + report = {'manifest': manifest, 'records': records, 'summary': {'complete': True, 'provenance_stable': True}, + 'final_provenance': manifest['provenance']} + usage = [dict(task_id='source', repeat=r, arm=arm, provider='deepseek', model='deepseek-flash', + at_utc='2026-10-11T09:00:00+00:00', prompt_tokens=6, completion_tokens=4, total_tokens=10, + prompt_cache_hit_tokens=2, prompt_cache_miss_tokens=4) + for r in range(2) for arm in ('baseline', 'treatment')] + prices = {'version': 'test', 'currency': 'CNY', 'provider': 'deepseek', 'model': 'deepseek-flash', + 'valid_from_utc': '2026-10-10T16:00:00+00:00', 'valid_until_utc': '2026-10-11T16:00:00+00:00', + 'input_cache_hit_per_million': .02, 'input_cache_miss_per_million': 1, 'output_per_million': 4} + return report, spec, usage, prices + + def audit(self, report, spec, usage, prices=None): + return audit_report(report, [spec], [fixture_spec(required_sql_tables=['fact_order'])], usage, prices=prices) + + def test_source_rescoring_preserves_original_verdict_and_never_calls_a_model(self): + report, spec, usage, prices = self.fixture() + original = deepcopy(report) + audited = self.audit(report, spec, usage, prices) + self.assertEqual(report, original) + self.assertEqual(audited['audit']['new_model_calls'], 0) + self.assertEqual(len(audited['audit']['newly_rejected_cases']), 4) + self.assertTrue(all(r['original_passed'] and not r['passed'] for r in audited['records'])) + self.assertEqual(audited['summary']['evaluable_pairs'], 2) + self.assertAlmostEqual(audited['audit']['estimated_cost_cny'], 4 * (2 * .02 + 4 + 4 * 4) / 1_000_000) + self.assertIsNone(audited['summary']['cost_usd']['delta']) + + def test_manifest_missing_entire_task_cannot_appear_complete(self): + report, spec, usage, _ = self.fixture() + report['records'] = [] + with self.assertRaisesRegex(ValueError, 'record count'): + self.audit(report, spec, usage) + + def test_tampered_original_verdict_or_token_usage_is_rejected(self): + for mutation, reason in (('verdict', 'verdict'), ('tokens', 'token mismatch')): + report, spec, usage, _ = self.fixture() + if mutation == 'verdict': + report['records'][0]['passed'] = False + else: + usage[0]['total_tokens'] += 1 + with self.subTest(mutation=mutation), self.assertRaisesRegex(ValueError, reason): + self.audit(report, spec, usage) + + def test_question_or_reference_gold_changes_are_rejected(self): + report, spec, usage, _ = self.fixture() + changed = spec.model_copy(update={'question': 'Different question'}) + with self.assertRaisesRegex(ValueError, 'execution gold'): + self.audit(report, changed, usage) + scoring = fixture_spec(question='Different question', required_sql_tables=['fact_order']) + with self.assertRaisesRegex(ValueError, 'model input'): + audit_report(report, [spec], [scoring], usage) + + def test_unknown_cost_remains_unknown_and_wrong_price_window_is_rejected(self): + report, spec, usage, prices = self.fixture() + usage[0]['prompt_cache_hit_tokens'] = None + audited = self.audit(report, spec, usage, prices) + self.assertIsNone(audited['audit']['estimated_cost_cny']) + self.assertIsNone(audited['records'][0]['cost_cny']) + report, spec, usage, prices = self.fixture() + prices['valid_until_utc'] = '2026-10-11T08:00:00+00:00' + with self.assertRaisesRegex(ValueError, 'price window'): + self.audit(report, spec, usage, prices) + + def test_invalid_price_cannot_be_reported_as_measured_cost(self): + for invalid in (True, -1, float('inf'), None): + report, spec, usage, prices = self.fixture() + prices['output_per_million'] = invalid + with self.subTest(invalid=invalid), self.assertRaisesRegex(ValueError, 'price rates'): + self.audit(report, spec, usage, prices) + + def test_timeout_keeps_reported_usage_and_unknown_case_cost_separate(self): + report, spec, usage, prices = self.fixture() + trace = fixture_trace().model_copy(update={ + 'usage': {'total_tokens': 15, 'estimated': True, 'model_calls': 2, 'measured_calls': 1}, + 'model_spans': [ + {'kind': 'model', 'usage': {'prompt_tokens': 6, 'completion_tokens': 4, + 'total_tokens': 10, 'estimated': False}}, + {'kind': 'model', 'usage': {'prompt_tokens': 4, 'completion_tokens': 1, + 'total_tokens': 5, 'estimated': True}}]}) + outcome = evaluate_task(spec, trace).model_dump() + report['records'][0] = dict(outcome, repeat=0, arm='baseline', raw_trace=trace.model_dump()) + original = deepcopy(report) + audited = self.audit(report, spec, usage, prices) + self.assertEqual(report, original) + self.assertEqual(audited['audit']['token_mismatches'], []) + self.assertEqual(audited['audit']['reported_response_tokens'], 40) + self.assertEqual(audited['records'][0]['reported_response_tokens'], 10) + self.assertEqual(audited['records'][0]['measured_tokens'], 0) + self.assertIsNone(audited['records'][0]['cost_cny']) + self.assertIsNone(audited['audit']['estimated_cost_cny']) + self.assertGreater(audited['audit']['reported_response_cost_cny'], 0) + self.assertEqual(audited['audit']['unknown_usage_cases'][0]['unknown_calls'], 1) + usage[0]['completion_tokens'] += 1 + with self.assertRaisesRegex(ValueError, 'token mismatch'): + self.audit(report, spec, usage, prices) + + def test_mixed_usage_without_complete_spans_fails_closed(self): + report, spec, usage, _ = self.fixture() + trace = fixture_trace().model_copy(update={'usage': {'total_tokens': 15, 'estimated': True, + 'model_calls': 2, 'measured_calls': 1}}) + outcome = evaluate_task(spec, trace).model_dump() + report['records'][0] = dict(outcome, repeat=0, arm='baseline', raw_trace=trace.model_dump()) + with self.assertRaisesRegex(ValueError, 'complete model spans'): + self.audit(report, spec, usage) + + def test_sensitivity_exclusion_keeps_primary_results_and_all_raw_records(self): + report, spec, usage, _ = self.fixture() + other = fixture_spec(task_id='other', question='All stored order calendar keys') + trace = fixture_trace(other.reference_sql).model_copy(update={'task_id': 'other'}) + outcome = evaluate_task(other, trace).model_dump() + report['records'] += [dict(outcome, repeat=r, arm=arm, raw_trace=trace.model_dump()) + for r in range(2) for arm in ('baseline', 'treatment')] + report['manifest']['schedule'] += [{'task_id': 'other', 'repeat': r, 'order': ['baseline', 'treatment']} + for r in range(2)] + report['manifest'].update(case_executions=8, task_count=2) + report['manifest']['provenance']['gold_sha256'] = digest_json( + [s.model_dump(exclude={'required_sql_tables'}) for s in (spec, other)]) + usage += [dict(call, task_id='other') for call in list(usage)] + scoring = [fixture_spec(required_sql_tables=['fact_order']), + other.model_copy(update={'required_sql_tables': ['fact_order']})] + audited = audit_report(report, [spec, other], scoring, usage, + excluded_tasks={'source': 'Confirmed question/oracle ambiguity'}) + self.assertEqual(len(audited['records']), 8) + self.assertEqual(audited['summary']['total_pairs'], 4) + self.assertEqual(audited['summary']['accuracy']['baseline_mean'], .5) + self.assertEqual(audited['sensitivity_summary']['total_pairs'], 2) + self.assertEqual(audited['sensitivity_summary']['accuracy']['baseline_mean'], 1) + self.assertEqual(audited['audit']['sensitivity_cost_cny']['pairs'], 0) + with self.assertRaisesRegex(ValueError, 'known task ids'): + audit_report(report, [spec, other], scoring, usage, excluded_tasks={'unknown': 'Bad gold'}) + with self.assertRaisesRegex(ValueError, 'explicit reasons'): + audit_report(report, [spec, other], scoring, usage, excluded_tasks={'source': ''}) + + +class LiveGoldContractTest(unittest.TestCase): + def test_live_v1_remains_byte_identical_to_its_independent_oracles(self): + frozen = frozen_tasks() + for split, text in frozen.items(): + self.assertEqual((ROOT / 'evaluation/live_tasks' / f'{split}.jsonl').read_text(), text) + + def test_source_contract_preserves_model_input_and_reference_values(self): + original, strict = frozen_tasks(), frozen_tasks(source_contract=True) + for split in original: + old = [json.loads(line) for line in original[split].splitlines()] + new = [json.loads(line) for line in strict[split].splitlines()] + self.assertEqual(len(old), len(new)) + for previous, current in zip(old, new): + self.assertEqual(current['required_sql_tables'], previous['expected_tables']) + for key in ('task_id', 'question', 'reference_sql', 'expected_values', 'result_contract'): + self.assertEqual(current[key], previous[key]) + + def test_corrected_future_corpus_disambiguates_all_store_formats(self): + source, corrected = frozen_tasks(source_contract=True), frozen_tasks(corrected_questions=True) + changed = [] + for split in source: + before = [json.loads(line) for line in source[split].splitlines()] + after = [json.loads(line) for line in corrected[split].splitlines()] + for previous, current in zip(before, after): + if previous['question'] != current['question']: + changed.append(current['task_id']) + self.assertIn('regardless of its store_format', current['question']) + self.assertIn('Include all stores', current['question']) + for key in ('reference_sql', 'expected_values', 'result_contract', 'required_sql_tables'): + self.assertEqual(current[key], previous[key]) + self.assertEqual(changed, ['live_retail_orders_regression_4']) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_sql_source_coverage.py b/tests/test_sql_source_coverage.py new file mode 100644 index 0000000..226bc9a --- /dev/null +++ b/tests/test_sql_source_coverage.py @@ -0,0 +1,94 @@ +"""Mutation regressions for independent physical SQL source coverage.""" +import sqlite3 +import unittest + +from queryforge.evaluation.sources import check_sql_sources + + +class SourceCoverageTest(unittest.TestCase): + def test_coincidentally_equal_values_cannot_hide_wrong_source(self): + with sqlite3.connect(":memory:") as db: + db.executescript("CREATE TABLE fact_order (date_key INT);" + "CREATE TABLE dim_date (date_key INT);" + "INSERT INTO fact_order VALUES (1),(10);" + "INSERT INTO dim_date VALUES (1),(5),(10);") + right = "SELECT MIN(date_key), MAX(date_key) FROM fact_order" + wrong = "SELECT MIN(date_key), MAX(date_key) FROM dim_date" + self.assertEqual(db.execute(right).fetchall(), db.execute(wrong).fetchall()) + self.assertTrue(check_sql_sources(right, ["fact_order"]).passed) + result = check_sql_sources(wrong, ["fact_order"]) + self.assertTrue(result.verified) + self.assertFalse(result.passed) + self.assertEqual(result.missing_tables, ("fact_order",)) + db.execute("INSERT INTO dim_date VALUES (20)") + self.assertNotEqual(db.execute(right).fetchall(), db.execute(wrong).fetchall()) + + def test_unused_cte_does_not_establish_a_source(self): + sql = "WITH proof AS (SELECT * FROM fact_order) SELECT * FROM dim_date" + result = check_sql_sources(sql, ["fact_order"]) + self.assertFalse(result.passed) + self.assertEqual(result.active_tables, ("dim_date",)) + + def test_alias_cannot_impersonate_a_physical_source(self): + sql = "SELECT * FROM dim_date AS fact_order" + self.assertFalse(check_sql_sources(sql, ["fact_order"]).passed) + + def test_cte_shadowing_uses_physical_source_with_sqlite_case_rules(self): + sql = 'WITH "fact_order" AS (SELECT * FROM dim_date) SELECT * FROM "FACT_ORDER"' + result = check_sql_sources(sql, ["fact_order"]) + self.assertFalse(result.passed) + self.assertEqual(result.active_tables, ("dim_date",)) + + def test_active_cte_and_derived_table_are_followed(self): + sql = "WITH F AS (SELECT * FROM FACT_ORDER) SELECT * FROM (SELECT * FROM f) t" + self.assertTrue(check_sql_sources(sql, ["fact_order"]).passed) + + def test_scalar_subqueries_cover_both_independent_counts(self): + sql = "SELECT (SELECT COUNT(*) FROM fact_order), (SELECT COUNT(*) FROM fact_order_line)" + self.assertTrue(check_sql_sources(sql, ["fact_order", "fact_order_line"]).passed) + + def test_all_set_operation_branches_are_followed(self): + sql = "SELECT date_key FROM fact_order UNION SELECT date_key FROM dim_date" + self.assertTrue(check_sql_sources(sql, ["fact_order", "dim_date"]).passed) + + def test_main_namespace_and_case_are_supported(self): + self.assertTrue(check_sql_sources('SELECT * FROM main."FACT_ORDER"', ["fact_order"]).passed) + + def test_unsupported_namespaces_are_unverified(self): + for sql in ("SELECT * FROM other.fact_order", "SELECT * FROM temp.fact_order"): + with self.subTest(sql=sql): + result = check_sql_sources(sql, ["fact_order"]) + self.assertFalse(result.verified) + self.assertFalse(result.passed) + + def test_missing_and_invalid_sql_are_unverified(self): + for sql in (None, False, "", "SELECT FROM", "SELECT * FROM fact_order; SELECT 1"): + with self.subTest(sql=sql): + result = check_sql_sources(sql, ["fact_order"]) + self.assertFalse(result.verified) + self.assertFalse(result.passed) + + def test_nonquery_and_unsupported_sources_are_unverified(self): + for sql in ("DELETE FROM fact_order", "SELECT * FROM json_each('[]')", + "SELECT * FROM (VALUES (1)) AS t"): + with self.subTest(sql=sql): + result = check_sql_sources(sql, ["fact_order"]) + self.assertFalse(result.verified) + self.assertFalse(result.passed) + + def test_recursive_cte_is_unverified(self): + sql = "WITH RECURSIVE f AS (SELECT * FROM fact_order UNION ALL SELECT * FROM f) SELECT * FROM f" + self.assertFalse(check_sql_sources(sql, ["fact_order"]).verified) + + def test_unicode_case_folding_cannot_impersonate_a_fixture_table(self): + with sqlite3.connect(":memory:") as db: + db.executescript('CREATE TABLE "K" (n INT); CREATE TABLE k (n INT);' + 'INSERT INTO "K" VALUES (1); INSERT INTO k VALUES (2);') + self.assertNotEqual(db.execute('SELECT n FROM "K"').fetchall(), + db.execute('SELECT n FROM k').fetchall()) + self.assertFalse(check_sql_sources('SELECT n FROM "K"', ['k']).verified) + self.assertFalse(check_sql_sources('SELECT n FROM k', ['K']).verified) + + +if __name__ == "__main__": + unittest.main() diff --git a/web/.env.example b/web/.env.example index 1a48f2c..30a8fd8 100644 --- a/web/.env.example +++ b/web/.env.example @@ -1,2 +1,4 @@ -# Optional: point the same-origin Studio proxy at a running QueryForge API. +# Local single-user Studio: upstream addresses must be HTTP(S) loopback URLs. QUERYFORGE_API_URL=http://127.0.0.1:8000 +# Optional isolated local D1/R2 state directory, useful for acceptance fixtures. +# STUDIO_STATE_DIR=/tmp/queryforge_phase4_studio diff --git a/web/.openai/hosting.json b/web/.openai/hosting.json index 94610ff..69682f2 100644 --- a/web/.openai/hosting.json +++ b/web/.openai/hosting.json @@ -1,5 +1,4 @@ { - "project_id": "appgprj_6a626b7df97c8191bc6290bc34b111fd", "d1": "DB", "r2": "UPLOADS" } diff --git a/web/README.md b/web/README.md index 6dcae8f..9231e48 100644 --- a/web/README.md +++ b/web/README.md @@ -25,8 +25,10 @@ terminal: queryforge --serve-api ``` -If the API uses another address, copy `.env.example` to `.env.local` and change -`QUERYFORGE_API_URL`. +If the API uses another loopback address, copy `.env.example` to `.env.local` and +change `QUERYFORGE_API_URL`. Local Studio rejects remote upstreams and foreign +browser origins. See [the Studio guide](../docs/studio.md) for bounded physical +profiling, actual publication, snapshot expiry and reproducible offline checks. ## Product areas @@ -55,7 +57,8 @@ tests. ## Runtime storage -The hosted build uses Cloudflare-compatible bindings: +Local development persists Cloudflare-compatible bindings through Miniflare. +`STUDIO_STATE_DIR` can isolate disposable test state: - `DB` (D1) stores data domains, source metadata, and domain-scoped run history. - `UPLOADS` (R2) stores files under diff --git a/web/app/api/queryforge/[...path]/route.ts b/web/app/api/queryforge/[...path]/route.ts index 4311498..2796cc3 100644 --- a/web/app/api/queryforge/[...path]/route.ts +++ b/web/app/api/queryforge/[...path]/route.ts @@ -1,4 +1,5 @@ import { requireStudioUser } from "@/app/studio-auth"; +import { localBackendBase } from "@/app/lib/local-boundary"; const ALLOWED_PATHS = new Set([ "health", @@ -37,9 +38,7 @@ function backendUrl(parts: string[]) { if (!isAllowedPath(parts)) { throw new Error("Unsupported QueryForge API route."); } - const base = ( - process.env.QUERYFORGE_API_URL ?? "http://127.0.0.1:8000" - ).replace(/\/+$/, ""); + const base = localBackendBase(process.env.QUERYFORGE_API_URL); return `${base}/${path}`; } @@ -70,7 +69,9 @@ async function proxy( signal: isEventStreamPath(path) ? request.signal : AbortSignal.any([request.signal, AbortSignal.timeout(120_000)]), + redirect: "manual", }); + if (upstream.status >= 300 && upstream.status < 400) throw new Error("Local backend redirects are denied."); const responseHeaders = new Headers(); responseHeaders.set( diff --git a/web/app/api/studio/runs/route.ts b/web/app/api/studio/runs/route.ts index 95a0141..1381039 100644 --- a/web/app/api/studio/runs/route.ts +++ b/web/app/api/studio/runs/route.ts @@ -1,5 +1,6 @@ import { requireStudioUser } from "@/app/studio-auth"; import { ensureStudioSchema, getStudioBindings } from "@/db/runtime"; +import { encodeSnapshot, expiredSnapshot, SNAPSHOT_RETENTION_DAYS } from "@/app/lib/run-snapshot"; const RUN_STATUSES = new Set([ "success", @@ -25,6 +26,15 @@ export async function GET(request: Request) { const includeDemo = url.searchParams.get("include_demo") === "1"; const { db } = getStudioBindings(); await ensureStudioSchema(db); + const runId = url.searchParams.get("run_id"); + if (runId) { + if (!domainId) return Response.json({ detail: "Replay requires a data domain." }, { status: 400 }); + const saved = await db.prepare("SELECT domain_id, output_json, data_version, expires_at FROM studio_runs WHERE id = ? AND domain_id = ?") + .bind(runId, domainId).first<{ domain_id: string; output_json: string | null; data_version: string | null; expires_at: string | null }>(); + if (!saved) return Response.json({ detail: "Run not found in this data domain." }, { status: 404 }); + if (!saved.output_json || expiredSnapshot(saved.expires_at)) return Response.json({ detail: "Run snapshot expired or was not retained." }, { status: 410 }); + return Response.json({ run: JSON.parse(saved.output_json), data_version: saved.data_version }, { headers: { "cache-control": "no-store" } }); + } const conditions: string[] = []; const params: string[] = []; if (domainId) { @@ -37,7 +47,7 @@ export async function GET(request: Request) { const where = conditions.length ? ` WHERE ${conditions.join(" AND ")}` : ""; const statement = db.prepare( `SELECT id, domain_id, question, status, model, row_count, duration, - created_at + created_at, is_demo, data_version FROM studio_runs${where} ORDER BY created_at DESC LIMIT 50`, @@ -71,6 +81,8 @@ export async function POST(request: Request) { rowCount?: number; duration?: string; isDemo?: boolean; + snapshot?: unknown; + dataVersion?: string; }; const domainId = payload.domainId?.trim() ?? ""; const question = payload.question?.trim() ?? ""; @@ -124,6 +136,11 @@ export async function POST(request: Request) { } else { id = crypto.randomUUID(); } + let snapshot: string | null; + try { snapshot = encodeSnapshot(payload.snapshot, id, status); } + catch (error) { return Response.json({ detail: String(error) }, { status: 400 }); } + const dataVersion = (payload.dataVersion ?? "").slice(0, 200); + const expiresAt = snapshot ? new Date(Date.now() + SNAPSHOT_RETENTION_DAYS * 86400_000).toISOString() : null; const { db } = getStudioBindings(); await ensureStudioSchema(db); @@ -141,8 +158,9 @@ export async function POST(request: Request) { await db .prepare( `INSERT INTO studio_runs ( - id, domain_id, question, status, model, row_count, duration, is_demo - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?) + id, domain_id, question, status, model, row_count, duration, is_demo, + output_json, data_version, expires_at + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(id) DO NOTHING`, ) .bind( @@ -154,8 +172,11 @@ export async function POST(request: Request) { payload.rowCount ?? 0, duration, payload.isDemo === true ? 1 : 0, + snapshot, dataVersion, expiresAt, ) .run(); + const saved = await db.prepare("SELECT domain_id FROM studio_runs WHERE id = ?").bind(id).first<{domain_id: string}>(); + if (saved?.domain_id !== domainId) return Response.json({ detail: "Run id already belongs to another data domain." }, { status: 409 }); return Response.json({ status: "saved", id }, { status: 201 }); } catch (error) { return Response.json( diff --git a/web/app/api/studio/upload/route.ts b/web/app/api/studio/upload/route.ts index e4b8584..e4d2498 100644 --- a/web/app/api/studio/upload/route.ts +++ b/web/app/api/studio/upload/route.ts @@ -1,5 +1,7 @@ import { requireStudioUser, studioAuthMode } from "@/app/studio-auth"; import { ensureStudioSchema, getStudioBindings } from "@/db/runtime"; +import { localBackendBase } from "@/app/lib/local-boundary"; +import { parseCsv } from "@/app/lib/source-profile"; const MAX_FILE_BYTES = 25 * 1024 * 1024; // Must match PublishService.ALLOWED_EXTENSIONS in @@ -125,14 +127,6 @@ function referencedColumns(expression: string): string[] { return [...found]; } -function parseCsvHeaderLine(firstLine: string): string[] { - const cleaned = firstLine.replace(/^\uFEFF/, "").trim(); - if (!cleaned) return []; - return cleaned - .split(",") - .map((cell) => cell.trim().replace(/^"([\s\S]*)"$/, "$1")); -} - /** * Reads the first non-empty line of a CSV and checks that the columns named * by the semantic contract (grain, primary key, dimensions, and any bare @@ -144,9 +138,7 @@ async function validateCsvAgainstContract( contract: UploadedSemanticContract, ): Promise { const sample = await file.slice(0, CSV_HEADER_READ_LIMIT).text(); - const firstNonEmptyLine = - sample.split(/\r?\n/).find((line) => line.trim().length > 0) ?? ""; - const header = parseCsvHeaderLine(firstNonEmptyLine); + const header = (parseCsv(sample, file.size > CSV_HEADER_READ_LIMIT, 1)[0] ?? []).map(value => value.trim()); const headerLookup = new Set(header.map((value) => value.toLowerCase())); const missing = new Set(); const requiredColumns = [ @@ -341,7 +333,7 @@ export async function POST(request: Request) { // verdict. CSV files get their header columns checked against the // semantic contract; binary files can only be marked not-verified. const fileValidations: FileValidation[] = []; - let allHeadersPass = true; + let csvHeadersPass = true; for (const file of files) { if (extension(file.name) === "csv") { const missingColumns = await validateCsvAgainstContract( @@ -356,7 +348,7 @@ export async function POST(request: Request) { if (missingColumns.length === 0) { validation.status = "ok"; } else { - allHeadersPass = false; + csvHeadersPass = false; } fileValidations.push(validation); } else { @@ -364,7 +356,8 @@ export async function POST(request: Request) { file: file.name, validation_status: "not_verified_server_side", }); - allHeadersPass = false; + // Binary schema is unknown here. The Python publisher performs the + // physical check; browser/header inspection must not suppress it. } } @@ -392,7 +385,7 @@ export async function POST(request: Request) { new Set(stored.map((file) => extension(file.name).toUpperCase())), ).join(" · "); const contractStatus = - allHeadersPass && form.get("reviewed") === "true" + csvHeadersPass && form.get("reviewed") === "true" ? "reviewed" : "review_pending"; let sourceStatus = "awaiting_validation"; @@ -408,8 +401,8 @@ export async function POST(request: Request) { // stays authoritative for Studio bookkeeping; this result is reported // honestly and never fabricates a pass. let pythonPublish: PythonPublishStatus = { status: "not_attempted" }; - const apiUrl = process.env.QUERYFORGE_API_URL; - if (apiUrl && contractStatus === "reviewed") { + const apiUrl = localBackendBase(process.env.QUERYFORGE_API_URL); + if (contractStatus === "reviewed") { try { const forward = new FormData(); forward.set( @@ -429,6 +422,7 @@ export async function POST(request: Request) { }, body: forward, signal: AbortSignal.timeout(120_000), + redirect: "manual", }, ); type PublishPayload = { diff --git a/web/app/lib/local-boundary.ts b/web/app/lib/local-boundary.ts new file mode 100644 index 0000000..30333b3 --- /dev/null +++ b/web/app/lib/local-boundary.ts @@ -0,0 +1,22 @@ +/** Local single-user Studio boundary; no new identity system. */ +export function isLoopback(hostname: string): boolean { + return ["localhost", "127.0.0.1", "[::1]", "::1"].includes(hostname.toLowerCase()); +} + +export function localRequestError(request: Request): string | null { + const url = new URL(request.url); + if (!isLoopback(url.hostname)) return "Local Studio accepts loopback requests only."; + const origin = request.headers.get("origin"); + if (origin && origin !== url.origin) return "Cross-origin local Studio request denied."; + if (request.headers.get("sec-fetch-site") === "cross-site") return "Cross-site local Studio request denied."; + return null; +} + +export function localBackendBase(value = "http://127.0.0.1:8000"): string { + const url = new URL(value); + if (!isLoopback(url.hostname) || !["http:", "https:"].includes(url.protocol) + || url.username || url.password || url.search || url.hash) { + throw new Error("Local Studio backend must be an HTTP loopback URL without credentials, query or fragment."); + } + return value.replace(/\/+$/, ""); +} diff --git a/web/app/lib/run-snapshot.ts b/web/app/lib/run-snapshot.ts new file mode 100644 index 0000000..8d5acf4 --- /dev/null +++ b/web/app/lib/run-snapshot.ts @@ -0,0 +1,21 @@ +import { normalizeRunStatus, persistableRunStatus, type RunView } from "./run-status"; + +export const SNAPSHOT_RETENTION_DAYS = 30; +export const MAX_SNAPSHOT_BYTES = 2 * 1024 * 1024; + +export function encodeSnapshot(value: unknown, runId: string, status: string): string | null { + if (value == null) return null; + const view = value as Partial; + if (view.runId !== runId || !view.status || persistableRunStatus(view.status) !== status || normalizeRunStatus(view.status) !== view.status + || !["live", "demo"].includes(String(view.provenance)) + || !Array.isArray(view.columns) || !Array.isArray(view.rows)) { + throw new Error("Run snapshot does not match its run id, status or result shape."); + } + const encoded = JSON.stringify(view); + if (new TextEncoder().encode(encoded).length > MAX_SNAPSHOT_BYTES) throw new Error("Run snapshot exceeds 2 MiB."); + return encoded; +} + +export function expiredSnapshot(expiresAt: string | null, now = Date.now()): boolean { + return !expiresAt || !Number.isFinite(Date.parse(expiresAt)) || Date.parse(expiresAt) <= now; +} diff --git a/web/app/lib/source-profile.ts b/web/app/lib/source-profile.ts new file mode 100644 index 0000000..ce29164 --- /dev/null +++ b/web/app/lib/source-profile.ts @@ -0,0 +1,59 @@ +/** Bounded physical CSV inspection; sample findings are never publication verdicts. */ +export type SourceProfile = { + files: number; + sampledRows: number; + warnings: string[]; + columns: Array<{ name: string; type: string; nulls: number }>; +}; + +export function parseCsv(text: string, incomplete = false, maxRows = 1001): string[][] { + const rows: string[][] = []; + let row: string[] = [], cell = "", quoted = false, closedQuote = false; + text = text.replace(/^\uFEFF/, ""); + for (let i = 0; i < text.length; i++) { + const char = text[i]; + if (char === '"') { + if (quoted && text[i + 1] === '"') { cell += '"'; i++; } + else if (quoted) { quoted = false; closedQuote = true; } + else if (!cell && !closedQuote) quoted = true; + else throw new Error("Malformed CSV quoting."); + } else if (char === "," && !quoted) { row.push(cell); cell = ""; closedQuote = false; } + else if ((char === "\n" || char === "\r") && !quoted) { + if (char === "\r" && text[i + 1] === "\n") i++; + row.push(cell); + if (row.some(value => value.length)) rows.push(row); + row = []; cell = ""; closedQuote = false; + if (rows.length >= maxRows) return rows; + } else { + if (closedQuote) throw new Error("Unexpected text after a CSV closing quote."); + cell += char; + } + } + if (quoted && !incomplete) throw new Error("Unclosed CSV quote."); + if (!incomplete && (cell || row.length)) { row.push(cell); rows.push(row); } + return rows; +} + +export async function profileSourceFiles(files: File[]): Promise { + const result: SourceProfile = { files: files.length, sampledRows: 0, warnings: [], columns: [] }; + for (const file of files) { + if (!file.name.toLowerCase().endsWith(".csv")) { + result.warnings.push(`${file.name}: schema not inspected in the browser; publication must validate it.`); + continue; + } + const rows = parseCsv(await file.slice(0, 2 * 1024 * 1024).text(), file.size > 2 * 1024 * 1024); + const header = rows.shift()?.map(value => value.trim()) ?? []; + if (!header.length || header.some(value => !value) || new Set(header.map(value => value.toLowerCase())).size !== header.length) { + throw new Error(`${file.name}: CSV needs non-empty, unique column names.`); + } + if (rows.some(row => row.length !== header.length)) throw new Error(`${file.name}: inconsistent CSV row width.`); + result.sampledRows += rows.length; + if (file.size > 2 * 1024 * 1024 || rows.length >= 1000) result.warnings.push(`${file.name}: bounded sample only.`); + result.columns.push(...header.map((name, index) => { + const values = rows.map(row => row[index]); + const nonempty = values.filter(value => value.trim() !== ""); + return { name, type: nonempty.length && nonempty.every(value => Number.isFinite(Number(value))) ? "NUMBER (sample)" : "TEXT (sample)", nulls: values.length - nonempty.length }; + })); + } + return result; +} diff --git a/web/app/lib/source-status.ts b/web/app/lib/source-status.ts new file mode 100644 index 0000000..80f8535 --- /dev/null +++ b/web/app/lib/source-status.ts @@ -0,0 +1,6 @@ +/** Stored bytes alone are not an executable, validated publication. */ +export function sourceStatus(status: unknown): "Ready" | "Publish failed" | "Awaiting validation" { + if (status === "ready") return "Ready"; + if (status === "publish_failed") return "Publish failed"; + return "Awaiting validation"; +} diff --git a/web/app/page.tsx b/web/app/page.tsx index b052ee2..b96a385 100644 --- a/web/app/page.tsx +++ b/web/app/page.tsx @@ -1,6 +1,8 @@ "use client"; import { publicationOutcome } from "./lib/publication-status"; +import { profileSourceFiles, type SourceProfile } from "./lib/source-profile"; +import { sourceStatus } from "./lib/source-status"; import { ChangeEvent, @@ -92,7 +94,7 @@ type UploadedSource = { size: string; tables: number; rows: string; - status: "Ready" | "Draft"; + status: "Ready" | "Publish failed" | "Awaiting validation"; }; type DataDomain = { @@ -118,7 +120,7 @@ type SemanticDraft = { metrics: Array<{ name: string; description: string; - aggregation: "count" | "sum"; + aggregation: "count" | "sum" | "ratio"; expression: string; }>; }; @@ -138,13 +140,13 @@ const INITIAL_SEMANTIC_DRAFT: SemanticDraft = { name: "uploaded_record_count", description: "Count of reviewed records at the declared grain.", aggregation: "count", - expression: "COUNT(*)", + expression: "COUNT(DISTINCT uploaded_record.record_id)", }, { name: "uploaded_amount_sum", description: "Sum of the profiled amount field in source-native units.", aggregation: "sum", - expression: "SUM(amount)", + expression: "SUM(uploaded_record.amount)", }, ], }; @@ -636,9 +638,6 @@ const EXAMPLE_QUESTIONS = [ "Which anime drive both engagement and merch GMV?", ]; -const sleep = (duration: number) => - new Promise((resolve) => window.setTimeout(resolve, duration)); - function cn(...classes: Array) { return classes.filter(Boolean).join(" "); } @@ -754,12 +753,14 @@ const EMPTY_LIVE_RESULT: QueryResult = { }; /** The governed request both transports send; the body is not transport-specific. */ -function queryRequestBody(question: string): Record { +function queryRequestBody(question: string, domain?: DataDomain): Record { return { question, + ...(domain && !domain.isSample ? { domain_id: domain.id } : { database: "sample_data/anime_streaming/anime_streaming.sqlite", semantic_model_path: "sample_data/anime_streaming/semantic_model.yml", sql_policy_path: "sample_data/anime_streaming/sql_policy.yml", + }), visualize: true, report: true, complexity_mode: "auto", @@ -833,6 +834,7 @@ export default function Home() { const [useStreaming, setUseStreaming] = useState(true); const [streamState, setStreamState] = useState(null); const streamAbortRef = useRef(null); + const selectionEpochRef = useRef(0); const [result, setResult] = useState(DEMO_RESULT); const [runs, setRuns] = useState(INITIAL_RUNS); const [selectedEntity, setSelectedEntity] = useState("watch_session"); @@ -848,6 +850,7 @@ export default function Home() { const [uploadStep, setUploadStep] = useState(1); const [uploadFiles, setUploadFiles] = useState([]); const [isProfiling, setIsProfiling] = useState(false); + const [sourceProfile, setSourceProfile] = useState(null); const [semanticReviewed, setSemanticReviewed] = useState(false); const [semanticValidated, setSemanticValidated] = useState(false); const [semanticDraft, setSemanticDraft] = useState( @@ -931,8 +934,8 @@ export default function Home() { type: String(source.source_type ?? "DATA"), size: formatBytes(Number(source.size_bytes ?? 0)), tables: Number(source.table_count ?? 1), - rows: "Profiled", - status: "Ready" as const, + rows: "Not retained", + status: sourceStatus(source.status), })); if (persisted.length) setUploadedSources(persisted); }) @@ -1025,7 +1028,7 @@ export default function Home() { try { const state = await consumeAskStream({ url: "/api/queryforge/ask/stream", - body: queryRequestBody(submitted), + body: queryRequestBody(submitted, activeDomain), signal: controller.signal, // React needs a fresh object per frame; the consumed state is mutated in // place so the copy also snapshots the frame list. @@ -1046,7 +1049,7 @@ export default function Home() { async function runQuery(nextQuestion?: string) { const submitted = (nextQuestion ?? query).trim(); if (!submitted || isRunning) return; - if (!activeDomain.isSample) { + if (!activeDomain.isSample && (activeDomain.status !== "ready" || connection !== "live")) { setActiveView("ask"); setToast( activeDomainSources.length @@ -1056,6 +1059,7 @@ export default function Home() { return; } + selectionEpochRef.current++; setQuery(submitted); setActiveView("ask"); setIsRunning(true); @@ -1078,7 +1082,7 @@ export default function Home() { const response = await fetch("/api/queryforge/ask", { method: "POST", headers: { "content-type": "application/json" }, - body: JSON.stringify(queryRequestBody(submitted)), + body: JSON.stringify(queryRequestBody(submitted, activeDomain)), }); setRunStage(2); let payload: unknown = null; @@ -1123,6 +1127,9 @@ export default function Home() { nextResult = { ...DEMO_RESULT, provenance: "demo" }; } + const persistedRunId = /^(qf_[a-f0-9]{32}|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i.test(nextResult.runId) + ? nextResult.runId : `qf_${crypto.randomUUID().replaceAll("-", "")}`; + nextResult = { ...nextResult, runId: persistedRunId }; setRunStage(4); setResult(nextResult); setRuns((current) => [ @@ -1139,11 +1146,6 @@ export default function Home() { }, ...current.filter((item) => item.id !== nextResult.runId), ]); - const persistedRunId = /^(qf_[a-f0-9]{32}|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i.test( - nextResult.runId, - ) - ? nextResult.runId - : `qf_${crypto.randomUUID().replaceAll("-", "")}`; void fetch("/api/studio/runs", { method: "POST", headers: { "content-type": "application/json" }, @@ -1157,8 +1159,17 @@ export default function Home() { rowCount: nextResult.rowCount, duration: provenance === "live" ? "live" : "1.84s", isDemo: provenance === "demo", + snapshot: { ...nextResult, runId: persistedRunId }, + dataVersion: String((nextResult.output?.domain as Record | undefined)?.data_version ?? ""), }), - }).catch(() => undefined); + }).then(async response => { + if (!response.ok) { + const body = await response.json().catch(() => null) as { detail?: string } | null; + throw new Error(body?.detail ?? `History storage returned ${response.status}.`); + } + }).catch(error => { + setToast(`Query result is available, but history was not saved: ${error instanceof Error ? error.message : String(error)}`); + }); setIsRunning(false); if (isFailureStatus(nextResult.status)) { setToast(`${statusLabel(nextResult.status)} — ${nextResult.detail}`); @@ -1206,6 +1217,7 @@ export default function Home() { const files = Array.from(event.target.files ?? []); if (!files.length) return; setUploadFiles(files); + setSourceProfile(null); setSemanticReviewed(false); setSemanticValidated(false); setSemanticDraft({ @@ -1218,9 +1230,15 @@ export default function Home() { async function profileFiles() { if (!uploadFiles.length) return; setIsProfiling(true); - await sleep(900); - setIsProfiling(false); - setUploadStep(2); + try { + const profile = await profileSourceFiles(uploadFiles); + setSourceProfile(profile); + setUploadStep(2); + } catch (error) { + setToast(error instanceof Error ? error.message : "Could not inspect the source files."); + } finally { + setIsProfiling(false); + } } async function validateUploadSemantic() { @@ -1236,16 +1254,15 @@ export default function Home() { semanticDraft.metrics.length > 0 && semanticDraft.metrics.every( (metric) => - metric.name && metric.description && metric.expression, + metric.name.trim() && metric.description.trim() && metric.expression.trim(), ); - if (requiredFields.some((value) => !value.trim()) || !metricsValid) { + if (requiredFields.some((value) => !value.trim()) || !metricsValid || !semanticDraft.dimensions.length || semanticDraft.dimensions.some(value => !value.trim())) { setSemanticValidated(false); setToast("Complete the entity, grain, owner, and metric contract first."); return; } - await sleep(500); setSemanticValidated(true); - setToast("Semantic contract passed all blocking checks."); + setToast("Draft fields checked. Publication will verify the physical and semantic contracts."); } async function publishUpload() { @@ -1322,13 +1339,36 @@ export default function Home() { setToast(publication.detail); } - function selectRun(run: RunRecord) { + async function selectRun(run: RunRecord) { + if (isRunning) { setToast("Cancel or finish the current run before replaying history."); return; } + const epoch = ++selectionEpochRef.current; setActiveDomainId(run.domainId); setQuery(run.question); setActiveView("ask"); + if (run.isDemo) { + setResult(DEMO_RESULT); + setToast("Offline demo selected."); + return; + } + try { + const response = await fetch(`/api/studio/runs?run_id=${encodeURIComponent(run.id)}&domain_id=${encodeURIComponent(run.domainId)}`); + const payload = await response.json() as { run: QueryResult; detail?: string; data_version?: string }; + if (!response.ok) throw new Error(payload.detail ?? "Saved run unavailable."); + if (epoch !== selectionEpochRef.current) return; + setResult(payload.run); + setStreamState(null); + setToast(`Saved run replayed${payload.data_version ? ` · data version ${payload.data_version}` : ""}.`); + } catch (error) { + if (epoch !== selectionEpochRef.current) return; + setResult({ ...EMPTY_LIVE_RESULT, runId: run.id, status: "failed", detail: error instanceof Error ? error.message : "Saved run unavailable." }); + } } function selectDomain(domain: DataDomain, view: View = "overview") { + if (isRunning) { setToast("Cancel or finish the current run before switching data domains."); return; } + selectionEpochRef.current++; + setResult(EMPTY_LIVE_RESULT); + setStreamState(null); setActiveDomainId(domain.id); setDomainMenuOpen(false); setActiveView(view); @@ -1345,6 +1385,7 @@ export default function Home() { description: string; owner: string; }) { + if (isRunning) { setToast("Cancel or finish the current run before creating a data domain."); return; } let created: DataDomain = { id: `domain_${crypto.randomUUID().replaceAll("-", "")}`, name: input.name, @@ -1368,13 +1409,16 @@ export default function Home() { ownerEmail: chatgptUserEmail() ?? undefined, }), }); - if (response.ok) { - const payload = (await response.json()) as { domain: DataDomain }; - created = payload.domain; - } - } catch { - // Keep the complete workflow available in local demo mode. + const payload = (await response.json()) as { domain?: DataDomain; detail?: string }; + if (!response.ok || !payload.domain) throw new Error(payload.detail ?? "Data domain storage unavailable."); + created = payload.domain; + } catch (error) { + setToast(error instanceof Error ? error.message : "Could not save the data domain."); + return; } + selectionEpochRef.current++; + setResult(EMPTY_LIVE_RESULT); + setStreamState(null); setDomains((current) => [...current, created]); setActiveDomainId(created.id); setCreateDomainOpen(false); @@ -1441,16 +1485,16 @@ export default function Home() {

- Semantic coverage - {activeDomain.isSample ? "100%" : activeDomain.sourceCount ? "Draft" : "0%"} + {activeDomain.isSample ? "Semantic coverage" : "Publication"} + {activeDomain.isSample ? "100%" : activeDomain.status === "ready" ? "Ready" : "Draft"}
@@ -1600,6 +1644,7 @@ export default function Home() { runQuery={runQuery} openSources={() => setActiveView("sources")} openSemantic={() => setActiveView("semantic")} + openAsk={() => setActiveView("ask")} openRuns={() => setActiveView("runs")} connection={connection} runs={activeDomainRuns} @@ -1671,6 +1716,7 @@ export default function Home() { step={uploadStep} files={uploadFiles} isProfiling={isProfiling} + sourceProfile={sourceProfile} reviewed={semanticReviewed} validated={semanticValidated} semanticDraft={semanticDraft} @@ -1804,15 +1850,15 @@ function DomainsView({ Sources - {domain.isSample ? 15 : sourceCount ? 1 : 0} + {domain.isSample ? 15 : "—"} Entities - {domain.isSample ? 11 : 0} + {domain.isSample ? 11 : "—"} Metrics - {domain.isSample ? "82/82" : sourceCount ? "Draft" : "—"} + {domain.isSample ? "82/82" : domain.status === "ready" ? "Published" : "Draft"} Contract
@@ -1854,6 +1900,7 @@ function OverviewView({ runQuery, openSources, openSemantic, + openAsk, openRuns, connection, runs, @@ -1864,6 +1911,7 @@ function OverviewView({ runQuery: (value?: string) => Promise; openSources: () => void; openSemantic: () => void; + openAsk: () => void; openRuns: () => void; connection: ConnectionState; runs: RunRecord[]; @@ -1883,12 +1931,11 @@ function OverviewView({

This domain is isolated from every other business context. - Complete the source and semantic contract steps to activate - governed analysis. + {domain.status === "ready" ? "Its published data and semantic contract are ready for governed analysis." : "Complete the source and semantic contract steps to activate governed analysis."}

-
@@ -2335,7 +2382,7 @@ function SourcesView({ {domain.isSample ? "Connect another source" : "Add the first domain source"} -

SQLite, CSV, or Parquet

+

CSV or Parquet

SEMANTICS REQUIRED @@ -2376,7 +2423,7 @@ function SourcesView({ {source.type} · {source.size} - {source.status} + {source.status} ))} @@ -3100,7 +3147,7 @@ function AskView({ selectRun: (run: RunRecord) => void; connection: ConnectionState; }) { - if (!domain.isSample) { + if (!domain.isSample && domain.status !== "ready") { return (
fileInputRef.current?.click()} > ↑ - Drop SQLite, CSV, or Parquet files here + Drop CSV or Parquet files here

or click to browse · up to 25 MB per file

Choose files @@ -3996,10 +4045,10 @@ function UploadModal({
✓
- Physical profile complete + Source sample inspected

- QueryForge inferred a draft only. Business definitions still - require human review. + CSV fields and bounded sample values are shown below. Keys and + business definitions require review; publication performs full validation.

@@ -4009,16 +4058,16 @@ function UploadModal({ {Math.max(files.length, 1)}
- Candidate grain - record_id + Sample rows + {sourceProfile?.sampledRows ?? 0}
- Dimensions - 7 + Observed columns + {sourceProfile?.columns.length ?? 0}
Quality warnings - 2 + {sourceProfile?.warnings.length ?? 0}
@@ -4028,19 +4077,15 @@ function UploadModal({ Semantic role Quality
- {[ - ["record_id", "INTEGER", "Primary key", "Unique"], - ["entity_id", "INTEGER", "Entity key", "99.9%"], - ["recorded_at", "TIMESTAMP", "Time dimension", "100%"], - ["amount", "DECIMAL", "Candidate measure", "2 outliers"], - ].map((row) => ( -
- {row.map((cell, index) => ( + {(sourceProfile?.columns ?? []).map((column, rowIndex) => ( +
+ {[column.name, column.type, "Unreviewed", `${column.nulls} empty in sample`].map((cell, index) => ( {cell} ))}
))}
+ {sourceProfile?.warnings.map(warning =>

{warning}

)}
-
- Quality rules - 6 -
- {semanticDraft.metrics.map((metric) => ( - {metric.name} - ))} + +

Review every metric. Expressions must use qualified table.column references; the publication table is derived from the business entity name.

+ {semanticDraft.metrics.map((metric, index) => ( +
+ Metric {index + 1} + {(["name", "description", "expression"] as const).map(field => ( + + ))} + + +
+ ))} +