diff --git a/.gitignore b/.gitignore index 5cd4400..cbc5eb1 100644 --- a/.gitignore +++ b/.gitignore @@ -24,8 +24,5 @@ Thumbs.db *.sqlite-wal *.build.json semantic-weekly-report.json -# Generated benchmark reports: raw JSON is regenerable, so it is not tracked. -# The summarized, versioned evidence lives in docs/optimization/baselines.md -# (the comment here previously pointed at docs/optimization/step-16-acceptance.md, -# which does not exist in the repository). +# Generated benchmark reports; regenerate with scripts/benchmark_agent.py. evaluation/reports/ diff --git a/AGENTS.md b/AGENTS.md index b3942ee..0702a63 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -131,6 +131,6 @@ the relevant area. | Configuration / env vars | `docs/configuration.md` | | Semantic model authoring | `docs/semantic_authoring.md`, `docs/semantic_contracts.md` | | REST / MCP surfaces | `docs/api_reference.md`, `docs/mcp_server.md` | -| Evaluation method + frozen numbers | `docs/nl2sql_evaluation.md` | +| Evaluation method + benchmark commands | `docs/nl2sql_evaluation.md` | | Database backends | `docs/database_adapters.md` | -| Release process | `docs/github_release.md` | +| Development checks | `docs/README.md` | diff --git a/README.md b/README.md index 71b9254..fbef39d 100644 --- a/README.md +++ b/README.md @@ -400,7 +400,7 @@ make web-check # Studio lint, types, build and tests ``` Evaluation separates deterministic governance checks from real-model behaviour. -See the [evaluation guide](docs/nl2sql_evaluation.md) for methods, results and limits. +See the [evaluation guide](docs/nl2sql_evaluation.md) for benchmark commands and result interpretation. ## Documentation @@ -417,7 +417,6 @@ See the [evaluation guide](docs/nl2sql_evaluation.md) for methods, results and l | Evaluation | [NL2SQL evaluation](docs/nl2sql_evaluation.md) | | Reports | [Report artifacts](docs/report_artifact.md) | | Subject scoping | [Subject tree](docs/subject_tree.md) | -| GitHub release | [First-publish checklist](docs/github_release.md) | | Documentation index | [All guides](docs/README.md) | ## Contributing and Security diff --git a/README.zh-CN.md b/README.zh-CN.md index de4489d..30ca425 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -381,7 +381,7 @@ make semantic-check # 语义模型漂移 make web-check # Studio lint、类型、构建与测试 ``` -评测区分确定性治理测试和真实模型表现,方法、结果与限制见 +评测区分确定性治理测试和真实模型表现,运行方法与结果解读见 [评测文档](docs/nl2sql_evaluation.md)。 ## 项目文档 @@ -399,7 +399,6 @@ make web-check # Studio lint、类型、构建与测试 | 评测 | [NL2SQL 评测](docs/nl2sql_evaluation.md) | | 报告 | [报告产物](docs/report_artifact.md) | | 主题域裁剪 | [Subject Tree](docs/subject_tree.md) | -| GitHub 发布 | [首次发布清单](docs/github_release.md) | | 文档索引 | [全部指南](docs/README.md) | ## 贡献与安全 diff --git a/docs/README.md b/docs/README.md index 08b1157..cddce04 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,6 +1,7 @@ # QueryForge Documentation -Start with whatever matches what you are trying to do. +Installation and quick-start commands are in the [project README](../README.md#quick-start). +Use the guides below for your next task. ## Start Here @@ -19,8 +20,6 @@ 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 @@ -29,9 +28,17 @@ Start with whatever matches what you are trying to do. ## Evaluation -- [NL2SQL evaluation](nl2sql_evaluation.md) — gold sets, metrics, tiers, how to reproduce a run -- [End-to-end acceptance demos](demo/README.md) — runnable scenarios, no API key required +- [Evaluation guide](nl2sql_evaluation.md) — offline checks, model benchmarks and result contracts +- [Runnable examples](demo/README.md) — data publication, analysis and recovery without an API key -## Contributing +## Development Checks -- [GitHub release checklist](github_release.md) +Run from the repository root after installing the development dependencies: + +```bash +./init.sh # environment and offline tests +make check # repository hygiene and offline acceptance +make semantic-check # sample semantic-model drift +make web-check # Studio lint, types, build and tests +make package # Python source and wheel distributions +``` diff --git a/docs/agent_team_architecture.md b/docs/agent_team_architecture.md index 4444a97..fa7f3cb 100644 --- a/docs/agent_team_architecture.md +++ b/docs/agent_team_architecture.md @@ -36,7 +36,6 @@ Every public transport reaches one of **two** application services: only execution kernel: the planner path reaches `DatabaseTool` through `ToolRegistry`. Both paths share `DatabaseTool` and the SQLGlot AST policy as their execution boundary and their safety invariants; the orchestration above them differs. -Unifying that upper layer is tracked work, not a current property. ## Five Stages diff --git a/docs/database_adapters.md b/docs/database_adapters.md index c7ab848..ff850c7 100644 --- a/docs/database_adapters.md +++ b/docs/database_adapters.md @@ -1,22 +1,20 @@ -# Database adapter contract (Step 18) +# Database Adapters -This document freezes the **read-only analytics database adapter contract** and -records the evidence behind the second backend (DuckDB) and the server-type backend -(PostgreSQL). The deployment/security view of the same feature is in -`database-adapters.md`; the plan item is -the QueryForge database-adapter programme (step 18). +QueryForge supports SQLite by default and optional DuckDB and PostgreSQL backends. +All analysis uses read-only connections and the shared DatabaseTool policy boundary. +This guide describes adapter capabilities, connection requirements and extension points. Files: | File | Role | | --- | --- | -| `queryforge/infrastructure/db/adapter.py` | the frozen contract, capability registry, error taxonomy, value/type normalization | -| `queryforge/infrastructure/db/sqlite_connector.py` | unchanged SQLite default path (pre-contract connector) | +| `queryforge/infrastructure/db/adapter.py` | adapter contract, capability registry, error taxonomy, value/type normalization | +| `queryforge/infrastructure/db/sqlite_connector.py` | SQLite default backend | | `queryforge/infrastructure/db/duckdb_connector.py` | DuckDB backend implementing the contract (optional driver) | | `queryforge/infrastructure/db/postgres_connector.py` | PostgreSQL server backend implementing the contract (optional `psycopg` driver) | | `queryforge/infrastructure/db/adapters.py` | factory: SQLite/DuckDB file paths, plus PostgreSQL DSNs and `*.pg` marker files; never imports a driver eagerly | | `queryforge/infrastructure/db/__init__.py` | lazy exports: importing the package never imports duckdb | -| `tests/test_db_adapter_contract.py` | parameterised conformance suite + 18-N1 cross-backend equivalence (SQLite/DuckDB) | +| `tests/test_db_adapter_contract.py` | SQLite/DuckDB conformance and result-equivalence tests | | `tests/test_postgres_adapter_contract.py` | always-run wiring/dialect checks + server-gated PostgreSQL conformance suite | ## 1. The contract surface @@ -145,12 +143,11 @@ both spellings to `decimal`. Cross-backend comparisons must use that reach it. But the engine role is not a complete boundary on SQLite: `mode=ro` protects the main database only, so the engine still accepts `ATTACH` of another file (writes *into* an attached database are refused by - `PRAGMA query_only`). That is exactly why the AST layer is load-bearing, and it - is asserted by `test_18_s1_sqlite_role_boundary_is_documented`. + `PRAGMA query_only`). The AST policy is therefore required alongside the engine boundary. * **`execute_sql` is a trusted primitive.** A caller that invokes it directly has already waived the policy layer; it exists because `DatabaseTool` owns the policy check for the existing callers. -* **No credentials, no vault, no DSN passthrough.** SQLite and DuckDB adapters open +* **Local-file permissions.** SQLite and DuckDB adapters open local files with the OS user's permissions. There is no credential vault and no per-domain authorisation in this layer. * **The server backend takes a DSN and stores nothing.** `open_postgres(dsn)` / @@ -174,13 +171,11 @@ both spellings to `decimal`. Cross-backend comparisons must use read-only transactions still allow writes to *temporary* tables (the AST policy refuses `CREATE` outright, so only the engine layer is relaxed there), and `SELECT ... INTO hacked FROM fact_orders` parses as a plain `SELECT` for the AST - policy, so on this backend the **engine** is what refuses it - (`test_18_s1_ast_policy_misses_select_into_and_the_server_catches_it`). The - reverse also holds: `ATTACH` is SQLite syntax, so on the PostgreSQL dialect the + policy, so on this backend the **engine** is what refuses it. `ATTACH` is SQLite + syntax, so on the PostgreSQL dialect the refusal is a typed parse error before the server is contacted. * **No pooling.** One adapter owns one connection and is never shared between - domains or runs; callers must `close()` it. There is no session reuse, therefore - no session-state crossover (18-C1 is out of scope for this step). + domains or runs; callers must `close()` it. There is no session reuse between runs. * **No cost model.** `explain` returns a plan (access paths), not a calibrated cost or wall-time estimate. PostgreSQL's plain `EXPLAIN` does print planner `cost=` units, which is why the declaration documents them as plan output rather @@ -200,7 +195,7 @@ both spellings to `decimal`. Cross-backend comparisons must use than `information_schema`, whose constraint views hide rows from a non-owner — a read-only role would otherwise appear to have no primary keys at all. -## 5. Adding a third backend +## 5. Adding a backend 1. Decide whether the engine really fits "read-only analytics database"; if it needs credentials, pooling or per-user sessions, extend this contract first. @@ -220,12 +215,12 @@ both spellings to `decimal`. Cross-backend comparisons must use full fetch because the engine LIMIT already bounds the result). 6. Run the parameterised suite for the new backend: subclass the conformance mixin in `tests/test_db_adapter_contract.py`, add its fixture builder (same DDL and - the same deterministic data) and extend the 18-N1 equivalence test. + the same deterministic data) and extend the cross-backend equivalence test. 7. A pre-contract connector (like `SQLiteConnector`) can be published unchanged through `adapt_connector(connector)`, which adds the contract seam without touching the connector's own behaviour. -### Adding a *server* backend (what PostgreSQL needed on top) +### Server backends 8. Route the target in `adapters.py` **without importing the driver**: a DSN scheme and/or a marker-file suffix (see `is_postgres_target`/`resolve_postgres_dsn`), so @@ -283,68 +278,3 @@ read-only role), `QUERYFORGE_TEST_POSTGRES_SCHEMA` (fixture schema prefix, defau superuser exists — the role layer is then explicitly not claimed). Setting `QUERYFORGE_REQUIRE_POSTGRES=1` turns a missing DSN into a **failure** instead of a skip, so a tier-2 job cannot go green without a server. - -**Unverified without a server.** The `psycopg`-side engine half of the PostgreSQL -conformance suite (18-N1 against SQLite, 18-S1's engine layer, cancellation, -`explain`, the streaming bound) executes **only** when -`QUERYFORGE_TEST_POSTGRES_DSN` is set. Without it those cases are skipped with that -reason in the skip text, which is why this document does not call them verified by -the default `python -m unittest discover -s tests -q` run. Everything that *can* be -checked without a server is checked unconditionally instead: the module and factory -import without the driver, the capability declaration is registered and consistent -with the frozen vocabulary, DSN/marker routing is asserted, a DSN read from a marker -file never appears in an error message, the SQLite/DuckDB paths stay driver-free, and -the postgres dialect's capability/bound behaviour is executed against the real -declaration. - -The suite proves, against real engines: - -* **18-N1** the same fixture (360-row fact table + dimension + date column, built - from the same DDL and the same deterministic data in both engines) answers the - same seven queries identically: `count`, `sum`, `group_by_join`, `window` - (`SUM(...) OVER (PARTITION BY ... ORDER BY ...)`), `cte`, `date_range`, - `empty` — compared on columns, row count and every row value with no tolerance; - plus schema-metadata parity and type-conversion parity. -* **18-S1** `INSERT`/`UPDATE`/`DELETE`/`DROP`/`CREATE`/`ATTACH`/`PRAGMA` are - refused by `AdapterPolicyError` (`decision.rule == "read_only_ast"`) before the - engine runs, the engine role independently refuses the writes on both backends, - and the fixture is verified unchanged afterwards. -* **18-R1** the SQLite path (query, schema, preview, explain, policy refusal) - keeps working while `duckdb` is made unimportable via monkeypatched - `sys.modules`/`find_spec`, the backend fails loudly only when used, and a - subprocess asserts that importing `queryforge.infrastructure.db` never imports - the driver. -* capabilities, typed-error parity (`AdapterQueryError` for an unknown table and - an unknown column from both backends), `EXPLAIN` plans, and cancellation: a - deadline (`AdapterTimeoutError`) and a client `cancel()` - (`AdapterCancelledError`) both interrupt a multi-billion-row join in well under - a second and leave the connection usable; DuckDB's bounded fetch stops at the - limit instead of materializing the whole result. - -The PostgreSQL suite (`tests/test_postgres_adapter_contract.py`) runs the same -conformance mixin against a server and adds: - -* **18-N1 across an embedded and a server engine**: the seven portable queries return - *identical* normalized rows from SQLite and PostgreSQL, plus logical-schema, - primary-key, nullability and type-conversion parity (the last one through the - documented `Decimal` comparison, since the two drivers report different Python - types for `DECIMAL`). -* **18-S1 with three layers**: 14 write/admin statements (including - `SET default_transaction_read_only = off`, `COPY`, `VACUUM`, `CREATE ROLE`) are - refused by `AdapterPolicyError` before the server sees them; the same statements - through the trusted `execute_sql` are refused by the server with SQLSTATE `25006` - (read-only transaction) or `42501` (insufficient privilege) — SQLSTATE, not message - text, so a localized server cannot turn the evidence green; and the - `SELECT ... INTO` gap in the AST layer is demonstrated to be closed by the engine. -* **the boundary is reported**: `SHOW default_transaction_read_only` is read back from - the server, the role identity is cross-checked against `current_user`, and - `readonly_role_verified` is asserted to mean exactly "this session is not a - superuser" (a run using `QUERYFORGE_TEST_POSTGRES_ALLOW_SUPERUSER=1` asserts that the - role layer is *not* claimed instead). -* **the bounded read really streams**: a named server cursor returns 4 of 20 000 000 - rows well inside the time budget a client-side materialization could not meet, and - leaves no cursor allocated (`pg_cursors`), including on a second use of the same - fixed cursor name. -* **the declaration is probed, not asserted**: every declared date function is run on - the server, and the always-run half of the module fails if a declaration appears - without a probe. diff --git a/docs/demo/README.md b/docs/demo/README.md index f76373f..5a09c2a 100644 --- a/docs/demo/README.md +++ b/docs/demo/README.md @@ -1,84 +1,38 @@ -# QueryForge 端到端验收 Demo(步骤 17) +# 可运行示例 -这五个脚本把「系统真的能做什么」写成**可复现、可断言**的演示:每一步都打印真实证据, -并且在断言不成立时**以非零退出**——所以它们既是给用户看的文档,也是 CI 里的验收测试 -(`tests/test_demo_scripts.py`)。 +这些示例使用仓库自带数据和临时工作区,展示数据接入、受治理查询、业务分析与恢复。 +全部采用确定性脚本模型,不需要 API key,也不调用外部模型。 -全部脚本**离线、确定性、零模型调用**:只用仓库自带的样例数据与自己生成的临时工作区, -不会写进仓库,不需要 API key,不访问网络。 +## 运行 -## 运行方式 +在仓库根目录安装依赖后执行: ```bash -# 全部(约 30 秒) -make demo # 等价于 python docs/demo/run_all.py - -# 单个 -.venv/bin/python docs/demo/run_demo_a.py # 上传 → 质量拦截 → 修正 → 发布 → 查询 -.venv/bin/python docs/demo/run_demo_b.py # 合法但业务错误的 SQL → 语义校验定位 → 正确结果与证据 -.venv/bin/python docs/demo/run_demo_c.py # 澄清 → 质量 → 趋势 → 下钻 → 贡献 → 证据化回答 -.venv/bin/python docs/demo/run_demo_d.py # 跨传输一致 / 部署契约拒绝 / 崩溃恢复与取消 -.venv/bin/python docs/demo/run_demo_e.py # 真实 HTTP 上传闭环 / 真实修复循环 / 数据驱动的归因 +pip install -e ".[all,duckdb]" +make demo ``` -退出码:`0` = 所有断言的声明都成立;`1` = 有声明不成立(脚本会指出是哪一条)。 - -## 每个 Demo 证明什么 - -| Demo | 演示的故事 | 关键断言(节选) | 对应验收项 | -|---|---|---|---| -| A | 上传的 CSV 决定结果;坏文件被拦下并留下可诊断证据;坏批次不污染已发布版本 | 坏批次退出 1 且**不发布任何行**、watermark 不前进、被拒行在回滚后仍可查;修正后 3 行发布,答案 = 1.5 小时;再加一行答案变 2 小时;再次失败后旧版本仍答 2 小时 | 17-E2E1 | -| B | 一条「能跑但答え错了」的 SQL 被语义校验抓住;受治理编译给出正确 SQL 并与独立 SQLite 口径逐桶一致;答案的每条结论都锚定真实证据 | 手写 SQL 是受治理值的 **3600 倍**(秒 vs 小时);校验器给出 `metric_expression` 违规;编译 SQL 带 `/3600.0` 且与独立口径完全一致;每条 finding 的 `evidence_ids` 都存在于本次运行 | 16-T1、17-I1 | -| C | 歧义先澄清、质量检查作为计划步骤、期间比较按时间排序、下钻可对账、空窗口不装成 0 | `needs_clarification` 且不跑 SQL;`ORDER BY dim_date.month_number`(不是按月份名排序);12 个月数值逐个等于独立 SQL;下钻 `buckets + others == 合计`;Q1 1990 → `partial` 且不产出答案 | 13-B1、16-N1 | -| D | 同一问题在 CLI / REST / MCP 得到同一个受治理答案;部署契约该拒就拒;崩溃可恢复、取消不可复活 | CLI 与 REST 的合计**完全相等**;MCP 暴露 `ask_sql` 等同一套工具;被策略屏蔽的列被拒(`column_scope`);allowlist 外的库在 `/ask` 与 `/analyze` 都返回 400;崩溃后 resume **复用全部已提交步骤、工具调用 0 次**;流式取消的运行不可 resume | 17-I1、17-S1、15-N1/C2 | -| E | 经**真实 HTTP 处理器**的上传→质量拒绝→发布→查询;可执行但错误的 SQL 被**真实 fix 节点**修回受治理定义;归因**随数据变化** | 上传 3 行→计数 3;被拒上传后旧版本仍可查(17-E2E1);错误语句返回 99(`valid=0`)→ 修复后返回 30(`valid=1`)且 `run_summary` 含 `fix` 节点;`paid=20/40/60` → 总变化 −20/0/+20、方向 decrease/flat/increase、残差 0;已发布域不可被调用方路径改写、已吊销域被拒 | M0、M1、M2–M3 | - -## 离线确定性与 live 模式 - -- 本目录的脚本**全部是离线确定性**模式:不配置任何模型凭证,不产生模型调用与费用; - Demo D 的 MCP 检查使用内存中的 FastMCP 替身(与 `tests/test_service_api_gateway_mcp.py` 同法), - 验证的是「同一服务被注册为工具」,不是真实模型行为。 -- **live 模式**(真实模型)不在本目录内脚本化,因为它不可离线复现、且每次成本不同: - 见 `docs/nl2sql_evaluation.md` 与 `.github/workflows/model-eval.yml`(tier 3,需凭证,结果单独报告)。 -- 因此:**本目录的 Demo 证明的是工程链路(治理、执行、证据、恢复),不是模型的 NL2SQL 准确率。** - -## Demo 过程中发现并已修复的产品缺陷 +也可以单独运行: -写 Demo 的价值就在于此——下面每一条都是「所有单测都是绿的,但真实使用时会出错」: - -1. **跨实体分组不编译 JOIN,改用原始预览冒充指标答案**(Demo C 的前身问题):规划器给编译器传空 - join path,于是「watch hours by anime format」降级为 `SELECT * FROM fact_watch_session LIMIT 5` - 并算作 `metric_value` 证据。已修复:解析受治理 join path,无法表达则显式失败。 -2. **时间维度接到了错误的列**:`watch_hours` 的时间字段是观看日期,但编译器走「分集上线日期」的 - join path,于是「watch hours by month」回答的是**分集上线月**的量。已修复(按指标自身 - `time_field` 直连日历表)。 -3. **时间序列按月份名排序**:`ORDER BY month_name` 让「上月对比」选到字母序最后两个月; - 已修复(有 `month_number` 时按其排序)。 -4. **未声明的分组字段被静默丢弃**:问「by brand_name」原本返回全体总计并报成功;已修复为澄清。 -5. **空窗口返回 NULL 仍报成功**:Q1 1990 现在按 `data_absent` 收为 `partial`。 -6. **坏批次回滚会丢掉被拒行的证据**:现在回滚后重放 quarantine 记录,运维能看到是哪几行被拒。 - -## 已知局限(Demo 里也如实展示) +```bash +.venv/bin/python docs/demo/run_demo_a.py +``` -- **贡献分解**:受治理编译器目前无法表达「按类别做两期贡献分解」,`contribution` 模板会诚实地 - 收敛为期间比较(Demo C 的 C5 断言「多维度时不得产出假的期间比较」)。 -- **语义校验器不检测手写 fan-out**:`ON 1=1` 这类乘法不会被 `SemanticSQLValidator` 单独发现 - (它检测的是粒度与请求维度不一致);真正的防线是**编译期拒绝不安全的 join path** - (Demo B 的 B5 三条断言把这点讲清楚)。 -- **月度聚合跨年**:没有指定年份的「month over month」会把所有年份的同月加总,这是当前实现的 - 确定行为,Demo C 因此显式用「in 2024」限定窗口。 +| 脚本 | 使用场景 | +| --- | --- | +| `run_demo_a.py` | CSV 上传、质量拒绝、修正发布与查询 | +| `run_demo_b.py` | 识别 SQL 的业务口径错误,检查正确结果和证据 | +| `run_demo_c.py` | 澄清、期间趋势、下钻与贡献分析 | +| `run_demo_d.py` | CLI/REST/MCP 一致性、访问限制、恢复与取消 | +| `run_demo_e.py` | HTTP 上传发布、SQL 修复循环、数据驱动的变化诊断 | -## 只有一份 Demo 实现 +脚本打印 SQL、结果与证据;退出码 `0` 表示运行成功,非零退出会指出失败步骤。 +这些示例帮助理解工程链路,真实模型评测见[评测指南](../nl2sql_evaluation.md)。 -仓库里曾经有两份 step-17 Demo:本目录的脚本,以及 `scripts/demo_data_agent.py`(由 -`tests/test_step17_demos.py` 覆盖)。现已整合:那份脚本的三个场景(真实 HTTP 上传闭环、 -真实工作流修复循环、数据驱动的增长归因)连同它的第四条安全断言(已发布域不可被改写) -一起搬进本目录,成为 **Demo E**: +## 与 Studio 联调 -- 场景代码:`docs/demo/scenarios_api_and_repair.py`(原 `scripts/demo_data_agent.py`) -- 叙事与断言:`docs/demo/run_demo_e.py` -- 离线起一个真实 API(脚本模型)供 Studio 联调:`docs/demo/serve_offline_api.py` -- `scripts/demo_data_agent.py` 与 `tests/test_step17_demos.py` 已删除,tier-2 门禁清单同步改为 - `tests.test_demo_scripts`。 +```bash +.venv/bin/python docs/demo/serve_offline_api.py +``` -因此 `make demo` 现在是 step-17 Demo 的唯一入口。 +在另一个终端启动 Studio,详见[Studio 使用指南](../studio.md)。 diff --git a/docs/github_release.md b/docs/github_release.md deleted file mode 100644 index 6bc34ed..0000000 --- a/docs/github_release.md +++ /dev/null @@ -1,152 +0,0 @@ -# QueryForge GitHub 发布清单 - -这份清单用于把当前本地目录首次发布到 GitHub。项目数据应完整提交, -本地密钥、虚拟环境、缓存和运行产物不得提交。 - -## 1. 选择许可证 - -公开仓库不等于开源。正式公开前先选择并添加根目录 `LICENSE`: - -- MIT:简洁、宽松; -- Apache-2.0:宽松,并包含明确的专利授权; -- 暂不授权:仓库保持 private,不添加开源许可证。 - -可以用 `gh repo license list` 查看 GitHub CLI 支持的许可证,或使用 -[Choose a License](https://choosealicense.com/) 生成完整文本。不要自行删改许可证正文。 - -## 2. 重建干净开发环境 - -```bash -cd QueryForge - -python3.12 -m venv .venv -source .venv/bin/activate -python -m pip install --upgrade pip -python -m pip install -e ".[dev]" - -cp .env.example .env -# 仅在本地 .env 中填写密钥;不要提交它。 -``` - -运行发布前检查: - -```bash -make check -make semantic-check -make package -python -m twine check dist/* -``` - -这些命令会重新生成缓存、报告和构建目录,但它们已经被 `.gitignore` -排除,不会进入仓库。 - -## 3. 初始化 Git - -当前目录尚未初始化为 Git 仓库: - -```bash -git init -b main -git add . -git status --short -``` - -提交前人工确认: - -- 输出中没有 `.env`、`.venv/`、`.queryforge/`、日志或缓存; -- `sample_data/anime_streaming/anime_streaming.sqlite` 在暂存区; -- `sample_data/anime_streaming/tables/` 下 15 份 CSV 都在暂存区; -- `semantic_model.yml` 和 `semantic_baseline.json` 都在暂存区; -- 根目录已经有你选择的 `LICENSE`。 - -然后创建首个提交: - -```bash -git commit -m "feat: publish QueryForge" -``` - -## 4. 创建并推送 GitHub 仓库 - -推荐使用 GitHub CLI: - -```bash -gh auth login -gh repo create QueryForge \ - --public \ - --source=. \ - --remote=origin \ - --push -``` - -如果发布到组织,使用 `OWNER/QueryForge` 作为仓库名。 - -也可以先在 GitHub 网页创建空仓库。不要在网页端额外初始化 README、 -`.gitignore` 或许可证,然后执行: - -```bash -git remote add origin git@github.com:YOUR_GITHUB_USER/QueryForge.git -git remote -v -git push -u origin main -``` - -GitHub 官方说明: -[添加本地代码到 GitHub](https://docs.github.com/en/migrations/importing-source-code/using-the-command-line-to-import-source-code/adding-locally-hosted-code-to-github)。 - -## 5. 等待首轮 Actions - -打开仓库的 **Actions** 页面,确认: - -- `quality` 在 Python 3.11 和 3.12 上通过; -- `package` 构建和元数据检查通过; -- `weekly-semantic-layer-check` 可以手动触发并通过。 - -也可以用 CLI 查看: - -```bash -gh run list --workflow quality.yml --limit 5 -gh run list --workflow semantic-weekly.yml --limit 5 -``` - -## 6. 配置主分支保护 - -首轮 Actions 成功后,在 **Settings → Rules → Rulesets**(或 Branches) -为 `main` 添加规则: - -- Require a pull request before merging; -- Require status checks to pass; -- 选择两个 `offline-acceptance` 矩阵检查和 `package`; -- Require conversation resolution; -- 禁止 force push 和删除 `main`。 - -单人维护时可以暂不强制其他人审批,但不应关闭状态检查。 - -GitHub 只允许选择近期成功运行过的状态检查,所以应先完成首次推送和 -Actions,再配置 required checks。 - -## 7. 完善仓库展示与安全 - -在仓库首页填写: - -- Description:`Governed AI analytics and NL2SQL with a mandatory semantic layer` -- Topics:`ai`、`analytics`、`data-agent`、`nl2sql`、`semantic-layer`、`sqlite` - -在 **Settings → General → Social preview** 上传 PNG/JPG/GIF。GitHub 推荐 -1280×640,并要求小于 1 MB。README 内的 SVG 和 Mermaid 会直接随代码展示。 - -在 **Settings → Security → Advanced Security** 启用: - -- Dependabot alerts; -- Dependabot security updates; -- Private vulnerability reporting。 - -## 8. 创建首个版本 - -主分支检查全部通过后: - -```bash -git tag -a v0.1.0 -m "QueryForge v0.1.0" -git push origin v0.1.0 -gh release create v0.1.0 --generate-notes -``` - -发布完成后,从一个新的临时目录克隆仓库并重新执行安装与 `make check`, -这是最可靠的“陌生机器可复现”验证。 diff --git a/docs/nl2sql_evaluation.md b/docs/nl2sql_evaluation.md index b22ddc7..6ee9a5d 100644 --- a/docs/nl2sql_evaluation.md +++ b/docs/nl2sql_evaluation.md @@ -1,4 +1,4 @@ -# Multi-Domain NL2SQL Evaluation +# Evaluation Guide The checked-in gold set is [nl2sql_multidomain.jsonl](../evaluation/gold/nl2sql_multidomain.jsonl). It contains 120 cases across three business domains: @@ -15,13 +15,16 @@ schema, deliberately exercising bridge tables, multi-hop joins, and multiple fac ## Run a Live Evaluation +Configure a provider key in `.env` as declared in `models.yml` (for DeepSeek, +`DEEPSEEK_API_KEY`). Live evaluation calls the provider and spends API credits. +Choose the provider/model explicitly and confirm the account is funded. + ```bash python scripts/evaluate_sql.py \ --cases evaluation/gold/nl2sql_multidomain.jsonl \ - --model-provider qwen \ - --output .queryforge/evaluations/qwen-multidomain.json \ - --input-cost-per-million 0.8 \ - --output-cost-per-million 2.0 + --model-provider deepseek \ + --parallel-candidates 1 --skill-mode auto \ + --output .queryforge/evaluations/nl2sql.json ``` The evaluator supports the former `--database` argument as a default for simple @@ -121,7 +124,7 @@ python scripts/evaluate_sql.py \ - `--min-policy-recall` (default 0.0, disabled): fails when any probe bypasses the policy engine. -### Token counts are measured, not estimated +### Usage and Cost When the provider returns usage, the report records the real counts and sets `token_source: "measured"`. Only when a provider exposes no usage at all does the @@ -132,64 +135,34 @@ figure cannot support a cost conclusion. Per-million prices are configured for comparable estimates only. Treat cost as an indicator of relative expense, never as an invoice. -## Frozen Baselines - -`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. - -Versions: provider `deepseek`, model `deepseek-v4-flash`, gold set -`evaluation/gold/nl2sql_multidomain.jsonl` (first 40 = `anime_content`), semantic model -`sample_data/anime_streaming/semantic_model.yml`. - -| Run (report file) | `semantic_correctness_rate` | `sql_execution_success_rate` | `p50_latency_ms` | In / out tokens | -|---|---|---|---|---| -| `nl2sql_skill_auto.json` — automatic skill selection | 0.84375 | 1.0 | 12260 | 1742 / 633 | -| `nl2sql_model_eval.json` — skills inactive | 0.875 | 1.0 | 5138 | 1446 / 438 | -| `nl2sql_selfverify2.json` — after reasoning-payload and prompt fixes | 0.875 | 1.0 | 11728 | 1734 / 579 | -| `nl2sql_defects_fixed2.json` — after the governance defect pass | 0.875 | 1.0 | 13906 | 1754 / 866 | - -> **These are single runs of 40 cases.** Differences of ±0.03 in -> `semantic_correctness_rate` have been observed across *identical* code, so the three -> 0.875 rows are the same result, not three improvements. Do not present a delta of that -> size as a gain; raise `--repeat` until the interval separates. +## Offline Checks -Two findings worth carrying forward, both from controlled comparisons rather than -aggregate impressions: - -- **Automatic skill selection costs p50 +139% and output tokens +44%** (12260 ms vs 5138 ms; - 633 vs 438) with no demonstrated accuracy benefit. `--skill-mode auto|off` exists to test - this; it is unresolved, not settled. -- **A second SQL candidate does not improve accuracy and costs ~20% p50 latency.** Measured - over 20 paired cases with candidate count forced, not grouped by the gold set's - `candidate_selection` flag (which correlates perfectly with task category and therefore - measures difficulty). Parallel candidates remain an explicit opt-in. - -A real-model run spends money. Confirm the account balance first: a depleted balance returns -HTTP 402, which the evaluator classifies as `environment_error` and excludes from the -accuracy denominators. - - -## Maintain the Gold Set - -Regenerate the deterministic checked-in file after changing its templates: +Run from the repository root with the project virtual environment: ```bash -python scripts/generate_nl2sql_gold.py -python -m unittest -q tests.test_evaluate_sql +# Governed agent tasks, without a model API call. +LOG_LEVEL=CRITICAL .venv/bin/python -B scripts/benchmark_agent.py \ + --tier 1 --gate --report evaluation/reports/offline.json + +# Independent total reconciliation and category-period diagnostics. +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 evaluation/reports/diagnostics.json ``` -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. +| Tier | Purpose | Requirements | +| --- | --- | --- | +| 1 | Deterministic governance and control-flow checks | Core dependencies; ScriptedModel supplies reference SQL | +| 2 | REST/MCP integration checks | Optional integrations, `pip install -e ".[all,duckdb]"`; no paid model | +| 3 | Real-model quality and usage | Explicit provider/model, credentials and funded account | + +Tier 1 passing does not measure model accuracy. Runnable end-to-end examples are +in [demo/README.md](demo/README.md). -## Phase-3 task contracts and paired experiments (2026-10-11) +## Task Result and Source Contracts -Task-level `result_contract` is shared by the agent-task and NL2SQL evaluators: +Agent tasks and NL2SQL cases share an explicit `result_contract`: ```json { @@ -202,393 +175,79 @@ Task-level `result_contract` is shared by the agent-task and NL2SQL evaluators: } ``` -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. +For NL2SQL cases, omit the paths; they default to `columns` and `rows`. Agent +`expected_values` declares the expected columns and rows. A task can declare +`values_absolute_tolerance` for paths such as floating-point reconciliation +residuals; other numeric comparisons keep their configured tolerance. -`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: +Source contracts require evidence that generated SQL reads the intended physical +facts. Matching values from an unrelated table cannot satisfy that requirement. +The check establishes necessary source coverage rather than proving every SQL +semantic. Query execution still passes through DatabaseTool and its policy gates. -```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, retrieval corpora and physical schema +fingerprints are audited before execution. Dev, regression and holdout datasets +have separate schema scopes. Synthetic fixtures provide regression coverage; +they do not establish population-wide generalization. -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. +Use [live_tasks_v3](../evaluation/live_tasks_v3/README.md) for new model comparisons; +its questions explicitly state the expected population. Preserve the original +questions and contracts when auditing an existing report. -The paired harness compares one mechanism at a time on identical tasks: +## Repeated Paired Comparisons -```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: +The paired harness holds tasks and controls fixed and alternates A/B order. +Candidate experiments compare 1 versus 2 with skills at `auto`; skill experiments +compare `off` versus `auto` with a fixed candidate count. ```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 \ +# Offline comparison of candidate control flow. +LOG_LEVEL=CRITICAL .venv/bin/python -B scripts/run_paired_benchmark.py \ + --tier 1 --tasks-dir evaluation/live_tasks_v3 \ --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 \ + --report evaluation/reports/paired-candidates.json + +# Offline comparison of skill routing. +LOG_LEVEL=CRITICAL .venv/bin/python -B scripts/run_paired_benchmark.py \ + --tier 1 --tasks-dir evaluation/live_tasks_v3 \ --feature skills --parallel-candidates 1 --repeat 5 \ - --report evaluation/reports/phase3_deepseek_flash_skills_live_v1_resumed.json + --report evaluation/reports/paired-skills.json + +# Preview a live experiment; --dry-run makes no provider calls. +LOG_LEVEL=CRITICAL .venv/bin/python -B scripts/run_paired_benchmark.py \ + --tier 3 --tasks-dir evaluation/live_tasks_v3 \ + --provider deepseek --model deepseek-v4-flash \ + --feature candidates --repeat 5 --dry-run \ + --report evaluation/reports/live-manifest.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. +Inspect the manifest before removing `--dry-run`. Each task runs once per repeat +and arm; selection, repair and follow-up turns can add provider calls. Model, +source, assets, gold data, policies and runtime versions are pinned in reports; +a version change during execution invalidates completion. -```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 -} -``` +Interpret paired reports using their explicit denominators: -Offline audit commands, executed after development, use a fresh output path: +- Account/transport failures and provider-contract failures exclude the pair + from both accuracy arms and make the run incomplete. +- Repeats are clustered by task for bootstrap confidence intervals. A single + small run cannot establish a small accuracy change. +- Measured-token and priced-cost comparisons have their own eligible pair counts. + Missing usage and unknown timeout costs remain `null`. +- A versioned `--prices` JSON enables cost estimates; they are not invoices. +- Keep questions, expected SQL and scoring contracts fixed. A changed task belongs + in a new run rather than a rescore of an old model answer. -```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. -``` +Raw reports are generated under the ignored `evaluation/reports/` directory. +Keep the report and its pinned inputs when sharing a benchmark result. -Both source audits recomputed 230 cases, with zero verdict/reported-token mismatches. -Scoring is versioned separately from the preserved execution provenance: +## Maintain the Gold Set -```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" - } -} +```bash +.venv/bin/python -B scripts/generate_nl2sql_gold.py +.venv/bin/python -B -m unittest -q tests.test_evaluate_sql ``` -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#补充开发最终验收). +Review expected SQL and category changes as data-contract changes. Do not alter +expected answers to raise a model score; valid alternative queries are accepted +through deterministic result equivalence. diff --git a/docs/optimization_results.md b/docs/optimization_results.md deleted file mode 100644 index 164da94..0000000 --- a/docs/optimization_results.md +++ /dev/null @@ -1,66 +0,0 @@ -# 四阶段优化成果汇总 - -本轮优化围绕回答正确性、业务语义、诊断与评测、效率与本地产品化推进。 -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 deleted file mode 100644 index 9adc37d..0000000 --- a/docs/optimization_roadmap.md +++ /dev/null @@ -1,416 +0,0 @@ -# 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/studio.md b/docs/studio.md index 1e9f05c..b37cd03 100644 --- a/docs/studio.md +++ b/docs/studio.md @@ -14,7 +14,7 @@ make web-install make web-dev ``` -Open . This optimization targets local single-user use. +Open . Studio supports 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: @@ -77,8 +77,8 @@ domains clears prior results and is refused while a run is in progress. 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. +owns SQL planning, policy enforcement, read-only execution and reports. The deployment assumes a local +single user; multi-user hosting is outside the supported deployment model. 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 @@ -104,15 +104,11 @@ 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 +STUDIO_STATE_DIR=/tmp/queryforge-studio-test 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-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.