test: accept independent verification tasks and evidence workflows

This commit is contained in:
阿白叔 committed 2026-11-17 17:12:08 +08:00
1 parent ec677a2864
commit 211d139653
26 files changed
+616 -138

No files matched your search

@@ -2,6 +2,8 @@
FREEFORM / FLAT BLOCKS 原生文本中的 `Pin 名称\tnum 编号\ttype 类型码` 可以与已解析图的实例、位号、物理脚号核对。适配器保留文件 SHA256 和行号,重复或无法绑定的字段不进入已证明清单。类型码按原文展示,不臆造类型语义。
自建格式夹具验证了逻辑名和电气类型码。引脚级 Value 尚未在该格式中证明,保持 unknown;器件 Value 不能代替它。确切库版本内部的引脚到焊盘映射尚未支持,保持未覆盖。没有进行客户工程真实字段验收。
自建格式夹具验证了逻辑名和电气类型码。另对已有工程的两份已保存副本执行了真实原生只读导出:前后各 57 个器件,83 个物理引脚取得了名称和类型码的原文证明。验收记录在本机 `D:/dx-vfy-native-final/acceptance.json`;原始客户工程和网表不提交 Git。
引脚级 Value 尚未在该格式中证明,保持 unknown;器件 Value 不能代替它。确切库版本内部的引脚到焊盘映射尚未支持,保持未覆盖。若检查计划要求这些未证明字段,结论必须为 INCOMPLETE(已有明确硬异常时仍为 DIFFERENT)。
探针:`python tools/probe_verification_pin_metadata.py <受管导出/netlist.json>`,只读已有输出,不调用 CAD、不修改工程。
@@ -1,6 +1,6 @@
# 独立校验新增功能 Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use `superpowers:executing-plans` to implement task-by-task. All checkboxes are pending. Do not start implementation from the UI image alone or dispatch agents without user authorization.
> **For agentic workers:** REQUIRED SUB-SKILL: Use `superpowers:executing-plans` to implement task-by-task. N01–N11 are implemented; N12 final validation is in progress. Do not start implementation from the UI image alone or dispatch agents without user authorization.
**Goal:** 新增可独立创建、接收成功结果、执行并让人复核的工程校验任务,交付 A 工作台及完整判断/失败处理。
@@ -10,7 +10,7 @@
**Spec:** [业务、流程、状态、数据与失败处理](../specs/2026-11-17-independent-verification-business-design.md)。对应用户最终选择的 A 图片入口,不采用此前带来源或流水线横条的旧草案。
用户已确认业务方向,开发阶段、工作区隔离、跨任务接口和交付门槛统一从[开发与交付入口](2026-11-17-verification-development.md)读取。本文件是该入口下的逐任务清单,仍全部待实施。
用户已确认业务方向,开发阶段、工作区隔离、跨任务接口和交付门槛统一从[开发与交付入口](2026-11-17-verification-development.md)读取。本文件是该入口下的逐任务清单,N01~N11 已实施,N12 最终验证进行中。
## Global Constraints
@@ -63,7 +63,7 @@ N05 可以先用已有比较器返回原始事实和明确覆盖,N06 增加分
检查ID固定:inputs(J01)、coverage(J02)、components(J03)、physical_pins(J04)、connections(J05/J06)、net_names(J07)、declared_attributes(J08)、attribute_changes(J09)、pin_text(J10)、pin_semantics(J11)、footprint_mapping(J12)、export_identity(J13)。同一check有多个issue,不重复check_id;无expectation时declared_attributes不能伪装已检查,attribute_changes仍输出变化事实。
- [ ] 写空结果、缺必查、错误与未知并存、警告、可选未知、无预期清单的失败测试:
- [x] 写空结果、缺必查、错误与未知并存、警告、可选未知、无预期清单的失败测试:
```python
def test_empty_checks_do_not_prove_consistency():
@@ -73,9 +73,9 @@ def test_empty_checks_do_not_prove_consistency():
assert result['coverage'] == 'partial'
```
- [ ] Run `.venv/Scripts/python.exe -m pytest tests/v1_1/test_independent_verification_contracts.py -q`,确认新合同尚不存在而失败。
- [ ] 实现严格字段、枚举、摘要、整数版本与受管引用结构校验;拒绝外部任意输出路径,UI不传来源字段。输入字段按规范4.1,check_plan明确 required/optional/excluded。
- [ ] 实现纯汇总优先级,核心逻辑固定为:
- [x] Run `.venv/Scripts/python.exe -m pytest tests/v1_1/test_independent_verification_contracts.py -q`,确认新合同尚不存在而失败。
- [x] 实现严格字段、枚举、摘要、整数版本与受管引用结构校验;拒绝外部任意输出路径,UI不传来源字段。输入字段按规范4.1,check_plan明确 required/optional/excluded。
- [x] 实现纯汇总优先级,核心逻辑固定为:
```python
if any(row['state'] == 'error' for row in checks):
@@ -91,9 +91,9 @@ else:
`states` 在同函数中由唯一 check_id 建立;重复check_id拒绝,不用后值覆盖前值。必查项被标not_requested同样不能通过;空required_checks在该分支前抛出TaskCenterError。覆盖清单独立计算。
- [ ] 重跑本组,补 actual属性值不能反推expected、not_requested不计已检查、没有规则时scope文字不能“换料符合”的断言。
- [ ] 对照规范J01~J13与状态表自审字段;保留原始文字及证据引用,不在合同层猜测引脚功能。
- [ ] Commit `feat: define independent verification contracts and verdicts`。
- [x] 重跑本组,补 actual属性值不能反推expected、not_requested不计已检查、没有规则时scope文字不能“换料符合”的断言。
- [x] 对照规范J01~J13与状态表自审字段;保留原始文字及证据引用,不在合同层猜测引脚功能。
- [x] Commit `feat: define independent verification contracts and verdicts`。
## N02:任务、版本、尝试与去重事务
@@ -101,7 +101,7 @@ else:
**Interfaces:** `VerificationRepository(task_store)`:`create_task(name: str, *, request_id: str) -> dict`、`publish(task_id: str, inputs: tuple[dict, ...], *, submission_id: str) -> dict`、`create_attempt(item_id: str, version: int, *, request_id: str) -> dict`、`claim(attempt_id: str, *, owner_id: str) -> dict`、`finish(attempt_id: str, *, generation: int, result: dict) -> bool`。这些只操作已验证的领域记录;原生I/O由服务完成。
- [ ] 写旧DB升级、创建去重、同版不同正文、乱序、唯一活动尝试、迟到finish与并发claim测试。测试内创建真实临时TaskStore:
- [x] 写旧DB升级、创建去重、同版不同正文、乱序、唯一活动尝试、迟到finish与并发claim测试。测试内创建真实临时TaskStore:
```python
def test_new_task_does_not_require_replacement_task(tmp_path):
@@ -117,8 +117,8 @@ def test_new_task_does_not_require_replacement_task(tmp_path):
with_store.close()
```
- [ ] Run `.venv/Scripts/python.exe -m pytest tests/v1_1/test_independent_verification_store.py -q`,确认失败。
- [ ] 建 verification_tasks/items/input_revisions/attempts/runs/requests 表,状态只属于本域;给版本和请求去重键唯一索引。至少固定:
- [x] Run `.venv/Scripts/python.exe -m pytest tests/v1_1/test_independent_verification_store.py -q`,确认失败。
- [x] 建 verification_tasks/items/input_revisions/attempts/runs/requests 表,状态只属于本域;给版本和请求去重键唯一索引。至少固定:
```sql
CREATE UNIQUE INDEX verification_input_identity
@@ -128,10 +128,10 @@ ON verification_attempts(item_id, input_version)
WHERE state IN ('queued','running','publishing','stopping');
```
- [ ] 实现事务内版本指针移动、逐条接收和CAS generation;批量外层错误全拒绝,逐项错误返回原因,已接收其他项不回滚。保存request摘要,拒绝同request_id异文。
- [ ] 用真实临时SQLite跑本组及既有schema/store回归;核对旧execution_operations与重试额度字节/行值未被新操作改写。
- [ ] 故障注入提交前/提交后;返回值在事务内准备,不能因COMMIT后的额外尾读失败误报未接收;记录同一 before 新after与新before分项的区别。
- [ ] Commit `feat: persist verification tasks inputs and attempts`。
- [x] 实现事务内版本指针移动、逐条接收和CAS generation;批量外层错误全拒绝,逐项错误返回原因,已接收其他项不回滚。保存request摘要,拒绝同request_id异文。
- [x] 用真实临时SQLite跑本组及既有schema/store回归;核对旧execution_operations与重试额度字节/行值未被新操作改写。
- [x] 故障注入提交前/提交后;返回值在事务内准备,不能因COMMIT后的额外尾读失败误报未接收;记录同一 before 新after与新before分项的区别。
- [x] Commit `feat: persist verification tasks inputs and attempts`。
## N03:统一接收、独立导入与成功结果交接
@@ -139,13 +139,13 @@ WHERE state IN ('queued','running','publishing','stopping');
**Interfaces:** `VerificationService(task_store, data_root: Path)`;`create_task(name, *, request_id)`;`publish_inputs(task_id, inputs, *, submission_id)`;`import_pair(task_id, before: Path, after: Path, *, request_id: str, stop_event) -> dict`;`receive_successful_results(result_ref: dict, *, submission_id: str) -> dict`;`reconcile_deliveries(*, limit: int = 100) -> dict`。两种操作最终发布同一种inputs,无来路枚举。默认自动接收容器名为“校验任务”,以持久交接关联键去重,用户可改名。
- [ ] 写两份工程同文件/数据库别名、捕获时变化、成功交接缺before、未成功结果拒绝、重复交接、一次批量和分次输入等价的测试。自建文件只用于事务/捕获测试,不假称可打开CAD工程。
- [ ] Run `.venv/Scripts/python.exe -m pytest tests/v1_1/test_independent_verification_intake.py -q`,确认失败。
- [ ] 复用capture_project,受管目录外输入先检查稳定性;两个文件最终数据库同源也要拒绝。已冻结交接只核验引用,不打开原CAD或重新捕获旧before。
- [ ] 对已落盘成功范围建规范inputs;expectation_ref来自冻结清单/有效回执,不用after反推。补有界交接对账:首次接收和重启/进入校验页重扫未确认通知都用同submission键,落库回执作为完成依据。
- [ ] 重跑本组;让导入/发布期间的替换和恢复入口抛AssertionError,证明只创建校验记录。成功工程缺证据仍可见,错误输入不能将旧baseline换成当前工程。
- [ ] 对照接口确认当前能批量传、未来能乱序增量传;输入接收不创建queued尝试,不强制切走用户正在看的任务。
- [ ] Commit `feat: receive verification inputs and import project pairs`。
- [x] 写两份工程同文件/数据库别名、捕获时变化、成功交接缺before、未成功结果拒绝、重复交接、一次批量和分次输入等价的测试。自建文件只用于事务/捕获测试,不假称可打开CAD工程。
- [x] Run `.venv/Scripts/python.exe -m pytest tests/v1_1/test_independent_verification_intake.py -q`,确认失败。
- [x] 复用capture_project,受管目录外输入先检查稳定性;两个文件最终数据库同源也要拒绝。已冻结交接只核验引用,不打开原CAD或重新捕获旧before。
- [x] 对已落盘成功范围建规范inputs;expectation_ref来自冻结清单/有效回执,不用after反推。补有界交接对账:首次接收和重启/进入校验页重扫未确认通知都用同submission键,落库回执作为完成依据。
- [x] 重跑本组;让导入/发布期间的替换和恢复入口抛AssertionError,证明只创建校验记录。成功工程缺证据仍可见,错误输入不能将旧baseline换成当前工程。
- [x] 对照接口确认当前能批量传、未来能乱序增量传;输入接收不创建queued尝试,不强制切走用户正在看的任务。
- [x] Commit `feat: receive verification inputs and import project pairs`。
## N04:当前版本查询、任务统计与历史投影
@@ -153,13 +153,13 @@ WHERE state IN ('queued','running','publishing','stopping');
**Interfaces:** `list_tasks(*, query='', cursor=None, limit=50, read_control=None)`;`read_task(task_id, *, state='', query='', cursor=None, limit=100, read_control=None)`;`read_item(item_id, *, version: int | None = None, read_control=None)`;`read_issues(attempt_id, *, kind='', cursor=None, limit=100, read_control=None)`。返回task view_revision、当前input_version、attempt身份、结论、范围、动作门禁、分页cursor。`summarize_items(rows)`只统计当前版本。
- [ ] 写24项计数、旧版不重复计数、重校验转排队后旧绿灯退出当前、同名不同身份、筛选与整任务操作范围分离的测试。
- [ ] Run `.venv/Scripts/python.exe -m pytest tests/v1_1/test_independent_verification_queries.py -q`,确认失败。
- [ ] 实现“输入→当前尝试→结论→可执行动作”的单一投影;执行succeeded且verdictDIFFERENT必须显示异常,而非通过。空任务可新建/加工程,活动任务不禁用创建其他任务。
- [ ] 参数化查询实现50任务/100工程/100问题上限,搜索名称、路径及已有issue位号/料号;转义LIKE的百分号/下划线。分页cursor绑定过滤、排序和view_revision,身份不从行号推断。
- [ ] 跑本组与既有任务只读查询测试,核对“24=16一致+2警告+1异常+1无法校验+4待校验,已处理20”;暂停/中断单列不当一致。
- [ ] 用并发读/新版本发布验证快照计数一致;旧attempt结果只进入历史,不刷新当前绿色。
- [ ] Commit `feat: query current verification results and task summaries`。
- [x] 写24项计数、旧版不重复计数、重校验转排队后旧绿灯退出当前、同名不同身份、筛选与整任务操作范围分离的测试。
- [x] Run `.venv/Scripts/python.exe -m pytest tests/v1_1/test_independent_verification_queries.py -q`,确认失败。
- [x] 实现“输入→当前尝试→结论→可执行动作”的单一投影;执行succeeded且verdictDIFFERENT必须显示异常,而非通过。空任务可新建/加工程,活动任务不禁用创建其他任务。
- [x] 参数化查询实现50任务/100工程/100问题上限,搜索名称、路径及已有issue位号/料号;转义LIKE的百分号/下划线。分页cursor绑定过滤、排序和view_revision,身份不从行号推断。
- [x] 跑本组与既有任务只读查询测试,核对“24=16一致+2警告+1异常+1无法校验+4待校验,已处理20”;暂停/中断单列不当一致。
- [x] 用并发读/新版本发布验证快照计数一致;旧attempt结果只进入历史,不刷新当前绿色。
- [x] Commit `feat: query current verification results and task summaries`。
## N05:独立只读执行器与原生后端适配
@@ -167,13 +167,13 @@ WHERE state IN ('queued','running','publishing','stopping');
**Interfaces:** `run_attempt(service, attempt_id: str, *, stop_event) -> dict`;`export_inputs(before_ref: dict, after_ref: dict, *, output: Path, stop_event) -> tuple[dict, dict]`;`can_start_native_export(service) -> dict` 返回allowed/reason,不占用新建入口。N06前本适配可返回已有比较事实并显式缺少扩展检查,不能编造完整结论。
- [ ] 写任意独立任务可运行、原输入不变、缺工具不启动CAD、旧缓存损坏重导出、并发领取唯一、资源忙排队的测试。runner用受控OwnedCliScope/现有graph夹具,实际持久库和文件发布链不替换为固定成功值。
- [ ] Run `.venv/Scripts/python.exe -m pytest tests/v1_1/test_independent_verification_runner.py -q`,确认失败。
- [ ] 依照E03~E07核验固定引用;捕获/导出只走既有native_netlist。首版独立runner一次领取一个工程对,前后导出顺序运行,避免复制旧批次pool再叠加并发。若原生资源准入不可证明可并行,则留队列等待;不以该等待禁用新建。
- [ ] 组织比较调用与暂存产物;先按E10确认自有CLI退出,再按E11发布结果及CAS finish。原异步导出/旧finish行为不被替换为新全局队列,接收既有完整证据时可以只复核/复用而不额外开进程。
- [ ] 跑新组及两个旧网表组;断言替换派发数、CAD启动数、execution_operations写次数均为0,旧入口的暂停与缓存合同不退化。
- [ ] 注入导出失败和发布中断;确认旧结果不覆盖、迟到attempt不更新当前。记录新执行器与旧资源修复的责任边界,不用本任务修退出helper。
- [ ] Commit `feat: execute independent verification on immutable inputs`。
- [x] 写任意独立任务可运行、原输入不变、缺工具不启动CAD、旧缓存损坏重导出、并发领取唯一、资源忙排队的测试。runner用受控OwnedCliScope/现有graph夹具,实际持久库和文件发布链不替换为固定成功值。
- [x] Run `.venv/Scripts/python.exe -m pytest tests/v1_1/test_independent_verification_runner.py -q`,确认失败。
- [x] 依照E03~E07核验固定引用;捕获/导出只走既有native_netlist。首版独立runner一次领取一个工程对,前后导出顺序运行,避免复制旧批次pool再叠加并发。若原生资源准入不可证明可并行,则留队列等待;不以该等待禁用新建。
- [x] 组织比较调用与暂存产物;先按E10确认自有CLI退出,再按E11发布结果及CAS finish。原异步导出/旧finish行为不被替换为新全局队列,接收既有完整证据时可以只复核/复用而不额外开进程。
- [x] 跑新组及两个旧网表组;断言替换派发数、CAD启动数、execution_operations写次数均为0,旧入口的暂停与缓存合同不退化。
- [x] 注入导出失败和发布中断;确认旧结果不覆盖、迟到attempt不更新当前。记录新执行器与旧资源修复的责任边界,不用本任务修退出helper。
- [x] Commit `feat: execute independent verification on immutable inputs`。
## N06:结构、属性、警告与未知的逐项判断
@@ -181,10 +181,10 @@ WHERE state IN ('queued','running','publishing','stopping');
**Interfaces:** `evaluate(before: dict, after: dict, *, expectations: dict | None, check_plan: dict, pin_metadata: dict | None = None) -> dict` 返回checks、issues和N01汇总;`match_components(before_graph, after_graph) -> dict`返回可证明对应及歧义,不改原图。没有expectations与有意声明空变化清单须区分。
- [ ] 用真实最小graph夹具写J01~J13反例:断线、短接、交换物理脚、位号增删、用户网名、无清单属性、正常目标变化、非目标变化、命名警告、必查unknown。固定脚号互换测试独立于名称相似度。
- [ ] Run `.venv/Scripts/python.exe -m pytest tests/v1_1/test_independent_verification_rules.py -q`,确认失败。
- [ ] 复用已有完整图/物理端点语义,建立只读对应视图;延用最新实例范围+生效位号唯一绑定,UID仅保留原始证据,其缺失/重复/变化不得否定已证明的位号对应。真实位号/实例歧义仍unknown。连接按完整端点集合比较,单端网络与未连接不混用。
- [ ] 按check输出事实,不直接复用旧verified作为新最终结论;对允许改名的原比较结果补warning。关键边界为:
- [x] 用真实最小graph夹具写J01~J13反例:断线、短接、交换物理脚、位号增删、用户网名、无清单属性、正常目标变化、非目标变化、命名警告、必查unknown。固定脚号互换测试独立于名称相似度。
- [x] Run `.venv/Scripts/python.exe -m pytest tests/v1_1/test_independent_verification_rules.py -q`,确认失败。
- [x] 复用已有完整图/物理端点语义,建立只读对应视图;延用最新实例范围+生效位号唯一绑定,UID仅保留原始证据,其缺失/重复/变化不得否定已证明的位号对应。真实位号/实例歧义仍unknown。连接按完整端点集合比较,单端网络与未连接不混用。
- [x] 按check输出事实,不直接复用旧verified作为新最终结论;对允许改名的原比较结果补warning。关键边界为:
```python
if numbers_equal is False or connections_equal is False:
@@ -199,9 +199,9 @@ else:
该片段只在物理脚已建立对应后运行;结构或连接已证明改变仍按硬异常处理,未证明的比较结果不会被Python的假值语义误判为“已证实改变”。unknown字段不由空字符串补齐,GND/VCC语义不由模型判断。
- [ ] 跑本组及现有physical pin/逻辑改名测试;证明默认旧比较器结果不被全局放宽,网名变化不会套入引脚名称规则。
- [ ] 检查错误优先、未知必查、警告、范围一致四类;有已知反脚加缺失属性时仍DIFFERENT,同时保留unknown列表。
- [ ] Commit `feat: classify verification checks with explicit evidence and coverage`。
- [x] 跑本组及现有physical pin/逻辑改名测试;证明默认旧比较器结果不被全局放宽,网名变化不会套入引脚名称规则。
- [x] 检查错误优先、未知必查、警告、范围一致四类;有已知反脚加缺失属性时仍DIFFERENT,同时保留unknown列表。
- [x] Commit `feat: classify verification checks with explicit evidence and coverage`。
## N07:引脚级字段与封装映射能力探测
@@ -209,7 +209,7 @@ else:
**Interfaces:** `inspect_pin_metadata(export: dict, *, evidence_root: Path) -> dict` 返回每物理脚的logical_name/pin_value/electrical_type字段、存在性、原始定位、confidence为proven/unknown;`inspect_footprint_mapping(binding: dict) -> dict` 首版只接纳真实可证适配,未支持返回unknown及原因,不用空字典代表映射相同。
- [ ] 写引脚Value与器件Value不同、原字段缺失、引脚类型变化、逻辑名对齐物理号、库映射未知的测试。缺证据边界:
- [x] 写引脚Value与器件Value不同、原字段缺失、引脚类型变化、逻辑名对齐物理号、库映射未知的测试。缺证据边界:
```python
def test_missing_mapping_is_unknown(tmp_path):
@@ -219,12 +219,12 @@ def test_missing_mapping_is_unknown(tmp_path):
assert result['mapping'] is None
```
- [ ] Run `.venv/Scripts/python.exe -m pytest tests/v1_1/test_verification_pin_metadata.py -q`,确认失败。
- [ ] 探针只在用户工程已保存副本/受管导出上读取现有原生输出,记录确切字段、版本、存在性和物理脚绑定。先确认能否读出,不能凭类型名发明COM方法或回退CAD采集;探针不直接进入生产导入链。
- [ ] 只有已证明的字段进入最小解析适配;无引脚Value就保留unknown,不用逻辑名或器件Value代替。库内映射默认未覆盖,只有取得真实版本/符号/Cell/脚号证据才实现对应分支。
- [ ] 运行本组及N06,使用自建可提交fixture覆盖loop/outloop、同号不同文字、同名不同脚和已证实映射交换;客户报告只本地保存,仓库仅自建摘录。
- [ ] 写能力报告:已验证字段/格式、未覆盖项、真实读取或纯夹具证据;无法验证的能力不阻止A基础页交付,但必查请求该能力时必须INCOMPLETE。
- [ ] Commit `feat: expose proven pin metadata and unsupported mapping coverage`。
- [x] Run `.venv/Scripts/python.exe -m pytest tests/v1_1/test_verification_pin_metadata.py -q`,确认失败。
- [x] 探针只在用户工程已保存副本/受管导出上读取现有原生输出,记录确切字段、版本、存在性和物理脚绑定。先确认能否读出,不能凭类型名发明COM方法或回退CAD采集;探针不直接进入生产导入链。
- [x] 只有已证明的字段进入最小解析适配;无引脚Value就保留unknown,不用逻辑名或器件Value代替。库内映射默认未覆盖,只有取得真实版本/符号/Cell/脚号证据才实现对应分支。
- [x] 运行本组及N06,使用自建可提交fixture覆盖loop/outloop、同号不同文字、同名不同脚和已证实映射交换;客户报告只本地保存,仓库仅自建摘录。
- [x] 写能力报告:已验证字段/格式、未覆盖项、真实读取或纯夹具证据;无法验证的能力不阻止A基础页交付,但必查请求该能力时必须INCOMPLETE。
- [x] Commit `feat: expose proven pin metadata and unsupported mapping coverage`。
## N08:可人工复核的证据模型与连接图
@@ -232,13 +232,13 @@ def test_missing_mapping_is_unknown(tmp_path):
**Interfaces:** `build_evidence(before_graph: dict, after_graph: dict, issues: tuple[dict, ...], *, binding: dict) -> dict` 返回issue稳定ID、前后物理脚位置、连接对端、差异表和raw定位。`connection_view(evidence: dict, issue_id: str) -> dict` 只生成确定性绘图数据,不调用图片/语言模型。
- [ ] 写R12 1/2互换、短接多对端、纯改名不画红断线、未知映射、图页未知与证据摘要损坏测试。前后pin1的绘制顺序必须相同,不能自动互换位置使图看起来一致。
- [ ] Run `.venv/Scripts/python.exe -m pytest tests/v1_1/test_verification_evidence.py -q`,确认失败。
- [ ] 从N06事实产生唯一issue_id;图和表共享同一数据结构,不分别拼判断。端点按固定脚号排列,变化线给出added/removed及原网络名,保留多gate与实例身份。
- [ ] 将issue绑定不可变raw文件、摘要与可定位段落/对象键;图页无法确定则明确未定位。图标注“由网表生成”,不画伪原理图截图,不用生成模型解释电气正确性。
- [ ] 跑本组与N06;反例断言每条红色连线都有对应连接error/差异,纯文字warning没有虚构接线变化。
- [ ] 检查独立输入无expectation时证据仍可读;原生身份列差异与有效料号显示分开,不改写raw以统一数值。
- [ ] Commit `feat: build traceable pin and network comparison evidence`。
- [x] 写R12 1/2互换、短接多对端、纯改名不画红断线、未知映射、图页未知与证据摘要损坏测试。前后pin1的绘制顺序必须相同,不能自动互换位置使图看起来一致。
- [x] Run `.venv/Scripts/python.exe -m pytest tests/v1_1/test_verification_evidence.py -q`,确认失败。
- [x] 从N06事实产生唯一issue_id;图和表共享同一数据结构,不分别拼判断。端点按固定脚号排列,变化线给出added/removed及原网络名,保留多gate与实例身份。
- [x] 将issue绑定不可变raw文件、摘要与可定位段落/对象键;图页无法确定则明确未定位。图标注“由网表生成”,不画伪原理图截图,不用生成模型解释电气正确性。
- [x] 跑本组与N06;反例断言每条红色连线都有对应连接error/差异,纯文字warning没有虚构接线变化。
- [x] 检查独立输入无expectation时证据仍可读;原生身份列差异与有效料号显示分开,不改写raw以统一数值。
- [x] Commit `feat: build traceable pin and network comparison evidence`。
## N09:A工作台、独立新建与证据检查器
@@ -246,13 +246,13 @@ def test_missing_mapping_is_unknown(tmp_path):
**Interfaces:** `VerificationWorkspace(service, parent=None)`;`open_task(task_id, item_id=None)`、`set_active(active)`、`shutdown()`、`busy`、`busy_changed`;`VerificationInspector.set_evidence(evidence)`。controller通过N04查询,未来增量输入仅更新结果查询,不重新设计来路入口。
- [ ] 写四导航映射、始终可新建、已有任务时独立导入、无来源横条、选择保持、不同任务延迟回调、DIFFERENT不显示通过的Qt测试。沿用既有`ui` fixture,但不更改其修复逻辑。
- [ ] Run `.venv/Scripts/python.exe -m pytest tests/ui/test_verification_workspace.py tests/ui/test_verification_inspector.py -q`,确认失败。
- [ ] 按最终图建立任务列表/状态筛选/工程表/右证据/固定底栏;main_window按页面对象明确映射四导航,DSH懒加载不被触发。新建对话框只含名称与可选前后工程,不要求来源选择。
- [ ] QPainter或Qt原生控件渲染N08确定性图,表格同源;保持8–12px圆角、白色数据面、已有亚克力外框和减少透明度设置。980宽改可展开详情,不遮住开始/停止按钮。
- [ ] 跑本组、现有history/DSH导航与样式测试;无后台run时点击导航或选工程只查询,不隐式导出。
- [ ] 人工看1280×880、980×700及125/150%缩放;右侧R12对照保持1/2位置,警告/未知文字可读。静态图片仅视觉参考,不算功能验收。
- [ ] Commit `feat: add the independent verification workspace and evidence inspector`。
- [x] 写四导航映射、始终可新建、已有任务时独立导入、无来源横条、选择保持、不同任务延迟回调、DIFFERENT不显示通过的Qt测试。沿用既有`ui` fixture,但不更改其修复逻辑。
- [x] Run `.venv/Scripts/python.exe -m pytest tests/ui/test_verification_workspace.py tests/ui/test_verification_inspector.py -q`,确认失败。
- [x] 按最终图建立任务列表/状态筛选/工程表/右证据/固定底栏;main_window按页面对象明确映射四导航,DSH懒加载不被触发。新建对话框只含名称与可选前后工程,不要求来源选择。
- [x] QPainter或Qt原生控件渲染N08确定性图,表格同源;保持8–12px圆角、白色数据面、已有亚克力外框和减少透明度设置。980宽改可展开详情,不遮住开始/停止按钮。
- [x] 跑本组、现有history/DSH导航与样式测试;无后台run时点击导航或选工程只查询,不隐式导出。
- [x] 人工看1280×880、980×700及125/150%缩放;右侧R12对照保持1/2位置,警告/未知文字可读。静态图片仅视觉参考,不算功能验收。
- [x] Commit `feat: add the independent verification workspace and evidence inspector`。
## N10:开始、停止、重校验、崩溃恢复与版本竞争
@@ -260,13 +260,13 @@ def test_missing_mapping_is_unknown(tmp_path):
**Interfaces:** `start(task_id, *, selection: tuple[tuple[str,int], ...] | None, request_id)`,None表示服务端冻结当前全部ready;`stop(run_id, *, request_id)`;`rerun(item_id, version, *, request_id)`;`recover() -> dict`;`begin_shutdown()`。停止/恢复均不调用替换停止/准备重试/核验恢复函数。
- [ ] 写重复点击、冻结范围不吞新项、当前v2不被v1完成覆盖、取消与提交竞争、进程退出未知、重启不自动执行的测试。queued取消保留历史;整run停止前从未派发项投影回待校验,用户单项取消显示已停止。
- [ ] Run `.venv/Scripts/python.exe -m pytest tests/v1_1/test_verification_control.py tests/ui/test_verification_control.py -q`,确认失败。
- [ ] 实现命令幂等与持久stop_requested;领取前/后、原生导出阶段和发布CAS前检查。终态提交先发生时保留真实结果;取消先发生时旧callback不能提交当前结果。
- [ ] 实现重启核实OwnedCli身份/退出、F15产物补提交和interrupted;归属核对使用原owner/token/进程创建身份,不仅凭PID,以免PID复用误杀外部进程。未知资源留stopping,禁止盲目新导出。新attempt递增generation,旧terminal不改回running。
- [ ] 跑本组及旧网表暂停组;在全部校验控制测试中将既有替换动作设为抛AssertionError,证明不会触发。GUI关闭不join/wait原生进程,通知安全结束后再关闭。
- [ ] 受控慢导出期间切页、建新任务和停止,验证事件循环可响应;新工程后到保持待校验,不无限扩展当前run范围。
- [ ] Commit `feat: control and recover independent verification attempts`。
- [x] 写重复点击、冻结范围不吞新项、当前v2不被v1完成覆盖、取消与提交竞争、进程退出未知、重启不自动执行的测试。queued取消保留历史;整run停止前从未派发项投影回待校验,用户单项取消显示已停止。
- [x] Run `.venv/Scripts/python.exe -m pytest tests/v1_1/test_verification_control.py tests/ui/test_verification_control.py -q`,确认失败。
- [x] 实现命令幂等与持久stop_requested;领取前/后、原生导出阶段和发布CAS前检查。终态提交先发生时保留真实结果;取消先发生时旧callback不能提交当前结果。
- [x] 实现重启核实OwnedCli身份/退出、F15产物补提交和interrupted;归属核对使用原owner/token/进程创建身份,不仅凭PID,以免PID复用误杀外部进程。未知资源留stopping,禁止盲目新导出。新attempt递增generation,旧terminal不改回running。
- [x] 跑本组及旧网表暂停组;在全部校验控制测试中将既有替换动作设为抛AssertionError,证明不会触发。GUI关闭不join/wait原生进程,通知安全结束后再关闭。
- [x] 受控慢导出期间切页、建新任务和停止,验证事件循环可响应;新工程后到保持待校验,不无限扩展当前run范围。
- [x] Commit `feat: control and recover independent verification attempts`。
## N11:完整报告、历史与证据保留
@@ -274,13 +274,13 @@ def test_missing_mapping_is_unknown(tmp_path):
**Interfaces:** `render_item_report(result_ref: dict, destination: Path) -> Path`;`export_task(task_id, destination: Path, *, request_id)`;`open_evidence(attempt_id, artifact_id)`只接受受管artifact标识。导出冻结view_revision,可在运行中生成并明确未完成项。
- [ ] 写同版本报告/图表一致、HTML转义、原证据损坏、导出重名、运行中快照、清历史不删证据、缓存不可伪装新结果的测试。
- [ ] Run `.venv/Scripts/python.exe -m pytest tests/v1_1/test_verification_reports.py tests/ui/test_verification_report_actions.py -q`,确认失败。
- [ ] 从N08证据包渲染HTML/JSON,字段转义,原始文件只引用或用户明确选择后打包;默认不复制整个工程。报告固定输入/策略/工具/attempt摘要与检查范围。
- [ ] 暂存→完整性核验→原子发布,重名目录明确错误不混写;HistoryRepository用稳定source_key防重复记录校验事件,此source_key为事件去重而非UI来源类型。
- [ ] 跑本组与retention/history回归,核对当前/活动引用不可被普通日志清空删除,失去证据时显示不可用而非缓存绿灯。
- [ ] 写用户说明:新建/自动接收无需来源、开始范围、警告/异常/未知、版本更新、停止重启、对照图与证据查看;不宣称ERC/PCB已检查。
- [ ] Commit `feat: export verification evidence and preserve result history`。
- [x] 写同版本报告/图表一致、HTML转义、原证据损坏、导出重名、运行中快照、清历史不删证据、缓存不可伪装新结果的测试。
- [x] Run `.venv/Scripts/python.exe -m pytest tests/v1_1/test_verification_reports.py tests/ui/test_verification_report_actions.py -q`,确认失败。
- [x] 从N08证据包渲染HTML/JSON,字段转义,原始文件只引用或用户明确选择后打包;默认不复制整个工程。报告固定输入/策略/工具/attempt摘要与检查范围。
- [x] 暂存→完整性核验→原子发布,重名目录明确错误不混写;HistoryRepository用稳定source_key防重复记录校验事件,此source_key为事件去重而非UI来源类型。
- [x] 跑本组与retention/history回归,核对当前/活动引用不可被普通日志清空删除,失去证据时显示不可用而非缓存绿灯。
- [x] 写用户说明:新建/自动接收无需来源、开始范围、警告/异常/未知、版本更新、停止重启、对照图与证据查看;不宣称ERC/PCB已检查。
- [x] Commit `feat: export verification evidence and preserve result history`。
## N12:集成、真实只读输入、包内入口与发布门禁
@@ -1,6 +1,6 @@
# 工程校验功能开发与交付计划
> **For agentic workers:** REQUIRED SUB-SKILL: Use `superpowers:executing-plans` with the linked N01~N12 detailed plan. This is the delivery entry point, not authorization to begin application changes. All development tasks are pending.
> **For agentic workers:** REQUIRED SUB-SKILL: Use `superpowers:executing-plans` with the linked N01~N12 detailed plan. This is the delivery entry point, not authorization to begin application changes. N01–N11 are implemented; N12 final validation is in progress.
**Goal:** 开发独立校验任务、可信判断和可人工复核的 A 工作台,复用现有能力,只增加缺失功能。
@@ -138,6 +138,6 @@ input_record = {
## 8. 交接状态
业务设计已获用户认可;本轮完善开发计划,不开始应用实现。按独立工作目录顺序执行,不创建新用户聊天,也不自动派发代理。推荐起点N01;公共接线N03/N05/N09等先核对其他任务已合入的最终接口。
用户已授权逐项实施;N01~N11 已实现并分步提交,N12 正在做最终回归与实际包验收。按独立工作目录顺序执行,不创建新用户聊天,也不自动派发代理。推荐起点N01;公共接线N03/N05/N09等先核对其他任务已合入的最终接口。
详细任务均待实施。后续开发以本入口和[N01~N12清单](2026-11-17-independent-verification-new-features.md)共同为准,11月6日的V/U旧计划保留为历史参考,不能再并行照旧重建后端或来源界面。
实施进度及验证结果见 docs/testing/2026-11-17-independent-verification-acceptance.md。后续开发以本入口和[N01~N12清单](2026-11-17-independent-verification-new-features.md)共同为准,11月6日的V/U旧计划保留为历史参考,不能再并行照旧重建后端或来源界面。
@@ -0,0 +1,49 @@
# 独立工程校验验收记录
开发分支:`codex/independent-verification`。独立工作目录:`.worktrees/independent-verification`。基础主线:`origin/main@b19afc6`;重新 fetch 后未出现更新提交。原工作区另一项修复仍有未提交修改,本分支没有复制它们。
## 已实现范围
| 阶段 | 结果 |
| --- | --- |
| N01~N04 | 独立任务、不可变输入版本、幂等交接、独立导入、当前版本投影、筛选/分页/计数 |
| N05~N08 | 原生只读导出、固定物理脚号判断、名称/属性警告、未知覆盖、同源接线图和逐脚事实 |
| N09~N11 | 第四导航、随时新建、开始/停止/重校验、历史版本与尝试、异步关闭、HTML/JSON报告、证据摘要与保留 |
| N12 | 混合批次、验收 CLI、真实原生导出已验证;最终默认回归、扩展回归和安装包结果见下方完成记录 |
## 验收路径
受控格式路径:`python tools/verify_independent_verification.py --fixture-root <目录> --output <新目录>`。夹具目录中 `before/after` 各含合法捕获配置 `.prj` 与数据库、`effective.txt` 和 `design.kyn`。该路径明确标记 `controlled-format-fixture`,不能冒充真实 CAD 导出。
真实只读路径:`python tools/verify_independent_verification.py --native-before <前工程.prj> --native-after <后工程.prj> --output <新目录>`。非零退出区分异常、缺覆盖和执行失败;警告结果保留给人工确认。
实际执行输出:`D:/dx-vfy-native-final/acceptance.json`。前后各 57 个器件、83 个有原文定位的引脚,结论 WARNING(器件属性变化且没有固定换料清单;原生身份表另有提示)。两个工程文件及两个数据库的 SHA256 前后不变,`replacement_operations=0`。JSON、HTML、网表原文及输入摘要保留于该本地目录,Git不收录工程和厂商二进制。
## 验证过的关键反例
- R12.1/2 互换:DIFFERENT;前后图位置不随名称交换,表和报告来自相同证据。
- loop→outloop、拓扑不变:WARNING;不伪造红色接错线。
- 断线、短接、位号变化、物理脚号/占用次数变化、用户网名变化:硬异常。
- 有固定清单时精确核对目标属性;无清单时列出变化并注明“未核对换料规则”。
- 缺必查字段/库映射:INCOMPLETE;硬异常与未知同时存在时仍为 DIFFERENT。
- 重复/乱序交接不重复创建;旧版本结果只留历史;重校验不会沿用旧绿灯。
- 持久停止先于提交时取消获胜;终态先提交时保留真实结果;未派发项回到待校验。
- 原始证据损坏取消绿色结论并拒绝有效报告;清历史不删除证据;存储失败暂停执行器。
- 慢证据核验不占住数据库事务,新建任务可继续;同一尝试仅一个领取者。
- 关闭可重复调用;重启不自动重跑;退出缺证明保留现场,不按 PID 误杀其他进程。
## 视觉检查
实际 Qt 截图而非生图:本机 `F:/dx-vfy-preview-20261117/`。1280×880、980×700,以及 1.25/1.5 缩放均已生成检查。接线图使用自建 R12 反脚夹具演示,不能冒充真实工程错误。完整事实另有逐脚表和原文定位。
## 验证环境与限制
共享 `.venv` 的基础 Python 路径异常,导致 `-E/-I` 的旧进程边界测试失败;Windows 默认 GBK 还影响旧测试中未声明编码的读取。没有修改产品旧执行器或用户环境变量。独立验证环境为 `D:/dx-vfy-python-20261117`,基于本机已安装 Python 3.12.10,复用已安装依赖;测试使用进程级 `-X utf8`。
首次默认回归:2221 passed、6 failed、6 errors;其中关闭重复调用的本功能回归已修复,环境相关项在独立环境的相关 66 项测试中通过。首次扩展回归 818 passed、4 failed、4 skipped;本功能首选问题定位已修正,GBK 相关的 28 项复核通过。不能把首轮失败记录解释为最终全绿结果。
F 盘空间不足使第一次构建未完成;仅清理了本工作目录本次生成的失败构建目录,构建和后续测试转到 D 盘。没有清理原工作区、客户工程或其他任务输出。引脚级 Value、确切库内部引脚到焊盘映射、ERC/PCB 正确性仍未覆盖。
## 最终完成记录
最终回归和实际包验收正在执行;完成后记录命令、通过数量、包摘要与原文位置。
@@ -104,9 +104,10 @@ class TaskCenterService:
@property
def verification(self):
if not hasattr(self, '_verification_service'):
from .verification.service import VerificationService
self._verification_service = VerificationService(self._store, self._logging.root)
with self._store._lock:
if not hasattr(self, '_verification_service'):
from .verification.service import VerificationService
self._verification_service = VerificationService(self._store, self._logging.root)
return self._verification_service
def __init__(
@@ -6,6 +6,9 @@ from PySide6.QtWidgets import (QWidget,QLabel,QVBoxLayout,QHBoxLayout,QComboBox,
QTableWidgetItem,QHeaderView,QTabWidget,QScrollArea,QPlainTextEdit,QPushButton)
from ..verification.evidence import verify_evidence
ATTEMPTS={'queued':'排队中','running':'执行中','publishing':'保存结果中','stopping':'安全收尾中',
'succeeded':'执行完成','failed':'执行失败','cancelled':'已停止','interrupted':'已中断'}
def pin_text(pin):
if pin is None:return '不存在/未覆盖'
@@ -42,6 +45,7 @@ class ConnectionDiagram(QWidget):
class VerificationInspector(QWidget):
open_raw=Signal(str)
select_version=Signal(int)
select_attempt=Signal(str)
def __init__(self,parent=None):
super().__init__(parent);self.evidence=None
layout=QVBoxLayout(self);layout.setContentsMargins(12,8,12,8)
@@ -50,6 +54,7 @@ class VerificationInspector(QWidget):
row=QHBoxLayout();self.components=QComboBox();self.components.setMinimumWidth(100)
self.versions=QComboBox();self.versions.setToolTip('查看历史输入版本,不改变当前输入')
row.addWidget(self.components,1);row.addWidget(self.versions);layout.addLayout(row)
self.attempts=QComboBox();layout.addWidget(self.attempts)
self.issues=QComboBox();layout.addWidget(self.issues)
self.tabs=QTabWidget();layout.addWidget(self.tabs,1)
self.diagram=ConnectionDiagram();scroll=QScrollArea();scroll.setWidgetResizable(True);scroll.setWidget(self.diagram)
@@ -65,12 +70,18 @@ class VerificationInspector(QWidget):
self.components.currentIndexChanged.connect(self._component)
self.issues.currentIndexChanged.connect(self._issue)
self.versions.activated.connect(lambda _:self.select_version.emit(self.versions.currentData()))
self.attempts.activated.connect(lambda _:self.select_attempt.emit(self.attempts.currentData()) if self.attempts.currentData() else None)
def set_record(self,record):
self.versions.blockSignals(True);self.versions.clear()
for version in sorted({record['current_version'],*(h['input_version'] for h in record['history'])},reverse=True):
for version in record.get('versions',sorted({record['current_version'],*(h['input_version'] for h in record['history'])},reverse=True)):
self.versions.addItem(f'输入 v{version}',version)
self.versions.setCurrentIndex(self.versions.findData(record['input_version']));self.versions.blockSignals(False)
self.attempts.clear()
for entry in record['history']:
if entry['input_version']==record['input_version']:
self.attempts.addItem(f"第 {entry['generation']} 次校验 · {ATTEMPTS.get(entry['state'],'未完成')}",entry['attempt_id'])
self.attempts.setCurrentIndex(self.attempts.findData(record.get('attempt_id')))
result=((record.get('attempt') or {}).get('result') or {})
if record.get('evidence_error'):
self.set_evidence(None);self.heading.setText(record['display_name']+' · 证据不可用')
@@ -83,20 +94,27 @@ class VerificationInspector(QWidget):
def set_evidence(self,evidence):
if evidence:verify_evidence(evidence)
previous=self.components.currentData()
self.evidence=evidence;self.components.blockSignals(True);self.components.clear();self.issues.blockSignals(True);self.issues.clear();self.raw.clear()
if evidence:
for key in sorted({tuple(p['endpoint'][:2]) for p in evidence['pins']}):self.components.addItem(f'{key[1]} · {key[0]}',key)
self.issues.addItem('全部问题',None)
for issue in evidence['issues']:self.issues.addItem(f"{issue.get('refdes','工程')} · {issue['reason']}",issue)
def priority(issue):
related=sum(i.get('refdes')==issue.get('refdes') and i.get('instance_path')==issue.get('instance_path') for i in evidence['issues'])
return (0 if issue['state']=='error' else 1,-related,issue.get('refdes',''))
for issue in sorted(evidence['issues'],key=priority):self.issues.addItem(f"{issue.get('refdes','工程')} · {issue['reason']}",issue)
for raw in evidence['binding'].get('raw',[]):self.raw.addItem(raw['artifact_id'],raw['artifact_id'])
self.coverage.setText('由网表生成 · 图页未定位\n未覆盖:封装库内部映射、引脚级 Value')
self.components.blockSignals(False);self.issues.blockSignals(False);self._component()
old=next((n for n in range(self.components.count()) if self.components.itemData(n)==previous),-1)
if old>=0:self.components.setCurrentIndex(old)
elif self.issues.count()>1:self.issues.setCurrentIndex(1);self._issue()
def _issue(self):
issue=self.issues.currentData()
if issue:
key=(issue.get('instance_path'),issue.get('refdes'))
index=self.components.findData(key)
index=next((n for n in range(self.components.count()) if tuple(self.components.itemData(n))==key),-1)
if index>=0:self.components.setCurrentIndex(index)
def _component(self):
@@ -2,6 +2,7 @@
from threading import Event
from uuid import uuid4
from PySide6.QtCore import Qt,QTimer,Signal,QSignalBlocker
from PySide6.QtGui import QColor
from PySide6.QtWidgets import (QWidget,QVBoxLayout,QHBoxLayout,QLabel,QPushButton,QListWidget,QListWidgetItem,
QTableWidget,QTableWidgetItem,QSplitter,QLineEdit,QComboBox,QInputDialog,QFileDialog,QHeaderView)
from .verification_controller import VerificationController
@@ -18,6 +19,9 @@ class VerificationWorkspace(QWidget):
self._active=False;self._closed=False;self._run_id=None;self._rows=[];self._cursor=None;self._intake_stop=Event()
layout=QVBoxLayout(self);layout.setContentsMargins(16,12,16,12)
head=QHBoxLayout();self.title=QLabel('工程校验',objectName='verificationTitle');head.addWidget(self.title);head.addStretch()
self.title.setStyleSheet('font-size:20px;font-weight:600;color:#34445b')
self._scroll_to_selection=False;self._view_version=None;self._view_attempt=None;self._selected_attempt=None
self._last_revision=None
self.new_button=QPushButton('新建校验',objectName='verificationNew');self.import_button=QPushButton('添加工程对')
head.addWidget(self.import_button);head.addWidget(self.new_button);layout.addLayout(head)
description=QLabel('替换完成后接续核对,也可随时添加两份工程独立校验。');description.setWordWrap(True);layout.addWidget(description)
@@ -48,6 +52,7 @@ class VerificationWorkspace(QWidget):
self.selected_button.clicked.connect(lambda:self._start(True));self.stop_button.clicked.connect(self._stop)
self.rerun_button.clicked.connect(self._rerun);self.export_button.clicked.connect(self._export)
self.inspector.open_raw.connect(self._open_raw);self.inspector.select_version.connect(self._version)
self.inspector.select_attempt.connect(self._attempt)
self.controller.failed.connect(self._error);self.controller.changed.connect(self._gates)
self._timer=QTimer(self);self._timer.setInterval(1500);self._timer.timeout.connect(self.refresh)
self._debounce=QTimer(self);self._debounce.setSingleShot(True);self._debounce.setInterval(250);self._debounce.timeout.connect(self.refresh_task)
@@ -83,11 +88,14 @@ class VerificationWorkspace(QWidget):
for row in result['tasks']:
item=QListWidgetItem(row['name']+f" {row['summary']['processed']}/{row['summary']['total']}")
item.setData(Qt.ItemDataRole.UserRole,row['task_id']);self.tasks.addItem(item)
item.setToolTip(row['name'])
if row['task_id']==self.controller.task_id:self.tasks.setCurrentItem(item)
if not self.controller.task_id and self.tasks.count():self.open_task(self.tasks.item(0).data(Qt.ItemDataRole.UserRole))
def open_task(self,task_id,item_id=None):
self.controller.task_id=task_id;self.controller.item_id=item_id;self._cursor=None
self._scroll_to_selection=True;self._view_version=None;self._view_attempt=None;self._selected_attempt=None
self._rows=[];self._last_revision=None
self.controller.item_query.invalidate();self.inspector.set_evidence(None);self.refresh();self._gates()
def _task_selected(self,item,previous):
@@ -103,6 +111,9 @@ class VerificationWorkspace(QWidget):
query=self.search.text(),cursor=cursor,read_control=control),lambda result:self._task_received(result,append),self._error,cancellable=True)
def _task_received(self,result,append):
if not append and result['view_revision']==self._last_revision and len(self._rows)>100:
self._gates();return
self._last_revision=result['view_revision']
self._rows=self._rows+result['items'] if append else result['items'];self._cursor=result['cursor']
selected=self.controller.item_id
with QSignalBlocker(self.table):
@@ -110,20 +121,34 @@ class VerificationWorkspace(QWidget):
for n,row in enumerate(self._rows):
for col,value in enumerate((row['display_name'],str(row['input_version']),LABELS[row['status']],row['scope'])):
cell=QTableWidgetItem(value);cell.setData(Qt.ItemDataRole.UserRole,row['item_id']);self.table.setItem(n,col,cell)
cell.setToolTip(value)
if col==2:cell.setForeground(QColor({'different':'#b83d4a','warning':'#9c6b1e','consistent':'#39817d'}.get(row['status'],'#61758e')))
if row['item_id']==selected:self.table.selectRow(n)
if self._scroll_to_selection and self.table.currentRow()>=0:
self.table.scrollToItem(self.table.item(self.table.currentRow(),0));self._scroll_to_selection=False
self.more_button.setEnabled(bool(self._cursor))
s=result['summary'];self.footer.setText(f"已处理 {s['processed']}/{s['total']} · 一致 {s['consistent']} · 关注 {s['warning']} · 异常 {s['different']} · 无法校验 {s['unavailable']} · 待校验 {s['waiting']}")
if selected:self._load_item(selected)
if selected:self._load_item(selected,self._view_version,self._view_attempt)
self._gates()
def _item_selected(self):
row=self.table.currentRow()
if 0<=row<len(self._rows):self.controller.item_id=self._rows[row]['item_id'];self._load_item(self.controller.item_id);self._gates()
if 0<=row<len(self._rows):
self._view_version=None;self._view_attempt=None;self.controller.item_id=self._rows[row]['item_id'];self._load_item(self.controller.item_id);self._gates()
def _load_item(self,item,version=None):
self.controller.item_query.request(lambda control:self.service.read_item(item,version=version,read_control=control),self.inspector.set_record,self._error,cancellable=True)
def _load_item(self,item,version=None,attempt=None):
self.controller.item_query.request(lambda control:self.service.read_item(item,version=version,attempt_id=attempt,read_control=control),self._record_received,self._error,cancellable=True)
def _record_received(self,record):
self._selected_attempt=record['attempt_id'];self.inspector.set_record(record)
def _attempt(self,attempt):
self._view_attempt=attempt
if self.controller.item_id:self._load_item(self.controller.item_id,attempt=attempt)
def _version(self,version):
self._view_version=version
self._view_attempt=None
if self.controller.item_id:self._load_item(self.controller.item_id,version)
def _new(self):
@@ -158,15 +183,13 @@ class VerificationWorkspace(QWidget):
if folder:self.controller.command(lambda:self.service.export_task(task,folder,request_id=uuid4().hex),lambda result:self.notice.setText('报告已保存:'+str(result)))
def _open_raw(self,artifact):
item=self.controller.item_id
if item:
def action():
record=self.service.read_item(item);return self.service.open_evidence(record['attempt_id'],artifact)
self.controller.command(action,lambda _:None)
attempt=self._selected_attempt
if attempt:self.controller.command(lambda:self.service.open_evidence(attempt,artifact),lambda _:None)
def begin_shutdown(self):
self._timer.stop();self._intake_stop.set()
if hasattr(self.service,'begin_shutdown'):self.service.begin_shutdown()
def shutdown(self):
if self._closed:return
self._closed=True;self.begin_shutdown();self.controller.close()
@@ -88,16 +88,18 @@ def rollup_results(checks, *, required_checks, optional_checks=()):
if not required_checks or any(key not in CHECKS for key in (*required_checks,*optional_checks)):
fail('必查项目不能为空。', 'verification_check_plan')
states = {}
partial = set()
for row in checks:
key, state = row.get('check_id'), row.get('state')
if key not in CHECKS or state not in STATES or key in states:
fail('检查结果包含重复或未知项目。', 'verification_result')
states[key] = state
if row.get('coverage')=='partial': partial.add(key)
requested = tuple(dict.fromkeys((*required_checks,*optional_checks)))
unknown = [key for key in requested if states.get(key, 'unknown') in {'unknown','not_requested'}]
unknown = [key for key in requested if key in partial or states.get(key, 'unknown') in {'unknown','not_requested'}]
if any(state=='error' for state in states.values()):
verdict = 'DIFFERENT'
elif any(states.get(key,'unknown') in {'unknown','not_requested'} for key in required_checks):
elif any(key in unknown for key in required_checks):
verdict = 'INCOMPLETE'
elif any(state=='warning' for state in states.values()):
verdict = 'WARNING'
@@ -9,13 +9,14 @@ from .store import encode,now
class VerificationControl:
def __init__(self,service):
self.service=service;self.repo=service.repo;self.lock=RLock();self.events={};self.thread=None;self.closing=False
self.last_error=None
@property
def busy(self):
with self.lock:return bool(self.thread and self.thread.is_alive())
def start(self,task_id,*,selection,request_id):
if self.closing:fail('校验执行器正在安全关闭。')
if self.closing:fail('校验执行器已暂停:'+self.last_error if self.last_error else '校验执行器正在安全关闭。')
body=[task_id,selection]
with self.repo.store.transaction():
old=self.repo._request('start',request_id,body)
@@ -87,6 +88,12 @@ class VerificationControl:
state='blocked' if blocked else 'stopped' if event.is_set() or self.closing else 'completed'
self.repo.connection.execute('UPDATE verification_runs SET state=? WHERE run_id=?',(state,run['run_id']))
self.repo._touch(run['task_id'])
except Exception as error:
self.closing=True;self.last_error=str(error)
from ..batch_resources import write_record
try:write_record(self.service.data_root/'verification/engine-paused.json',{
'reason':str(error),'error':type(error).__name__,'replayed':False})
except OSError:pass
finally:
with self.lock:
self.thread=None
@@ -127,6 +134,7 @@ class VerificationControl:
return result
def begin_shutdown(self):
if self.closing:return
self.closing=True
with self.repo.store._lock:
runs=[r[0] for r in self.repo.connection.execute("SELECT run_id FROM verification_runs WHERE state IN ('queued','running','stopping')")]
@@ -53,6 +53,7 @@ def inspect_pin_metadata(export,*,evidence_root):
def compare_metadata(before,after):
left={tuple(p['endpoint']):p for p in before['pins']};right={tuple(p['endpoint']):p for p in after['pins']}
return {'comparisons':{str(key):{phase:{name:row[name]['value'] for name in ('pin_value','electrical_type')}
return {'comparisons':{str(key):dict({phase:{name:row[name]['value'] for name in ('pin_value','electrical_type')}
for phase,row in (('before',left[key]),('after',right[key]))}
,endpoint=list(key))
for key in left.keys()&right.keys()}}
@@ -20,7 +20,7 @@ def project(row):
elif state=='succeeded': status={'CONSISTENT':'consistent','WARNING':'warning','DIFFERENT':'different'}.get(verdict,'unavailable')
else: status='waiting'
row.update(status=status,can_start=row['input_state']=='ready' and state not in ACTIVE,
scope='已核对换料规则' if row.get('expectation_ref') else '未核对换料规则')
scope='包含固定换料规则' if row.get('expectation_ref') else '未核对换料规则')
return row
@@ -68,10 +68,15 @@ class VerificationQueries:
result=[]
for row in rows:
checkpoint(control);row=project(row)
if self.validator and row['attempt_state']=='succeeded':self._validate(row,self.repo.attempt(row['attempt_id']))
result.append(row)
return result
def validate_rows(self,rows,control=None):
for row in rows:
checkpoint(control)
if self.validator and row['attempt_state']=='succeeded':self._validate(row,self.repo.attempt(row['attempt_id']))
return rows
def list_tasks(self,*,query='',cursor=None,limit=50,read_control=None):
with self.repo.store.transaction():
tasks=[]
@@ -79,37 +84,48 @@ class VerificationQueries:
checkpoint(read_control)
row=dict(row)
if query.casefold() in row['name'].casefold():
row['summary']=summarize_items(self._rows(row['task_id'],read_control));tasks.append(row)
row['_rows']=self._rows(row['task_id'],read_control);tasks.append(row)
binding=digest([query,[(r['task_id'],r['view_revision']) for r in tasks]])
page,next_cursor=paginate(tasks,cursor,limit,binding,50)
return {'tasks':page,'cursor':next_cursor}
for row in page:row['summary']=summarize_items(self.validate_rows(row.pop('_rows'),read_control))
return {'tasks':page,'cursor':next_cursor}
def read_task(self,task_id,*,state='',query='',cursor=None,limit=100,read_control=None):
with self.repo.store.transaction():
task=self.repo.task(task_id);rows=self._rows(task_id,read_control)
filtered=[]
for row in rows:
checkpoint(read_control)
if state and row['status']!=state:continue
text=row['display_name']+' '+row['project_key']
if query and row.get('attempt_id'):
text+=' '+(self.repo.attempt(row['attempt_id'])['result_json'] or '')
if query.casefold() in text.casefold():filtered.append(row)
binding=digest([task_id,task['view_revision'],state,query])
page,next_cursor=paginate(filtered,cursor,limit,binding,100)
return dict(task,items=page,cursor=next_cursor,summary=summarize_items(rows))
self.validate_rows(rows,read_control)
filtered=[]
for row in rows:
checkpoint(read_control)
if state and row['status']!=state:continue
text=row['display_name']+' '+row['project_key']
if query and row.get('attempt_id'):text+=' '+(self.repo.attempt(row['attempt_id'])['result_json'] or '')
if query.casefold() in text.casefold():filtered.append(row)
binding=digest([task_id,task['view_revision'],state,query])
page,next_cursor=paginate(filtered,cursor,limit,binding,100)
return dict(task,items=page,cursor=next_cursor,summary=summarize_items(rows))
def read_item(self,item_id,*,version=None,read_control=None):
def read_item(self,item_id,*,version=None,attempt_id=None,read_control=None):
row=self.snapshot_item(item_id,version=version,attempt_id=attempt_id,read_control=read_control)
return self._validate(row,row['attempt'])
def snapshot_item(self,item_id,*,version=None,attempt_id=None,read_control=None):
with self.repo.store.transaction():
checkpoint(read_control)
item=self.repo.item(item_id);version=version or item['current_version']
revision=self.repo.revision(item_id,version);attempt=self.repo.latest_attempt(item_id,version)
item=self.repo.item(item_id)
attempt=self.repo.attempt(attempt_id) if attempt_id else None
if attempt:
if attempt['item_id']!=item_id or (version is not None and attempt['input_version']!=version):fail('历史尝试不属于该工程版本。')
version=attempt['input_version']
version=version or item['current_version']
revision=self.repo.revision(item_id,version);attempt=attempt or self.repo.latest_attempt(item_id,version)
row=dict(item,**{k:v for k,v in revision['payload'].items() if k not in item})
row.update(input_version=version,attempt_id=attempt['attempt_id'] if attempt else None,
attempt_state=attempt['state'] if attempt else None,reason=attempt['reason'] if attempt else '',
verdict=(attempt['result'] or {}).get('verdict') if attempt else None)
history=[dict(r) for r in self.repo.connection.execute('SELECT input_version,generation,attempt_id,state FROM verification_attempts WHERE item_id=? ORDER BY input_version DESC,generation DESC',(item_id,))]
return dict(self._validate(project(row),attempt),payload=revision['payload'],attempt=attempt,history=history)
versions=[r[0] for r in self.repo.connection.execute('SELECT input_version FROM verification_input_revisions WHERE item_id=? ORDER BY input_version DESC',(item_id,))]
return dict(project(row),payload=revision['payload'],attempt=attempt,history=history,versions=versions)
def read_issues(self,attempt_id,*,kind='',cursor=None,limit=100,read_control=None):
checkpoint(read_control)
@@ -57,7 +57,7 @@ def item_html(result):
for pin in subset:
out.append(f'<tr><td>{text(pin["endpoint"][2])}</td><td><pre>{text(pin["before"])}</pre></td><td><pre>{text(pin["after"])}</pre></td><td>{"连接变化" if pin["connection_changed"] else "文字变化" if pin["text_changed"] else "未发现变化"}</td></tr>')
out.append('</table>')
out.append('<h2>判断依据与范围</h2><pre>'+text({key:result.get(key) for key in ('checks','issues','uncovered','attempt_id','input_version','input_digest','policy')})+'</pre>')
out.append('<h2>判断依据与范围</h2><pre>'+text({key:result.get(key) for key in ('attempt_state','reason','resource_state','checks','issues','uncovered','attempt_id','input_version','input_digest','policy')})+'</pre>')
out.append('<h2>原始证据定位与摘要</h2><pre>'+text(evidence.get('binding',{}))+'</pre>')
return ''.join(out)
@@ -88,10 +88,11 @@ def export_task(service,task_id,destination,*,request_id):
return path
with service.repo.store.transaction():
task=service.repo.task(task_id);rows=service.queries._rows(task_id)
records=[service.read_item(row['item_id']) for row in rows]
for row in records:
if row.get('evidence_error'):fail('证据不可用,不能导出为有效报告:'+row['evidence_error'])
records=[service.queries.snapshot_item(row['item_id']) for row in rows]
snapshot=dict(task,items=records)
for row in records:
service.queries._validate(row,row['attempt'])
if row.get('evidence_error'):fail('证据不可用,不能导出为有效报告:'+row['evidence_error'])
root=Path(destination).resolve();root.mkdir(parents=True,exist_ok=True)
output=root/f'verification-{task_id[:12]}-v{task["view_revision"]}-{digest(request_id)[:8]}'
if output.exists():fail('报告目录已存在。')
@@ -86,6 +86,12 @@ def evaluate(before,after,*,expectations,check_plan,pin_metadata=None):
issue('components','error','器件位号或实例范围增减',key=key,
left=key in matched['before'],right=key in matched['after'])
else:issue('components','unknown','器件身份或覆盖无法唯一证明')
if complete:
for key,(lid,rid) in matched['matches'].items():
lnums=[p.get('number') for p in left['components'][lid].get('pins',{}).values()]
rnums=[p.get('number') for p in right['components'][rid].get('pins',{}).values()]
if lnums and rnums and all(lnums+rnums) and Counter(lnums)!=Counter(rnums):
issue('physical_pins','error','物理脚号或占用次数变化',key=key,left=lnums,right=rnums)
views=[]
try:
if not complete:raise ValueError('导出不完整')
@@ -93,7 +99,8 @@ def evaluate(before,after,*,expectations,check_plan,pin_metadata=None):
except (ValueError,KeyError,TypeError) as error:
issue('coverage','unknown',str(error))
if views:
states['physical_pins']=states['connections']=states['net_names']='equal'
if states['physical_pins']!='error':states['physical_pins']='equal'
states['connections']=states['net_names']='equal'
states['pin_text']='equal' if 'pin_text' in requested else 'not_requested'
states['pin_semantics']='equal' if 'pin_semantics' in requested else 'not_requested'
lp,rp=views
@@ -141,12 +148,23 @@ def evaluate(before,after,*,expectations,check_plan,pin_metadata=None):
for endpoint,fields in pin_metadata.get('comparisons',{}).items():
l,r=fields.get('before',{}).get(key),fields.get('after',{}).get(key)
if l is not None and r is not None and l!=r:
issue('pin_text' if key=='pin_value' else 'pin_semantics','warning','引脚字段变化,需人工确认',left=l,right=r,field=key)
bound=fields.get('endpoint')
issue('pin_text' if key=='pin_value' else 'pin_semantics','warning','引脚字段变化,需人工确认',
key=tuple(bound[:2]) if bound else None,pin=bound[2] if bound else None,left=l,right=r,field=key)
if 'export_identity' in requested:
diffs=[g.get('identity_tables',{}).get('keyin',{}).get('part_number_differences',[]) for g in (left,right)]
states['export_identity']='warning' if any(diffs) else 'equal'
if any(diffs):issue('export_identity','warning','原生身份表与有效料号存在差异',left=diffs[0],right=diffs[1])
checks=[{'check_id':key,'state':states[key],'issues':[i['issue_id'] for i in issues if i['check_id']==key]} for key in sorted(CHECKS)]
# This dimension covers names AND pin-level Value. Native text has not proven Value.
for check in checks:
if check['check_id']=='pin_text' and 'pin_text' in requested:
check.update(coverage='partial',unknown_fields=['pin_value'])
if check['check_id']=='pin_semantics' and 'pin_semantics' in requested:
expected={e for e in views[0] if e[:2] in matched['matches']} if views else set()
proven={tuple(fields['endpoint']) for fields in (pin_metadata or {}).get('comparisons',{}).values()
if fields.get('endpoint') and all(fields.get(phase,{}).get('electrical_type') is not None for phase in ('before','after'))}
if not expected or not expected<=proven:check.update(coverage='partial',unknown_fields=['electrical_type'])
return dict(rollup_results(checks,required_checks=plan['required_checks'],optional_checks=plan['optional_checks']),
checks=checks,issues=issues,scope='已核对换料规则' if declared else '未核对换料规则',
uncovered=['封装库内部引脚到焊盘映射','引脚级 Value(原生输出未证明)'])
@@ -12,9 +12,10 @@ _native_lock=Lock()
def can_start_native_export(service):
from ..native_cli import _UNCERTAIN_SCOPES
with service.repo.store._lock:
held=service.repo.connection.execute("SELECT 1 FROM verification_attempts WHERE state='stopping' OR resource_state='unknown' LIMIT 1").fetchone()
if held or pending_resources(service.data_root):return {'allowed':False,'reason':'资源退出尚未确认'}
if held or _UNCERTAIN_SCOPES or pending_resources(service.data_root):return {'allowed':False,'reason':'资源退出尚未确认'}
return {'allowed':not _native_lock.locked(),'reason':'原生导出忙' if _native_lock.locked() else ''}
@@ -52,7 +53,7 @@ def run_attempt(service,attempt_id,*,stop_event):
metadata={phase:inspect_pin_metadata(export,evidence_root=output) for phase,export in (('before',left),('after',right))}
result=dict(evaluate(left,right,expectations=expected,check_plan=payload['check_plan'],
pin_metadata=compare_metadata(metadata['before'],metadata['after'])),
before=left,after=right,attempt_state='succeeded',resource_state='released')
before=left,after=right,attempt_state='succeeded' if all(e.get('status')=='success' for e in (left,right)) else 'failed',resource_state='released')
result['pin_metadata']=metadata
result.update(item_id=attempt['item_id'],input_version=attempt['input_version'],attempt_id=attempt_id,
generation=attempt['generation'],input_digest=payload['payload_digest'],policy=payload['check_plan'])
@@ -71,6 +72,10 @@ def run_attempt(service,attempt_id,*,stop_event):
write_record(output/'result-ready.json',{'result_ref':ref})
check_cancelled(stop_event)
published=service.repo.finish(attempt_id,generation=attempt['generation'],result=result)
if not published and stop_event.is_set():
service.repo.finish(attempt_id,generation=attempt['generation'],result={
'attempt_state':'cancelled','resource_state':'released','verdict':'INCOMPLETE','reason':'用户停止先于结果提交',
'attempt_id':attempt_id,'input_version':attempt['input_version'],'checks':[],'issues':[]})
return dict(result,published=published)
except Exception as error:
if attempt:
@@ -61,6 +61,7 @@ class VerificationService:
validate_result(stored,self.data_root)
payload=self.repo.revision(attempt['item_id'],attempt['input_version'])['payload']
for key in ('before_ref','after_ref'):self.artifacts.read(payload[key],'snapshot')
if payload['expectation_ref']:self.artifacts.read(payload['expectation_ref'],'expectations')
def open_evidence(self, attempt_id, artifact_id):
attempt=self.repo.attempt(attempt_id);self.validate_attempt(attempt)
@@ -80,6 +81,15 @@ class VerificationService:
with self.repo.store._lock:
old = self.repo._request('ingest',submission_id,body)
if old is not None: return old
normalized=self._validated_inputs(inputs)
with self.repo.store.transaction():
old=self.repo._request('ingest',submission_id,body)
if old is not None:return old
result=self.repo.publish(task_id,tuple(normalized),submission_id='ingest:'+submission_id)
return self.repo._remember('ingest',submission_id,body,result)
def _validated_inputs(self, inputs):
# Snapshot hashing can be slow; never run it inside a store transaction.
normalized=[]
for value in inputs:
if not isinstance(value,dict):
@@ -92,11 +102,7 @@ class VerificationService:
except (ValueError,OSError) as error:
row['unavailable_reason']=str(error)
normalized.append(row)
with self.repo.store.transaction():
old=self.repo._request('ingest',submission_id,body)
if old is not None:return old
result=self.repo.publish(task_id,tuple(normalized),submission_id='ingest:'+submission_id)
return self.repo._remember('ingest',submission_id,body,result)
return normalized
def import_pair(self, task_id, before, after, *, request_id, stop_event):
body=[task_id,str(before),str(after)]
@@ -114,8 +120,9 @@ class VerificationService:
'display_name':after.stem,'input_version':1,'before_ref':left,'after_ref':right,
'expectation_ref':None,'check_plan':default_plan()}
check_cancelled(stop_event)
normalized=self._validated_inputs((row,))
with self.repo.store.transaction():
result=self.publish_inputs(task_id,(row,),submission_id='import:'+request_id)
result=self.repo.publish(task_id,tuple(normalized),submission_id='import:'+request_id)
return self.repo._remember('import',request_id,body,result)
def receive_successful_results(self, result_ref, *, submission_id):
@@ -170,8 +177,9 @@ class VerificationService:
with self.repo.store.transaction():
self.repo._remember('handoff-row',delivery_key,report,row)
rows.append(row)
normalized=self._validated_inputs(rows)
with self.repo.store.transaction():
result=self.publish_inputs(task,tuple(rows),submission_id='handoff:'+submission_id)
result=self.repo.publish(task,tuple(normalized),submission_id='handoff:'+submission_id)
result['task_id']=task
return self.repo._remember('handoff',submission_id,result_ref,result)
@@ -37,6 +37,8 @@ def create_schema(c):
FOREIGN KEY(item_id,input_version) REFERENCES verification_input_revisions(item_id,input_version))''',
'''CREATE UNIQUE INDEX IF NOT EXISTS verification_active_attempt ON verification_attempts(item_id,input_version)
WHERE state IN ('queued','running','publishing','stopping')''',
'''CREATE UNIQUE INDEX IF NOT EXISTS verification_attempt_generation
ON verification_attempts(item_id,input_version,generation DESC)''',
'''CREATE TABLE IF NOT EXISTS verification_runs (
run_id TEXT PRIMARY KEY, task_id TEXT NOT NULL REFERENCES verification_tasks(task_id),
members_json TEXT NOT NULL, stop_requested INTEGER NOT NULL DEFAULT 0,
@@ -179,6 +181,9 @@ class VerificationRepository:
if result.get('resource_state') != 'released': fail('资源退出尚未确认。','verification_resources')
state = result.get('attempt_state','succeeded')
if state not in TERMINAL: fail('无效校验终态。')
if attempt['run_id'] and state not in {'cancelled','interrupted'}:
run=self.connection.execute('SELECT stop_requested FROM verification_runs WHERE run_id=?',(attempt['run_id'],)).fetchone()
if run and run[0]:return False
self.connection.execute('UPDATE verification_attempts SET state=?,result_json=?,resource_state=?,updated=? WHERE attempt_id=?',
(state,encode(result),'released',now(),attempt_id))
self._touch(self.item(attempt['item_id'])['task_id'])
+22
View File
@@ -0,0 +1,22 @@
from threading import Event
def test_mixed_result_inspector_shows_error_and_keeps_new_task_enabled(ui,qtbot):
from pathlib import Path
import sys
sys.path.insert(0,str(Path(__file__).parents[1]/'v1_1'))
from test_independent_verification_rules import export,evaluate
from dx_productivity.trial_task_center.verification.evidence import build_evidence
from test_independent_verification_contracts import payload
import copy
v=ui.service.verification;task=v.create_task('人工复核',request_id='accept')['task_id']
row=payload();item=v.repo.publish(task,(row,),submission_id='direct')['accepted'][0]['item_id']
a=export();b=copy.deepcopy(a);b['graph']['components']['a']['pins']['loop']['number']='2';b['graph']['components']['a']['pins']['GND']['number']='1'
result=evaluate(a,b);result.update(resource_state='released',evidence=build_evidence(a['graph'],b['graph'],result['issues'],binding={}))
attempt=v.repo.create_attempt(item,1,request_id='a');v.repo.claim(attempt['attempt_id'],owner_id='controlled')
v.repo.finish(attempt['attempt_id'],generation=1,result=result)
page=ui.window.verification_panel;page.open_task(task,item);ui.window.verification_action.trigger()
qtbot.waitUntil(lambda:'异常' in page.inspector.heading.text())
assert page.new_button.isEnabled() and page.inspector.pin_table.rowCount()==2
assert page.inspector.diagram.pins[0]['endpoint'][2]=='1'
assert '已处理 1/1' in page.footer.text()
+10
View File
@@ -6,3 +6,13 @@ def test_close_and_controls_do_not_block_new_task_creation(ui,qtbot):
assert page.start_button.isEnabled() and page.new_button.isEnabled()
page.begin_shutdown()
assert page.new_button.isEnabled()
def test_shutdown_is_idempotent_after_store_is_released(ui,qtbot):
page=ui.window.verification_panel
page.shutdown()
original=page.service.begin_shutdown
def forbidden():raise AssertionError('closed page must not access released store')
page.service.begin_shutdown=forbidden
try:page.shutdown()
finally:page.service.begin_shutdown=original
@@ -0,0 +1,68 @@
import copy
import json
from pathlib import Path
from threading import Event
from test_independent_verification_intake import service
from test_independent_verification_runner import imported
from test_independent_verification_rules import export
from test_verification_control import wait_idle
def test_end_to_end_mixed_batch_is_nonblocking_and_exports_same_evidence(service,tmp_path,monkeypatch):
from dx_productivity.trial_task_center import netlist_verification
from dx_productivity.trial_task_center.history_store import HistoryRepository
from dx_productivity.trial_task_center.retention import maintain_quick_run_storage
task,item=imported(service,tmp_path)
original=service.repo.revision(item,1)['payload']
rows=[]
for key in ('rename','swap','missing'):
row={k:v for k,v in original.items() if k not in {'payload_digest','input_state'}};row['item_key']=key;row['display_name']=key
if key=='missing':row['before_ref']=None
rows.append(row)
service.publish_inputs(task,rows,submission_id='batch')
def native(capture,output,*,stop_event):
graph=export()
aid=output.parent.name;attempt=service.repo.attempt(aid);name=service.repo.item(attempt['item_id'])['display_name']
if output.name=='after':
if name=='swap':
graph['graph']['components']['a']['pins']['loop']['number']='2';graph['graph']['components']['a']['pins']['GND']['number']='1'
if name=='rename':
graph['graph']['components']['a']['pins']['outloop']=graph['graph']['components']['a']['pins'].pop('loop')
graph['graph']['nets'][0]['endpoints'][0][1]='outloop'
return graph
monkeypatch.setattr(netlist_verification,'_export_saved_capture',native)
run=service.start(task,request_id='all');wait_idle(service)
summary=service.read_task(task)['summary']
assert [summary[k] for k in ('consistent','warning','different','unavailable')]==[1,1,1,1]
report=service.export_task(task,tmp_path/'reports',request_id='report')
saved=json.loads((report/'task.json').read_text(encoding='utf-8'))
swapped=next(r for r in saved['items'] if r['display_name']=='swap')
assert swapped['attempt']['result']['verdict']=='DIFFERENT'
assert any(p['connection_changed'] for p in swapped['attempt']['result']['evidence']['pins'])
history=HistoryRepository(service.repo.store);assert history.page(query='工程校验').total==3
snapshot=history.clear_snapshot();history.clear(snapshot.cutoff_id)
maintain_quick_run_storage(service.data_root,max_age_days=0,min_entries=0)
assert service.read_item(item)['status']=='consistent'
assert service.repo.store._connection.execute('SELECT COUNT(*) FROM execution_operations').fetchone()[0]==0
def test_required_pin_text_does_not_claim_unread_pin_value_is_equal():
from dx_productivity.trial_task_center.verification.rules import evaluate
from dx_productivity.trial_task_center.verification.contracts import default_plan
plan=default_plan();plan['optional_checks'].remove('pin_text');plan['required_checks'].append('pin_text')
assert evaluate(export(),export(),expectations=None,check_plan=plan)['verdict']=='INCOMPLETE'
def test_acceptance_cli_labels_controlled_format_evidence(tmp_path):
import subprocess,sys
from test_native_cli_netlist import project_fixture,graph
fixture=tmp_path/'fixture'
for phase in ('before','after'):
folder=fixture/phase;folder.mkdir(parents=True)
project_fixture(folder);graph(folder)
script=Path(__file__).parents[2]/'tools/verify_independent_verification.py'
result=subprocess.run([sys.executable,str(script),'--fixture-root',str(fixture),'--output',str(tmp_path/'acceptance')],capture_output=True,text=True,timeout=20)
assert result.returncode==0,result.stderr
summary=json.loads((tmp_path/'acceptance/acceptance.json').read_text(encoding='utf-8'))
assert summary['evidence_kind']=='controlled-format-fixture' and summary['inputs_unchanged']
assert summary['replacement_operations']==0
@@ -11,8 +11,14 @@ from test_native_cli_netlist import project_fixture
def service(tmp_path):
from dx_productivity.trial_task_center.verification.service import VerificationService
store = TaskStore(tmp_path/'tasks.db')
try: yield VerificationService(store,tmp_path/'data')
finally: store.close()
verification=VerificationService(store,tmp_path/'data')
try: yield verification
finally:
verification.begin_shutdown()
thread=verification.control.thread
if thread is not None:thread.join(10)
assert not verification.busy,'Verification must finish before its store is closed'
store.close()
def test_pair_import_creates_same_input_contract_without_replacement(service,tmp_path):
@@ -84,3 +90,21 @@ def test_complete_delivery_can_be_reconciled_under_another_notification(service,
assert len(first['accepted'])==1
assert len(second['duplicates'])==1 and not second['rejected']
assert second['task_id']==first['task_id']
def test_import_evidence_validation_does_not_hold_store_lock(service,tmp_path,monkeypatch):
from threading import Thread
a=tmp_path/'a';b=tmp_path/'b';a.mkdir();b.mkdir()
before,after=project_fixture(a),project_fixture(b)
task=service.create_task('导入',request_id='c')['task_id']
read=service.artifacts.read;entered=Event();release=Event();created=Event();errors=[]
def slow(*args):entered.set();release.wait(5);return read(*args)
monkeypatch.setattr(service.artifacts,'read',slow)
def import_pair():
try:service.import_pair(task,before,after,request_id='i',stop_event=Event())
except Exception as error:errors.append(error)
worker=Thread(target=import_pair);worker.start();assert entered.wait(3)
creator=Thread(target=lambda:(service.create_task('另一个',request_id='other'),created.set()));creator.start()
try:assert created.wait(.5)
finally:release.set();worker.join(5);creator.join(5)
assert not errors
@@ -39,3 +39,32 @@ def test_new_version_has_no_old_green_and_filters_are_literal(repo):
assert len(q.read_task(task,query='%_')['items'])==1
assert not q.read_task(task,query='missing')['items']
with pytest.raises(TaskCenterError):q.read_task(task,cursor={'offset':1,'binding':'bad'})
def test_slow_evidence_read_does_not_lock_task_creation(repo):
from threading import Event,Thread
from dx_productivity.trial_task_center.verification.queries import VerificationQueries
task=repo.create_task('读取',request_id='c')['task_id']
item=repo.publish(task,(payload(),),submission_id='s')['accepted'][0]['item_id']
a=repo.create_attempt(item,1,request_id='a');repo.claim(a['attempt_id'],owner_id='o')
repo.finish(a['attempt_id'],generation=1,result={'resource_state':'released','verdict':'CONSISTENT'})
entered=Event();release=Event();created=Event();q=VerificationQueries(repo)
def validate(_):entered.set();release.wait(3)
q.validator=validate
read=Thread(target=lambda:q.read_task(task));read.start();assert entered.wait(2)
writer=Thread(target=lambda:(repo.create_task('新任务',request_id='new'),created.set()));writer.start()
try:assert created.wait(.5)
finally:release.set();read.join(3);writer.join(3)
def test_previous_attempt_is_readable_without_replacing_current_result(repo):
from dx_productivity.trial_task_center.verification.queries import VerificationQueries
task=repo.create_task('历史',request_id='c')['task_id']
item=repo.publish(task,(payload(),),submission_id='s')['accepted'][0]['item_id']
attempts=[]
for n,verdict in enumerate(('DIFFERENT','CONSISTENT')):
a=repo.create_attempt(item,1,request_id=str(n));repo.claim(a['attempt_id'],owner_id='o')
repo.finish(a['attempt_id'],generation=a['generation'],result={'resource_state':'released','verdict':verdict});attempts.append(a)
q=VerificationQueries(repo)
assert q.read_item(item,attempt_id=attempts[0]['attempt_id'])['verdict']=='DIFFERENT'
assert q.read_item(item)['verdict']=='CONSISTENT'
@@ -84,3 +84,15 @@ def test_missing_pin_number_cannot_prove_equal_and_error_beats_unknown():
b['graph']['components']['b']['attributes']['Value']='WRONG'
result=evaluate(a,b,expectations={'changes':{}})
assert result['verdict']=='DIFFERENT' and result['unknown_checks']
def test_duplicate_physical_number_introduced_is_hard_error():
a=export();b=copy.deepcopy(a);b['graph']['components']['a']['pins']['loop']['number']='2'
result=evaluate(a,b)
assert result['verdict']=='DIFFERENT'
assert any(i['check_id']=='physical_pins' and i['state']=='error' for i in result['issues'])
def test_required_semantics_without_proven_type_is_incomplete():
plan=default_plan();plan['optional_checks'].remove('pin_semantics');plan['required_checks'].append('pin_semantics')
assert evaluate(export(),export(),check_plan=plan)['verdict']=='INCOMPLETE'
@@ -81,3 +81,31 @@ def test_schema_survives_reopen_and_does_not_change_execution_tables(tmp_path):
assert VerificationRepository(store).task(task['task_id'])['name'] == '持久任务'
assert store._connection.execute('SELECT COUNT(*) FROM execution_operations').fetchone()[0] == 0
finally: store.close()
def test_commit_acknowledgement_loss_can_be_retried_without_duplicates(repo,monkeypatch):
from contextlib import contextmanager
original=repo.store.transaction
fired=False
@contextmanager
def lost_reply():
nonlocal fired
with original():yield
if not fired:
fired=True;raise OSError('lost response after commit')
with monkeypatch.context() as patch:
patch.setattr(repo.store,'transaction',lost_reply)
with pytest.raises(OSError):repo.create_task('持久结果',request_id='lost')
result=repo.create_task('持久结果',request_id='lost')
assert repo.task(result['task_id'])['name']=='持久结果'
assert repo.connection.execute('SELECT COUNT(*) FROM verification_tasks').fetchone()[0]==1
def test_two_threads_cannot_claim_same_attempt(repo):
from concurrent.futures import ThreadPoolExecutor
task=repo.create_task('任务',request_id='c')['task_id']
item=repo.publish(task,(payload(),),submission_id='s')['accepted'][0]['item_id']
attempt=repo.create_attempt(item,1,request_id='a')
with ThreadPoolExecutor(2) as pool:
results=list(pool.map(lambda owner:repo.claim(attempt['attempt_id'],owner_id=owner),('one','two')))
assert sum(row is not None for row in results)==1
+32
View File
@@ -57,3 +57,35 @@ def test_recovery_never_automatically_runs_and_unknown_owner_blocks(service,tmp_
assert result['blocked']==1 and not service.busy
assert service.repo.attempt(attempt['attempt_id'])['state']=='stopping'
assert service.read_item(item)['verdict'] is None
def test_durable_stop_wins_race_with_final_result_commit(service,tmp_path,monkeypatch):
from dx_productivity.trial_task_center import netlist_verification
task,item=imported(service,tmp_path)
def native(capture,output,*,stop_event):
output.mkdir(parents=True,exist_ok=True)
return {'status':'success','complete':True,'graph':graph(output),'outputs':{}}
monkeypatch.setattr(netlist_verification,'_export_saved_capture',native)
finish=service.repo.finish
def stop_before_commit(attempt_id,*,generation,result):
if result.get('attempt_state')=='succeeded':
attempt=service.repo.attempt(attempt_id)
service.stop(attempt['run_id'],request_id='race-stop')
return finish(attempt_id,generation=generation,result=result)
monkeypatch.setattr(service.repo,'finish',stop_before_commit)
service.start(task,request_id='run');wait_idle(service)
assert service.read_item(item)['status']=='stopped'
def test_storage_failure_pauses_dispatcher_without_replaying_forever(service,tmp_path,monkeypatch):
from dx_productivity.trial_task_center import netlist_verification
task,item=imported(service,tmp_path);calls=[]
def native(capture,output,*,stop_event):
output.mkdir(parents=True,exist_ok=True)
return {'status':'success','complete':True,'graph':graph(output),'outputs':{}}
def unavailable(*args,**kwargs):calls.append(1);raise OSError('storage unavailable')
monkeypatch.setattr(netlist_verification,'_export_saved_capture',native)
monkeypatch.setattr(service.repo,'finish',unavailable)
service.start(task,request_id='run');wait_idle(service)
assert service.control.closing and len(calls)<=2
assert (service.data_root/'verification/engine-paused.json').is_file()
+19
View File
@@ -47,3 +47,22 @@ def test_corrupt_evidence_cannot_remain_green_or_export(service,tmp_path,monkeyp
assert service.read_item(item)['status']=='unavailable'
assert service.read_task(task)['summary']['consistent']==0
with pytest.raises(TaskCenterError):service.export_task(task,tmp_path/'reports',request_id='bad')
def test_missing_fixed_expectation_cannot_keep_a_green_result(service,tmp_path,monkeypatch):
from test_native_cli_netlist import graph
from dx_productivity.trial_task_center import netlist_verification
from dx_productivity.trial_task_center.verification.runner import run_attempt
_,item=imported(service,tmp_path)
expected=service.artifacts.put('expectations',{'changes':{}})
row={k:v for k,v in service.repo.revision(item,1)['payload'].items() if k not in {'payload_digest','input_state'}}
row.update(input_version=2,expectation_ref=expected)
service.publish_inputs(service.repo.item(item)['task_id'],(row,),submission_id='expectations')
def native(capture,output,*,stop_event):
output.mkdir(parents=True,exist_ok=True)
return {'status':'success','complete':True,'graph':graph(output),'outputs':{}}
monkeypatch.setattr(netlist_verification,'_export_saved_capture',native)
attempt=service.repo.create_attempt(item,2,request_id='a');run_attempt(service,attempt['attempt_id'],stop_event=Event())
assert service.read_item(item)['status']=='consistent'
(service.artifacts.directory(expected['manifest_id'])/'manifest.json').unlink()
assert service.read_item(item)['status']=='unavailable'
+77
View File
@@ -0,0 +1,77 @@
"""Acceptance through public verification interfaces; fixture/native evidence are labelled."""
import argparse
import json
from pathlib import Path
import shutil
import sys
import time
from threading import Event
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'src'))
from dx_productivity.trial_task_center.store import TaskStore
from dx_productivity.trial_task_center.verification.service import VerificationService
from dx_productivity.trial_task_center import native_netlist,netlist_verification
from dx_productivity.trial_task_center.batch_resources import write_record
def main(argv=None):
parser=argparse.ArgumentParser(description=__doc__)
group=parser.add_mutually_exclusive_group(required=True)
group.add_argument('--fixture-root',type=Path)
group.add_argument('--native-before',type=Path)
parser.add_argument('--native-after',type=Path);parser.add_argument('--output',type=Path,required=True)
args=parser.parse_args(argv)
if args.native_before and not args.native_after:parser.error('--native-after is required')
root=args.output.resolve()
if root.exists():parser.error('output must be a new directory')
root.mkdir(parents=True)
store=TaskStore(root/'tasks.db');service=VerificationService(store,root/'data')
original=netlist_verification._export_saved_capture
try:
if args.fixture_root:
fixture=args.fixture_root.resolve();before=next((fixture/'before').rglob('*.prj'));after=next((fixture/'after').rglob('*.prj'))
def controlled(capture,output,*,stop_event):
phase='before' if capture['project']==str(before.resolve()) else 'after'
source=fixture/phase;output.mkdir(parents=True,exist_ok=True)
for name in ('effective.txt','design.kyn'):shutil.copyfile(source/name,output/name)
graph=native_netlist.read_graph(output/'effective.txt',output/'design.kyn')
return {'status':'success','complete':True,'graph':graph,'capture':capture,
'outputs':{'effective':str(output/'effective.txt'),'keyin':str(output/'design.kyn')},
'runs':[],'evidence_kind':'controlled-format-fixture'}
netlist_verification._export_saved_capture=controlled
evidence_kind='controlled-format-fixture'
else:before,after=args.native_before.resolve(),args.native_after.resolve();evidence_kind='native-read-only'
# Capture verifies source stability. Record live bytes to prove no mutation as well.
from dx_productivity.trial_task_center.native_inventory import _project_options
paths=[before,after,Path(_project_options(before)[3]),Path(_project_options(after)[3])]
initial={str(p):native_netlist._hash(p) for p in paths}
task=service.create_task('独立校验验收',request_id='acceptance-create')['task_id']
accepted=service.import_pair(task,before,after,request_id='acceptance-import',stop_event=Event())
if not accepted['accepted']:raise ValueError('No input accepted')
run=service.start(task,request_id='acceptance-run')
deadline=time.monotonic()+900
while service.busy:
if time.monotonic()>deadline:raise TimeoutError('Native acceptance timed out')
time.sleep(.05)
current=service.read_task(task);report=service.export_task(task,root/'reports',request_id='acceptance-report')
unchanged=all(native_netlist._hash(Path(p))==sha for p,sha in initial.items())
summary={'evidence_kind':evidence_kind,'task_id':task,'run':run,'summary':current['summary'],
'input_sha256':initial,'inputs_unchanged':unchanged,'report':str(report),
'policy':'verification-v1','replacement_operations':store._connection.execute('SELECT COUNT(*) FROM execution_operations').fetchone()[0]}
write_record(root/'acceptance.json',summary);print(json.dumps(summary,ensure_ascii=False))
if not unchanged:return 4
if current['summary']['different']:return 2
if current['summary']['unavailable'] or current['summary']['waiting'] or current['summary']['running']:return 3
return 0
except Exception as error:
write_record(root/'failure.json',{'error':type(error).__name__,'reason':str(error)})
print(str(error),file=sys.stderr);return 1
finally:
service.begin_shutdown()
deadline=time.monotonic()+10
while service.busy and time.monotonic()<deadline:time.sleep(.05)
netlist_verification._export_saved_capture=original
if not service.busy:store.close()
if __name__=='__main__':raise SystemExit(main())