From d08a940afe96eb155cb70933628b0c851d4393d1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=98=BF=E7=99=BD=E5=8F=94?= <11794527+absfan@user.noreply.gitee.com> Date: Tue, 17 Nov 2026 19:35:38 +0800 Subject: [PATCH] fix: verify saved replacements through native netlist exports --- .../2026-11-17-saved-netlist-validation.md | 22 + .../2026-11-17-saved-netlist-validation.md | 68 +++ .../dxdesigner795/QuickPartReplace.vbs | 276 ++++++++---- .../trial_task_center/batch_runtime.py | 55 ++- .../trial_task_center/execution_journal.py | 53 ++- .../trial_task_center/execution_proof.py | 47 +- .../trial_task_center/native_helper.py | 63 ++- .../trial_task_center/native_netlist.py | 2 + .../trial_task_center/netlist_verification.py | 26 +- .../trial_task_center/quick_run.py | 134 +++++- .../saved_netlist_verification.py | 273 ++++++++++++ .../trial_task_center/value_readback.py | 28 ++ tests/v1_1/test_native_cli_netlist.py | 14 + tests/v1_1/test_native_selected_capture.py | 74 ++-- .../test_project_commit_runtime_checkpoint.py | 60 +++ tests/v1_1/test_refdes_identity_closure.py | 29 +- .../test_resource_isolation_prewrite_pause.py | 20 +- tests/v1_1/test_saved_netlist_consumers.py | 80 ++++ tests/v1_1/test_saved_netlist_journal.py | 78 ++++ tests/v1_1/test_saved_netlist_verification.py | 405 ++++++++++++++++++ tests/v1_1/test_saved_netlist_writer.py | 266 ++++++++++++ tools/measure_project_session.py | 11 +- 22 files changed, 1907 insertions(+), 177 deletions(-) create mode 100644 docs/superpowers/plans/2026-11-17-saved-netlist-validation.md create mode 100644 docs/testing/2026-11-17-saved-netlist-validation.md create mode 100644 src/dx_productivity/trial_task_center/saved_netlist_verification.py create mode 100644 tests/v1_1/test_saved_netlist_consumers.py create mode 100644 tests/v1_1/test_saved_netlist_journal.py create mode 100644 tests/v1_1/test_saved_netlist_verification.py create mode 100644 tests/v1_1/test_saved_netlist_writer.py diff --git a/docs/superpowers/plans/2026-11-17-saved-netlist-validation.md b/docs/superpowers/plans/2026-11-17-saved-netlist-validation.md new file mode 100644 index 0000000..ecfeab5 --- /dev/null +++ b/docs/superpowers/plans/2026-11-17-saved-netlist-validation.md @@ -0,0 +1,22 @@ +# 保存后原生数据核验实施计划 + +用户已确认:原生数据定位 → DxDesigner 仅负责目标器件替换、属性写入和保存 → 从已保存数据库导出数据核验。此轮修正上一轮没有移除的 CAD 全页核验,不增加第二套全页保护。 + +## 约束与接口 + +- 正常执行不调用 QPCurrentSemanticState、QPVerifyUntouched、QPNativeCapture/QPNativeRead,不为核验关闭重开 CAD。工程末保存关闭一次;下一工程复用 CAD 会话。 +- 写入所需的目标器件定位、原实例属性快照、属性恢复与引脚编号提升仍属于写入操作,限于目标器件;不读取非目标属性/样式/连接。禁止把全页检查改名后继续运行。 +- 新目标快照使用 `X\tsaved_netlist_v1` 标记;保留原 M/C/A 格式及旧操作编号。C.connections 使用 `NETLIST` 表示连接由保存后原生导出核验,不查询 CAD 连接。旧快照/旧恢复证据按原协议处理,不删除历史保护。 +- 新 CAD 工程收尾清单第一行第三列为 `project_saved`;只证明写入/保存/关闭已返回,不能当成 `project_verified`。各项保持 pending_save,原生导出核验通过后才提交 saved_ok/verified。 +- 原生 helper 新快照成功阶段为 `native_replace_applied`,保留事务/库件/尝试身份;旧快照仍保留 native_replace_verified。新正常路径不做全页前后 COM 验证。 +- Python 在确认工程关闭后,复用 native_netlist.capture_project/export_netlist 与原生证据校验,按工程/页/位号对齐全部暂存目标;核验料号、Value/NC、Cell 和可导出的库件属性。证据不完整、目标缺失、属性错误均不得提前完成,不回退 CAD。 +- 独立前后网表比较继续单独展示;尽量复用同一份保存后导出,不再次驱动 CAD。原生格式不覆盖文字位置/字体/颜色,明确覆盖范围,不伪造图形证明。 +- 新回执/重启/暂停/恢复不再要求 full_sheet_v1 或 CAD value-readback TSV;使用有保存源与原尝试绑定的原生导出证据。旧回执验证保留兼容。 +- 不改原工程、中心库、Excel;真实验证仅新副本。保留用户和其他聊天文档。当前功能分支继续,本轮基点 d9cf6a0。 + +## 实施与验证 + +1. VBS/native_helper:先写真实函数测试,令任何正常路径全页扫描调用都失败;实现仅目标写入、工程保存关闭及 project_saved 协议。测试两项目标、合法多单元、暂停前缀、旧恢复兼容。 +2. Python 原生核验/回执:先写缺失/错误目标、原生导出失败、无 CAD 的正例;接入工程提交回调和持久证据。不得以省略 baseline 的方式给旧回执放行。 +3. 集成:同步运行时关闭检查点、journal、恢复与独立网表导出复用。先 RED 后 GREEN;真实副本两项替换比较扫描次数与计时,确认全页 CAD 采集为零、无保存后重开。 +4. 针对改动回归、独立审查、记录真实限制并提交本地变更。此次先改执行链;上一轮候选程序保留,不将旧包冒充本轮源码。 diff --git a/docs/testing/2026-11-17-saved-netlist-validation.md b/docs/testing/2026-11-17-saved-netlist-validation.md new file mode 100644 index 0000000..310d2c4 --- /dev/null +++ b/docs/testing/2026-11-17-saved-netlist-validation.md @@ -0,0 +1,68 @@ +# 保存后原生数据核验 + +本轮修正正常执行链仍然依赖全页 CAD/COM 核验的问题。DxDesigner 负责目标器件替换、属性恢复、保存和关闭;保存后的目标数据与连接核验由 Mentor 原生命令行导出承担。 + +```mermaid +flowchart TD + A[原生数据发现目标:工程、页、位号] --> B[打开工程与目标页] + B --> C[仅记录目标器件原属性] + C --> D[替换目标器件,记录库件 Value 写入期望] + D --> E[恢复属性与 NC,暂存 pending_save] + E --> F{还有同工程目标?} + F -- 有 --> C + F -- 无或暂停 --> G[保存并关闭一次,发布 project_saved] + G --> H[捕获保存数据库,原生命令行导出] + H --> I{按工程、页、位号核验目标数据} + I -- 通过 --> J[原子提交本工程回执,追加完成状态] + I -- 不通过或导出失败 --> K[保留已保存待核验状态,不重放替换] + K --> H + J --> L[独立前后网表比对复用同一份保存后导出] +``` + +## 开发项 + +- [x] 正常路径不调用全页语义状态、非目标属性、连接索引与原生 CAD 宿主快照。 +- [x] 新快照 `saved_netlist_v1` 仅含目标 C/A;旧快照继续使用原兼容路径。 +- [x] helper 使用 `native_replace_applied`,不将写入完成冒充核验通过。 +- [x] 写入前固定选定库件、Value/NC 与 Cell 期望,保留原 preserve 语义。 +- [x] 工程末保存关闭一次;不为核验重开 CAD。 +- [x] 原生导出按工程、页、位号匹配目标,UID 作为尝试关联证据。 +- [x] `project_saved` 仅授权后续原生验证,SQL 完成提交必须具备已验证导出。 +- [x] 暂停、重启与恢复沿用原尝试,已保存操作不重放。 +- [x] 回执只记录本项观察与共享导出引用,完整工程证明只存一份。 +- [x] 独立网表比对复用保存后导出。 +- [x] 完成状态以追加方式发布,保持活动批次的增量读取位置。 +- [x] 单步执行和非复用模式也按本次调用保存、原生核验、提交完成。 +- [x] 多批保存恢复只对最新保存状态比较当前源;历史已完成批次核对其固化证据。 +- [x] 修正真实工程端口名 `LED2/RXDLY` 被误识别为层级路径的问题。 +- [x] 审查发现的可变缓存图与 mixed no-match 提交问题均有失败复现和修复测试。 + +## 验收记录 + +真实验证只使用备份的新副本,原备份 34 个文件哈希保持不变。样本选择单页 RL02/RL05,料号从 `4100-CA3300-T7` 替换为 `4100-CA3300-2200`。 + +第一次副本完成替换、一次保存与关闭,但原生解析因带 `/` 的端口名误判而拒绝提交。修复解析后,新 Python 进程在 6.03 秒内完成导出与原子提交,两项仍为 generation 1,没有调用 CAD 或重放替换。以原备份独立导出作前基准,与已验证保存后导出比较,结果 verified、差异为空;后导出直接复用。 + +第二次副本暴露完成状态发布重建文件、破坏增量读取位置的问题。追加式发布修复后,第三次全新副本完整执行通过:任务表状态 completed,两项操作 verified 且 generation 仍为 1,CAD 进程正常退出。 + +| 指标 | 上一轮 | 本轮第三份副本 | +| --- | ---: | ---: | +| 两项任务总耗时 | 1450.341 秒 | 226.461 秒 | +| 工程打开 | — | 1 次 | +| 工程保存 | 1 次 | 1 次 | +| 全页原生 CAD 快照 | 4 次 | 0 次 | +| 保存后为核验重开 CAD | 存在 | 0 次 | + +本轮无 `post-state-*.tsv`,两个目标快照均无 U/G 记录。独立原生器件清单读取耗时 1.312 秒,13 个器件料号全部符合预期;对第三份副本的完整原生前后网表比较同样 verified、差异为空,直接复用保存后导出。原备份 34 文件哈希不变。耗时降低约 84.4%,剩余耗时主要在 CAD 启动、目标定位、替换交互和属性写入。 + +本次只完成两项目标的实机功能与性能探针,不能代替此前要求的 20 个业务样本验收。 + +第四份新副本验证非复用分支:253.389 秒,两次打开/保存,两个工程提交均 verified,任务 completed,全页 CAD 原生采集仍为 0。两个公开执行事件的 Value 回执均为 verified。随后在该副本模拟“SQL 已提交但状态发布未完成”的保护记录,复现历史源指纹错误阻塞;修复后,新 Python 进程在 0.452 秒内完成恢复,尝试编号、generation、操作状态和历史条目数量均未改变,审计记录 `native_replacement_called=false`。CAD 进程已正常退出。 + +全量回归先得到 2412 通过、1 失败;失败来自抽取 VBS 函数的测试夹具漏声明全局新模式变量。修正夹具后该文件 37 项通过;最后一轮涉及执行、恢复、状态、网表与身份关联的回归 430 项通过。后续多批恢复专项 51 项通过,包含三个恢复时机与五个失败证据场景。将全量与增量报告按测试名称合并、以后续复验覆盖原失败结果,**2426 个不同用例均已验证通过**;这不是一次完整重跑的数量,也不将重复执行算作额外业务样本。 + +证据位于 `D:/CodexValidation/saved-netlist-20261117/`,自动化报告位于 `build/saved-netlist-validation/`。 + +## 覆盖限制 + +原生 ASCII 导出不证明 Value 属性的空值/缺失差异,也不覆盖 CAD 显示位置、字体和颜色;回执保留此限制,不伪造这些图形核验结果。本轮不更新旧候选安装包。 diff --git a/integration/dxdesigner795/QuickPartReplace.vbs b/integration/dxdesigner795/QuickPartReplace.vbs index 25b7e2a..728a5fb 100644 --- a/integration/dxdesigner795/QuickPartReplace.vbs +++ b/integration/dxdesigner795/QuickPartReplace.vbs @@ -29,6 +29,7 @@ Dim QP_ComponentUidIndex, QP_ComponentRefdesIndex, QP_ComponentLocationIndex Dim QP_FallbackIdentityUsed Dim QP_FallbackIdentityWarnings Dim QP_ReferenceAliases +Dim QP_SavedNetlistMode Dim QP_ComponentIndexContext Dim QP_NativeCallActive Dim QP_BatchMode, QP_OwnedProject, QP_BatchState, QP_BatchCode, QP_BatchMessage @@ -162,7 +163,7 @@ WScript.Quit QP_ExitCode Sub QPMain() Dim Command Dim SnapshotPath - Dim State + Dim State, ExistingRecords If Not QP_Fso.FolderExists(QP_Root) Then Err.Raise vbObjectError + 795, "QuickPartReplace", _ @@ -171,9 +172,11 @@ Sub QPMain() Set Command = QPReadCommand(QP_Fso.BuildPath(QP_Root, "command.tsv")) QP_CurrentJobId = CStr(Command("job_id")) QPRequireProject Command - If QP_BatchMode And QP_SessionItems.Count = 0 And Not QP_Fso.FileExists(QP_Fso.BuildPath(QP_Root, "recovery.request")) Then _ - QPVerifyExpectedBaselines CStr(Command("project_path")) SnapshotPath = QPJobSnapshotPath(CStr(Command("job_id"))) + QP_SavedNetlistMode = True + If QP_Fso.FileExists(SnapshotPath) Then Set ExistingRecords = QPReadSnapshot(SnapshotPath) + If Not QP_SavedNetlistMode And QP_BatchMode And QP_SessionItems.Count = 0 And Not QP_Fso.FileExists(QP_Fso.BuildPath(QP_Root, "recovery.request")) Then _ + QPVerifyExpectedBaselines CStr(Command("project_path")) State = QPReadState(QP_Fso.BuildPath(QP_Root, "status.tsv"), _ CStr(Command("job_id"))) @@ -438,7 +441,7 @@ Sub QPRequireSessionCheckpoint() Err.Raise vbObjectError + 873, "QuickPartReplace.ProjectSession", "owned sheet set changed at checkpoint" If CStr(View.GetName(0)) <> QP_CheckpointSchematic Or CStr(View.Block.SheetNum) <> QP_CheckpointSheet Then _ Err.Raise vbObjectError + 873, "QuickPartReplace.ProjectSession", "active sheet changed at checkpoint" - If QP_SessionSheets.Exists(QPSheetKey(QP_CheckpointSchematic, QP_CheckpointSheet)) Then _ + If Not QP_SavedNetlistMode And QP_SessionSheets.Exists(QPSheetKey(QP_CheckpointSchematic, QP_CheckpointSheet)) Then _ QPRequireExpectedState QP_SessionSheets.Item(QPSheetKey(QP_CheckpointSchematic, QP_CheckpointSheet)), QPCurrentSemanticState() End Sub @@ -1156,6 +1159,7 @@ Sub QPVerifyFailedOriginalSnapshot() Set Command = QPReadCommand(QP_Fso.BuildPath(QP_Root, "command.tsv")) QPRequireCommandSnapshot Command, SnapshotPath Set Records = QPReadSnapshot(SnapshotPath) + If QP_SavedNetlistMode Then Exit Sub QPInvalidatePinIndex QPInvalidateComponentIndex For Index = 0 To Records.Item("components").Count - 1 @@ -1182,6 +1186,14 @@ Sub QPFinishBatchItem() Set Command = QPReadCommand(QP_Fso.BuildPath(QP_Root, "command.tsv")) QP_BatchState = FinalState TargetPath = CStr(Command("project_path")) + If QP_SavedNetlistMode Then + If FinalState = "restored_ok" Then QPMarkBatchMutation Command + QPCloseBatchProject TargetPath, (FinalState = "restored_ok") + QP_BatchMode = False + If FinalState = "restored_ok" Then FinalState = "pending_save" + QPWriteStatus QP_Root, QP_CurrentJobId, FinalState, "project_saved", "Engineering project saved and closed; awaiting saved native data verification." + Exit Sub + End If If FinalState = "restored_ok" Then SnapshotPath = QPJobSnapshotPath(QP_CurrentJobId) QPRequireCommandSnapshot Command, SnapshotPath @@ -1273,20 +1285,23 @@ Sub QPStageSessionItem() If FinalState = "restored_ok" Then Set Records = QPReadSnapshot(QPJobSnapshotPath(QP_CurrentJobId)) QPRequireCommandSnapshot Command, QPJobSnapshotPath(QP_CurrentJobId) - QPVerifyUntouched Records - Set ValueStates = CreateObject("Scripting.Dictionary") - For Index = 0 To Records.Item("components").Count - 1 - Set Record = Records.Item("components").Item(CStr(Index)) - Set Candidate = QPFindUniqueByOldLocation(Record) - ValueStates.Add CStr(Index), QPCaptureValueState(Candidate) - QPSetRequiredNc ValueStates.Item(CStr(Index)), Record, Records.Item("attributes"), QPSyncNc(Command) - ValueStates.Item(CStr(Index)).Add "custom_value", QPCustomValue(Command) - Next + If Not QP_SavedNetlistMode Then + QPVerifyUntouched Records + Set ValueStates = CreateObject("Scripting.Dictionary") + For Index = 0 To Records.Item("components").Count - 1 + Set Record = Records.Item("components").Item(CStr(Index)) + Set Candidate = QPFindUniqueByOldLocation(Record) + ValueStates.Add CStr(Index), QPCaptureValueState(Candidate) + QPSetRequiredNc ValueStates.Item(CStr(Index)), Record, Records.Item("attributes"), QPSyncNc(Command) + ValueStates.Item(CStr(Index)).Add "custom_value", QPCustomValue(Command) + Next + Item.Add "value_states", ValueStates + End If Item.Add "snapshot_path", QPJobSnapshotPath(QP_CurrentJobId) - Item.Add "value_states", ValueStates End If + Item.Add "saved_netlist", CBool(QP_SavedNetlistMode) QP_SessionItems.Add QP_CurrentJobId, Item - QP_SessionSheets.Item(QPSheetKey(Item("schematic"), Item("sheet"))) = QPCurrentSemanticState() + If Not QP_SavedNetlistMode Then QP_SessionSheets.Item(QPSheetKey(Item("schematic"), Item("sheet"))) = QPCurrentSemanticState() QP_BatchMode = False QP_NativeMutationPossible = False QP_SessionExternalChange = False @@ -1295,7 +1310,7 @@ Sub QPStageSessionItem() QP_SessionWaiting = True Code = "session_staged" If FinalState = "no_match" Then Code = "session_staged_no_match" - QPWriteStatus QP_Root, QP_CurrentJobId, "pending_save", Code, "Verified in memory; awaiting engineering project save and readback." + QPWriteStatus QP_Root, QP_CurrentJobId, "pending_save", Code, "Writes staged; awaiting engineering project save and saved native data verification." QPWriteUtf8 QP_Fso.BuildPath(QP_Root, "project-session-result.tsv"), _ QP_SessionToken & vbTab & QP_CurrentJobId & vbTab & "pending_save" & vbTab & Code End Sub @@ -1314,6 +1329,13 @@ Sub QPCommitSessionProject() QP_SessionCommitActive = True QP_FailureCleanupActive = True QP_BatchMode = True + If QP_SavedNetlistMode Then + QPCommitSavedNetlistProject + QP_SessionCommitActive = False + QP_FailureCleanupActive = False + QP_BatchMode = False + Exit Sub + End If HasChanges = False Set VerifiedSheets = CreateObject("Scripting.Dictionary") ' Capture the final memory state once per sheet, including later replacements. @@ -1384,6 +1406,32 @@ Sub QPCommitSessionProject() QP_BatchMode = False End Sub +Sub QPCommitSavedNetlistProject() + Dim Job, Item, Manifest, HasChanges, FinalState + HasChanges = False + For Each Job In QP_SessionItems.Keys + Set Item = QP_SessionItems.Item(Job) + If Not Item("saved_netlist") Then Err.Raise vbObjectError + 871, "QuickPartReplace.Batch", "mixed project validation protocols" + If Item("final_state") = "restored_ok" Then HasChanges = True + Next + QPCloseBatchProject QP_SessionProject, HasChanges + QP_SessionDocuments.RemoveAll + Manifest = QP_SessionToken & vbTab & QPEncode(QP_SessionProject) & vbTab & "project_saved" & vbCrLf + For Each Job In QP_SessionItems.Keys + Set Item = QP_SessionItems.Item(Job) + FinalState = "no_match" + If Item("final_state") = "restored_ok" Then FinalState = "pending_save" + Manifest = Manifest & CStr(Job) & vbTab & FinalState & vbCrLf + Next + QPWriteUtf8 QP_Fso.BuildPath(QP_Root, "project-commit-" & QP_SessionToken & ".tsv"), Manifest + For Each Job In QP_SessionItems.Keys + Set Item = QP_SessionItems.Item(Job) + FinalState = "no_match" + If Item("final_state") = "restored_ok" Then FinalState = "pending_save" + QPWriteStatus QP_Root, CStr(Job), FinalState, "project_saved", "Engineering project saved and closed; awaiting saved native data verification." + Next +End Sub + Function QPCurrentSemanticState() Dim Components, Comp, State, Count QPInvalidatePinIndex @@ -1466,6 +1514,7 @@ Function QPComparableState(ByVal Text) End Function Sub QPWriteVerifiedState(ByRef Command) + If QP_SavedNetlistMode Then Exit Sub QPWriteSemanticState Command, QPCurrentSemanticState() End Sub @@ -1572,7 +1621,7 @@ Sub QPAutomaticReplaceAndRestore(ByRef Command, ByVal SnapshotPath) Err.Clear On Error GoTo 0 If ErrorNumber <> 0 Then - If QP_NativeMutationPossible And Not QP_BatchMode Then + If QP_NativeMutationPossible And Not QP_BatchMode And Not QP_SavedNetlistMode Then On Error Resume Next QPRollbackNativeReplacement SnapshotPath If Err.Number <> 0 Then @@ -1585,6 +1634,8 @@ Sub QPAutomaticReplaceAndRestore(ByRef Command, ByVal SnapshotPath) ErrorDescription = "Replacement validation failed; native rollback was verified and the original sheet state was restored. No replacement remains. Original failure: " & ErrorDescription End If On Error GoTo 0 + ElseIf QP_NativeMutationPossible And QP_SavedNetlistMode Then + ErrorDescription = "Replacement writes may have been applied; persisted outcome requires saved native data verification. " & ErrorDescription ElseIf QP_NativeMutationPossible And QP_BatchMode Then ErrorDescription = "Replacement validation failed; batch mode kept the native result unsaved and closed the failed project. " & ErrorDescription End If @@ -1699,8 +1750,9 @@ Sub QPCaptureAndSelect(ByRef Command, ByVal SnapshotPath) Dim PartNumber Dim Snapshot Dim Index - Dim Selectors, Selector, SelectorUid, FoundSelectors, Uid, ValueAttr, ValueText, MatchedUids, UntouchedCount, NativeRead, AlreadyTargets + Dim Selectors, Selector, SelectorUid, FoundSelectors, Uid, ValueAttr, ValueText, AlreadyTargets + QP_SavedNetlistMode = True QP_FallbackIdentityUsed = False Set QP_FallbackIdentityWarnings = CreateObject("Scripting.Dictionary") If StrComp(CStr(Command("old_part_number")), CStr(Command("new_part_number")), vbTextCompare) = 0 Then _ @@ -1782,49 +1834,15 @@ Sub QPCaptureAndSelect(ByRef Command, ByVal SnapshotPath) Snapshot = Snapshot & vbCrLf If Len(QPTargetCell(Command)) > 0 Then _ Snapshot = Snapshot & "L" & vbTab & QPEncode(QPTargetCell(Command)) & vbCrLf - Set MatchedUids = CreateObject("Scripting.Dictionary") For Index = 0 To Matches.Count - 1 Set Comp = Matches.Item(CStr(Index)) QPRequireUniqueAttributeNames Comp - MatchedUids.Add QPComponentIdentityKey(Comp), True - Next - Set NativeRead = Nothing - If QPUseNativeSnapshot() And Not QP_FallbackIdentityUsed Then - QPRequireProject Command - Set NativeRead = QPNativeCapture(MatchedUids) - If Not NativeRead Is Nothing Then - If NativeRead("total") <> Components.Count Then _ - Err.Raise vbObjectError + 875, "QuickPartReplace.NativeRead", "component count changed during capture" - End If - End If - For Index = 0 To Matches.Count - 1 - Set Comp = Matches.Item(CStr(Index)) Uid = QPComponentIdentityKey(Comp) QPLog QP_Root, "INFO", "stage=snapshot_component uid=" & QPLogField(Uid) - If NativeRead Is Nothing Then - Snapshot = Snapshot & QPSnapshotComponent(Comp) - Else - QPRequireNativeCapturedTarget CStr(NativeRead("selected")(Uid)), Command, Uid, Selectors - Snapshot = Snapshot & CStr(NativeRead("selected")(Uid)) - End If + Snapshot = Snapshot & QPSnapshotComponent(Comp) QPProgress "capture", Index + 1, Matches.Count Next - ' U remains the seven-field native-helper identity baseline. X/G extend it - ' with complete unselected state for every scope, including all-match jobs. - Snapshot = Snapshot & "X" & vbTab & "untouched_full_v1" & vbCrLf - UntouchedCount = 0 - If NativeRead Is Nothing Then - For Each Comp In Components - If Not MatchedUids.Exists(QPComponentIdentityKey(Comp)) Then - QPProgress "capture_untouched", UntouchedCount, Components.Count - Matches.Count - Snapshot = Snapshot & QPUntouchedComponent(Comp) - UntouchedCount = UntouchedCount + 1 - QPProgress "capture_untouched", UntouchedCount, Components.Count - Matches.Count - End If - Next - Else - Snapshot = Snapshot & CStr(NativeRead("text")) - End If + Snapshot = Snapshot & "X" & vbTab & "saved_netlist_v1" & vbCrLf QPWriteUtf8 SnapshotPath, Snapshot For Each Comp In Components @@ -2110,8 +2128,12 @@ Function QPSnapshotComponent(ByRef Comp) Identity = QPComponentIdentityKey(Comp) Set Point = Comp.GetLocation() - Set Pins = QPComponentPins(Identity) - Connections = QPConnectionSignatureFromPins(Identity, Pins) + If QP_SavedNetlistMode Then + Connections = "NETLIST" + Else + Set Pins = QPComponentPins(Identity) + Connections = QPConnectionSignatureFromPins(Identity, Pins) + End If Result = "C" & vbTab & QPEncode(Identity) & vbTab & _ QPEncode(CStr(Comp.Refdes)) & vbTab & QPEncode(CStr(Point.X)) & _ vbTab & QPEncode(CStr(Point.Y)) & vbTab & _ @@ -2278,10 +2300,9 @@ Sub QPRestoreAfterOperatorReplace(ByRef Command, ByVal SnapshotPath) QPProgress "restore_preflight", 0, 0 Set Records = QPReadSnapshot(SnapshotPath) QPRequireCommandSnapshot Command, SnapshotPath - ' Owned batches perform full-page checks immediately before saving and - ' after disk reopen in QPFinishBatchItem, before publishing completion. - ' Manual restoration keeps full checks on both sides of its writes. - If Not QP_BatchMode Then QPVerifyUntouched Records + ' Saved-native jobs validate persisted results after the engineering close. + ' Legacy manual snapshots keep the original checks around restoration. + If Not QP_BatchMode And Not QP_SavedNetlistMode Then QPVerifyUntouched Records Set Meta = Records.Item("meta") If QPCanonicalPath(CStr(Meta("project_path"))) <> QPCanonicalPath(QPProjectPath()) Or _ CStr(Meta("sheet_name")) <> QPSheetIdentity() Then _ @@ -2359,9 +2380,14 @@ Sub QPRestoreAfterOperatorReplace(ByRef Command, ByVal SnapshotPath) " Target Cell verified: " & QPTargetCell(Command) & "." If Len(QP_NcSyncSummary) > 0 Then SuccessMessage = SuccessMessage & _ " NC synced: " & QP_NcSyncSummary - If Not QP_BatchMode Then QPWriteValueReadback Command, Records, Plans, "restored_ok" + If QP_SavedNetlistMode Then SuccessMessage = "Replacement and attribute writes applied; awaiting saved native data verification. Replacements: " & ReplacementSummary + If Not QP_BatchMode And Not QP_SavedNetlistMode Then QPWriteValueReadback Command, Records, Plans, "restored_ok" QPWriteStatus QP_Root, CStr(Command("job_id")), "restored_ok", "", SuccessMessage - QPLog QP_Root, "INFO", "verified replacement count=" & Plans.Count & " value_mode=" & QPValueMode(Command) + If QP_SavedNetlistMode Then + QPLog QP_Root, "INFO", "applied replacement count=" & Plans.Count & " value_mode=" & QPValueMode(Command) + Else + QPLog QP_Root, "INFO", "verified replacement count=" & Plans.Count & " value_mode=" & QPValueMode(Command) + End If End Sub Function QPReplacementSummary(ByRef Records, ByRef Plans, ByVal OldPartNumber, ByVal NewPartNumber) @@ -2389,13 +2415,18 @@ Sub QPRestorePlans(ByRef Command, ByRef Records, ByRef Plans) ValueStates.Add CStr(Index), QPCaptureValueState(Candidate) QPSetRequiredNc ValueStates.Item(CStr(Index)), ComponentRecord, Records.Item("attributes"), QPSyncNc(Command) ValueStates.Item(CStr(Index)).Add "custom_value", QPCustomValue(Command) + Next + If QP_SavedNetlistMode Then QPWriteWriterExpectations Command, Records, ValueStates + For Index = 0 To Plans.Count - 1 + Set ComponentRecord = Records.Item("components").Item(CStr(Index)) + Set Candidate = Plans.Item(CStr(Index)) QPRestoreComponent Candidate, ComponentRecord, Records.Item("attributes"), _ QPValueMode(Command), QPCustomValue(Command), QPSyncNc(Command) QPSetTargetCell Candidate, Command QPProgress "restore_attributes", Index + 1, Plans.Count Next - QPVerifyRestoredPlans Command, Records, Plans, ValueStates - If Not QP_BatchMode Then QPVerifyUntouched Records + If Not QP_SavedNetlistMode Then QPVerifyRestoredPlans Command, Records, Plans, ValueStates + If Not QP_BatchMode And Not QP_SavedNetlistMode Then QPVerifyUntouched Records End Sub Sub QPVerifyRestoredPlans(ByRef Command, ByRef Records, ByRef Plans, ByRef ValueStates) @@ -2441,6 +2472,7 @@ Sub QPRecoverSavedJob(ByRef Command, ByVal SnapshotPath) Dim Records, Plans, Used, ValueStates, Index, Record, Candidate, PartNumber Dim OldCount, NewCount, ErrorNumber, ErrorDescription, RecoveryDocuments, RecoveryDocument, RecoveryProjectData, SourceOnly QPRequireCommandSnapshot Command, SnapshotPath + If QP_SavedNetlistMode Then Err.Raise vbObjectError + 865, "QuickPartReplace.Recovery", "saved native snapshot requires saved database verification; no CAD replay allowed" SourceOnly = False If Command.Exists("recovery_source_only") Then If CStr(Command("recovery_source_only")) <> "1" Then _ @@ -2602,15 +2634,17 @@ Sub QPRestorePreflight(ByRef Comp, ByRef ComponentRecord, _ Err.Raise vbObjectError + 800, "QuickPartReplace", _ "replacement Part Number does not equal command target" End If - CurrentConnections = QPConnectionSignature(Comp) SavedConnections = CStr(ComponentRecord("connections")) - If Not QPConnectionsMatch(CurrentConnections, SavedConnections) Then - QPLog QP_Root, "ERROR", "connection_mismatch uid=" & _ - CStr(ComponentRecord("uid")) & " saved=" & _ - QPLogField(SavedConnections) & " current=" & _ - QPLogField(CurrentConnections) - Err.Raise vbObjectError + 804, "QuickPartReplace", _ - "connection validation failed" + If Not QP_SavedNetlistMode Then + CurrentConnections = QPConnectionSignature(Comp) + If Not QPConnectionsMatch(CurrentConnections, SavedConnections) Then + QPLog QP_Root, "ERROR", "connection_mismatch uid=" & _ + CStr(ComponentRecord("uid")) & " saved=" & _ + QPLogField(SavedConnections) & " current=" & _ + QPLogField(CurrentConnections) + Err.Raise vbObjectError + 804, "QuickPartReplace", _ + "connection validation failed" + End If End If For Index = 0 To Attributes.Count - 1 Set Record = Attributes.Item(CStr(Index)) @@ -2763,9 +2797,11 @@ Sub QPRestoreComponent(ByRef Comp, ByRef ComponentRecord, ByRef Attributes, _ Comp.Scale = CDbl(ComponentRecord("scale")) Comp.SetLocation CLng(ComponentRecord("x")), CLng(ComponentRecord("y")) Comp.Refdes = CStr(ComponentRecord("refdes")) - If StrComp(CStr(Comp.Refdes), CStr(ComponentRecord("refdes")), _ - vbBinaryCompare) <> 0 Then - Err.Raise vbObjectError + 803, "QuickPartReplace", "Refdes restore failed" + If Not QP_SavedNetlistMode Then + If StrComp(CStr(Comp.Refdes), CStr(ComponentRecord("refdes")), _ + vbBinaryCompare) <> 0 Then + Err.Raise vbObjectError + 803, "QuickPartReplace", "Refdes restore failed" + End If End If LabelValue = "" HasOldNc = False @@ -2786,8 +2822,10 @@ Sub QPRestoreComponent(ByRef Comp, ByRef ComponentRecord, ByRef Attributes, _ Else Attr.InstanceValue = CStr(Record("value")) End If - If QPEffectiveAttributeValue(Attr) <> QPSavedEffectiveValue(Record) Then _ - Err.Raise vbObjectError + 834, "QuickPartReplace", "instance attribute readback failed" + If Not QP_SavedNetlistMode Then + If QPEffectiveAttributeValue(Attr) <> QPSavedEffectiveValue(Record) Then _ + Err.Raise vbObjectError + 834, "QuickPartReplace", "instance attribute readback failed" + End If End If If Attr Is Nothing Then If Not QPNativeAttributeAbsenceAllowed(CStr(Record("name")), ValueMode) Then _ @@ -2879,13 +2917,14 @@ Sub QPRestoreComponent(ByRef Comp, ByRef ComponentRecord, ByRef Attributes, _ Err.Raise ErrorNumber, ErrorSource, ErrorDescription End If End If - If StrComp(QPEffectiveAttributeValue(ValueAttr), LabelValue, _ - vbBinaryCompare) <> 0 Then - Err.Raise vbObjectError + 818, "QuickPartReplace", _ - "Value readback does not equal the selected source" + If Not QP_SavedNetlistMode Then + If StrComp(QPEffectiveAttributeValue(ValueAttr), LabelValue, _ + vbBinaryCompare) <> 0 Then + Err.Raise vbObjectError + 818, "QuickPartReplace", _ + "Value readback does not equal the selected source" + End If End If - If HasOldNc Then QPRecordNcSync Comp, QPSavedEffectiveValue(ValueRecord), _ - QPEffectiveAttributeValue(ValueAttr) + If HasOldNc Then QPRecordNcSync Comp, QPSavedEffectiveValue(ValueRecord), LabelValue End Sub Function QPComponentIdentity(ByRef Comp) @@ -3003,7 +3042,7 @@ Sub QPSetTargetCell(ByRef Comp, ByRef Command) If Attr Is Nothing Then Err.Raise vbObjectError + 878, _ "QuickPartReplace.Cell", "replaced target has no Cell Name attribute" Attr.InstanceValue = Value - QPVerifyTargetCell Comp, Command + If Not QP_SavedNetlistMode Then QPVerifyTargetCell Comp, Command End Sub Sub QPVerifyTargetCell(ByRef Comp, ByRef Command) @@ -3063,6 +3102,40 @@ Function QPCaptureValueState(ByRef Comp) Set QPCaptureValueState = State End Function +Sub QPWriteWriterExpectations(ByRef Command, ByRef Records, ByRef ValueStates) + Dim Text, Index, Record, Before, ExpectedValue, ExpectedExists, Mode + Text = "W" & vbTab & "1" & vbTab & QPEncode(CStr(Command("task_id"))) & vbTab & _ + QPEncode(CStr(Command("job_id"))) & vbTab & QPEncode(CStr(Command("project_path"))) & vbTab & _ + QPEncode(CStr(QP_App.ActiveView.GetName(0))) & vbTab & QPEncode(CStr(QP_App.ActiveView.Block.SheetNum)) & vbTab & _ + QPEncode(QPReadUtf8(QPJobSnapshotPath(Command("job_id")))) & vbCrLf + Mode = QPValueMode(Command) + For Index = 0 To Records.Item("components").Count - 1 + Set Record = Records.Item("components").Item(CStr(Index)) + Set Before = ValueStates.Item(CStr(Index)) + ExpectedExists = True + Select Case Mode + Case "preserve" + ExpectedValue = Before("value") + ExpectedExists = Before("exists") + Case "custom" + ExpectedValue = QPCustomValue(Command) + Case "part_number" + ExpectedValue = CStr(Command("new_part_number")) + Case Else + ExpectedValue = Before("part_label") + End Select + If Before("nc_required") Then + ExpectedValue = QPAppendNcMarker(ExpectedValue) + ExpectedExists = True + End If + Text = Text & "C" & vbTab & QPEncode(CStr(Record("uid"))) & vbTab & QPEncode(CStr(Record("refdes"))) & vbTab & _ + QPEncode(CStr(ExpectedValue)) & vbTab & QPBooleanText(ExpectedExists) & vbTab & _ + QPEncode(CStr(Before("part_name"))) & vbTab & QPEncode(CStr(Before("part_label"))) & vbTab & _ + QPEncode(CStr(Command("new_part_number"))) & vbTab & QPEncode(QPTargetCell(Command)) & vbCrLf + Next + QPWriteUtf8 QP_Fso.BuildPath(QP_Root, "writer-expectations-" & CStr(Command("job_id")) & ".tsv"), Text +End Sub + Sub QPVerifyValuePolicy(ByRef Comp, ByVal ValueMode, ByRef Before) Dim Current, SourceName, ExpectedValue, ExpectedExists If ValueMode = "preserve" Then @@ -3239,7 +3312,7 @@ Sub QPRestoreDisplay(ByRef Attr, ByRef Record, ByVal Refdes) Attr.Orientation = CLng(Record("orientation")) Attr.Visible = CLng(Record("visible")) Attr.SetLocation CLng(Record("x")), CLng(Record("y")) - QPVerifyDisplay Attr, Record, Refdes + If Not QP_SavedNetlistMode Then QPVerifyDisplay Attr, Record, Refdes End Sub Sub QPVerifyDisplay(ByRef Attr, ByRef Record, ByVal Refdes) @@ -3744,8 +3817,11 @@ Function QPReadSnapshot(ByVal Path) Dim Fields Dim Index Dim Record - Dim Meta + Dim Meta, Protocol, SelectedUids, UnknownRecord + Protocol = "" + UnknownRecord = False + QP_SavedNetlistMode = False Set Result = CreateObject("Scripting.Dictionary") Set Components = CreateObject("Scripting.Dictionary") Set Attributes = CreateObject("Scripting.Dictionary") @@ -3822,20 +3898,42 @@ Function QPReadSnapshot(ByVal Path) QP_ReferenceAliases.Add LCase(Meta("sheet_name") & "|" & Trim(QPDecode(Fields(2)))),QPDecode(Fields(1)) End If Case "X" - If UBound(Fields) <> 1 Or Fields(1) <> "untouched_full_v1" Then _ - Err.Raise vbObjectError + 874, "QuickPartReplace.Target", "invalid unselected-state protocol" - Result.Add "untouched_full_version", CStr(Fields(1)) + If UBound(Fields) <> 1 Then Err.Raise vbObjectError + 874, "QuickPartReplace.Target", "invalid snapshot protocol" + If Len(Protocol) > 0 Or (Fields(1) <> "untouched_full_v1" And Fields(1) <> "saved_netlist_v1") Then _ + Err.Raise vbObjectError + 874, "QuickPartReplace.Target", "invalid snapshot protocol" + Protocol = CStr(Fields(1)) + If Protocol = "untouched_full_v1" Then Result.Add "untouched_full_version", Protocol Case "G" If UBound(Fields) <> 2 Or Len(QPDecode(Fields(1))) = 0 Or Len(QPDecode(Fields(2))) = 0 Then _ Err.Raise vbObjectError + 874, "QuickPartReplace.Target", "invalid unselected full-state snapshot" UntouchedFull.Add QPDecode(Fields(1)), QPDecode(Fields(2)) If Result.Exists("meta") Then QPBindSnapshotFullState Meta("sheet_name"),QPDecode(Fields(2)) + Case Else + UnknownRecord = True End Select End If Next If Not Result.Exists("meta") Or Components.Count = 0 Or Attributes.Count = 0 Then Err.Raise vbObjectError + 815, "QuickPartReplace", "incomplete snapshot" End If + If Protocol = "saved_netlist_v1" Then + If UnknownRecord Or Untouched.Count <> 0 Or UntouchedFull.Count <> 0 Then _ + Err.Raise vbObjectError + 874, "QuickPartReplace.Target", "saved native snapshot contains unselected records" + For Each Index In Components.Keys + If Components.Item(Index)("connections") <> "NETLIST" Then _ + Err.Raise vbObjectError + 874, "QuickPartReplace.Target", "saved native snapshot has CAD connection data" + Next + Set SelectedUids = CreateObject("Scripting.Dictionary") + For Each Index In Components.Keys + SelectedUids.Add Components.Item(Index)("uid"), True + Next + For Each Index In Attributes.Keys + If Not SelectedUids.Exists(Attributes.Item(Index)("uid")) Then _ + Err.Raise vbObjectError + 874, "QuickPartReplace.Target", "saved native snapshot attribute is outside targets" + Next + QP_SavedNetlistMode = True + End If + Result.Add "saved_netlist", QP_SavedNetlistMode Result.Add "components", Components Result.Add "attributes", Attributes Result.Add "untouched", Untouched diff --git a/src/dx_productivity/trial_task_center/batch_runtime.py b/src/dx_productivity/trial_task_center/batch_runtime.py index a50aa2e..de0808c 100644 --- a/src/dx_productivity/trial_task_center/batch_runtime.py +++ b/src/dx_productivity/trial_task_center/batch_runtime.py @@ -430,7 +430,8 @@ class BatchCadRuntime: from .execution_proof import capture_project_commit, bind_project_commit_source from .quick_run import _decode_vbs_field rows = [line.split('\t') for line in marker.read_text(encoding='utf-8-sig').splitlines() if line] - if (not rows or len(rows[0]) != 3 or rows[0][0] != request[0] or rows[0][2] != 'project_verified' + if (not rows or len(rows[0]) != 3 or rows[0][0] != request[0] + or rows[0][2] not in {'project_verified', 'project_saved'} or canonical_path(_decode_vbs_field(rows[0][1])) != project or any(len(row) != 2 for row in rows[1:])): raise WorkerMonitorError('native project commit marker is not bound to the closed project') @@ -439,6 +440,10 @@ class BatchCadRuntime: expected_jobs = expected_jobs[expected_jobs.index(self.record['active_job']):] if not jobs or len(set(jobs)) != len(jobs) or jobs != expected_jobs[:len(jobs)]: raise WorkerMonitorError('native project commit marker does not cover an authorized prefix') + saved_only = rows[0][2] == 'project_saved' + allowed_outcomes = {'pending_save', 'no_match'} if saved_only else {'saved_ok', 'no_match'} + if any(row[1] not in allowed_outcomes for row in rows[1:]): + raise WorkerMonitorError('native project commit marker has an invalid outcome') proof = capture_project_commit(self.root, root, {'session_token': request[0], 'project_path': str(project).casefold(), 'jobs_json': json.dumps(jobs)}) proof = bind_project_commit_source(proof, self.root, root, project) @@ -446,14 +451,49 @@ class BatchCadRuntime: proof['files'].append({'path': str(canonical_path(marker)), 'sha256': proof['marker_sha256']}) readback_names = [] for job, outcome in proof['outcomes'].items(): - readback_names.append('post-state-' + job + '.tsv') - if outcome == 'saved_ok': + if saved_only: + from .batch_attempt import read_attempt + path, expected = next((path, expected) for path, expected in self._current_attempts + if expected['job_id'] == job) + actual = read_attempt(path) + if any(actual.get(name) != value for name, value in expected.items() if name != 'state'): + raise WorkerMonitorError('saved project attempt identity changed') + if outcome == 'no_match' and actual['state'] != 'prepared': + raise WorkerMonitorError('saved project no-match outcome has a possible native write') + snapshot = internal_path(root / ('snapshot-' + job + '.tsv')) + report_path = internal_path(str(snapshot) + '.native.json') + if snapshot.exists(): + if b'X\tsaved_netlist_v1' not in snapshot.read_bytes().splitlines(): + raise WorkerMonitorError('saved project snapshot does not authorize native export validation') + readback_names.append(snapshot.name) + if outcome in {'saved_ok', 'pending_save'} or report_path.exists(): + report = json.loads(report_path.read_text(encoding='utf-8')) + native = report.get('batch_attempt', {}) + if (report.get('ok') is not True + or outcome in {'saved_ok', 'pending_save'} and report.get('stage') != 'native_replace_applied' + or any(native.get(name) != expected[name] for name in + ('session_id', 'generation', 'attempt_id', 'task_id', 'job_id')) + or canonical_path(native.get('project_path', '')) != project): + raise WorkerMonitorError('saved project native write attempt is not bound') + readback_names.append(report_path.name) + if outcome in {'saved_ok', 'pending_save'}: + if not snapshot.is_file() or actual['state'] != 'mutation_possible': + raise WorkerMonitorError('saved project applied write lacks its original mutation attempt') + readback_names.append('writer-expectations-' + job + '.tsv') + proof.setdefault('batch_attempts', []).append({'path': str(path), 'expected': expected}) + proof['files'].append({'path': str(path), 'sha256': hashlib.sha256(internal_path(path).read_bytes()).hexdigest()}) + else: + readback_names.append('post-state-' + job + '.tsv') + if not saved_only and outcome == 'saved_ok': readback_names.extend(('snapshot-' + job + '.tsv', 'snapshot-' + job + '.tsv.native.json', 'value-readback-' + job + '.tsv')) proof['readback_files'] = {name: hashlib.sha256(internal_path(root / name).read_bytes()).hexdigest() for name in readback_names} proof['native_attempt'] = {'session_id': self.session_id, 'generation': self.generation, 'attempt_id': attempt_id} + if saved_only: + proof.update(marker_state='project_saved', saved_only=True, validation_required='saved_netlist_v1', + native_outcomes=dict(rows[1:]), outcomes=dict(rows[1:])) checkpoint['project_commit_source'] = proof write_record(root / 'project-checkpoint.json', checkpoint) self._active_attempts = [] @@ -737,15 +777,19 @@ class BatchCadRuntime: raise ValueError('prewrite project closure marker is missing or stale') manifest_path = root / ('project-commit-' + request[0] + '.tsv') committed = {} + prefix_marker_state = None files = [marker_path, *(path for path, _ in expected)] if internal_path(manifest_path).exists(): rows = [line.split('\t') for line in internal_path(manifest_path).read_text(encoding='utf-8-sig').splitlines()] if (not rows or len(rows[0]) != 3 or rows[0][0] != request[0] - or canonical_path(_decode_vbs_field(rows[0][1])) != project or rows[0][2] != 'project_verified'): + or canonical_path(_decode_vbs_field(rows[0][1])) != project + or rows[0][2] not in {'project_verified', 'project_saved'}): raise ValueError('committed prefix manifest is not bound') + prefix_marker_state = rows[0][2] + allowed_outcomes = {'pending_save', 'no_match'} if prefix_marker_state == 'project_saved' else {'saved_ok', 'no_match'} for row in rows[1:]: if (len(row) != 2 or row[0] not in prefix_jobs or row[0] in committed - or row[1] not in {'saved_ok', 'no_match'}): + or row[1] not in allowed_outcomes): raise ValueError('committed prefix manifest contains an unrelated result') committed[row[0]] = row[1] files.append(manifest_path) @@ -761,6 +805,7 @@ class BatchCadRuntime: session_id=self.session_id, generation=self.generation, attempt_id=attempt_id, resource_record=str(self.path), project_closed=True, native_dispatch_not_started=True, source_sha256=hashlib.sha256(repr(after).encode()).hexdigest(), committed_prefix=committed, + prefix_marker_state=prefix_marker_state, prefix_validation_required=prefix_marker_state == 'project_saved', pause_marker_path=str(marker_path), pause_marker_sha256=hashlib.sha256(internal_path(marker_path).read_bytes()).hexdigest(), commit_manifest_path=str(manifest_path) if committed else None, diff --git a/src/dx_productivity/trial_task_center/execution_journal.py b/src/dx_productivity/trial_task_center/execution_journal.py index 4fc2742..b1b14e2 100644 --- a/src/dx_productivity/trial_task_center/execution_journal.py +++ b/src/dx_productivity/trial_task_center/execution_journal.py @@ -634,6 +634,28 @@ class ExecutionJournal: WHERE task_id=? AND round_id=? AND session_token=? AND state='pending_save' AND proof_json IS NULL''', (_json(proof), task_id, current['round_id'], session_token)) + def promote_project_commit_proof(self, task_id, session_token, expected_proof, verified_proof): + """Attach native verification to the same saved attempt without replacing its source binding.""" + from .execution_proof import proof_intact + with self.store.transaction(): + current = self._round(task_id) + record = self.store._connection.execute('''SELECT * FROM execution_project_commits + WHERE task_id=? AND round_id=? AND session_token=?''', + (task_id, current['round_id'], session_token)).fetchone() if current else None + original = {key: value for key, value in expected_proof.items() if key not in {'files', 'outcomes', 'saved_netlist'}} + if (record is None or record['state'] != 'pending_save' + or expected_proof.get('session_token') != session_token + or expected_proof.get('validation_required') != 'saved_netlist_v1' + or verified_proof.get('saved_netlist', {}).get('status') != 'verified' + or any(verified_proof.get(key) != value for key, value in original.items()) + or any(item not in verified_proof.get('files', []) for item in expected_proof.get('files', [])) + or not proof_intact(verified_proof) + or json.loads(record['proof_json'] or 'null') not in (expected_proof, verified_proof)): + raise TaskCenterError('quick_run_uncertain', '原工程保存证明发生变化,不能覆盖核验结果。') + self.store._connection.execute('''UPDATE execution_project_commits SET proof_json=? + WHERE task_id=? AND round_id=? AND session_token=?''', + (_json(verified_proof), task_id, current['round_id'], session_token)) + def staged_project_rows(self, task_id, session_token): with self.store._lock: current = self._round(task_id) @@ -661,6 +683,16 @@ class ExecutionJournal: or not commit_proof.get('files') or not proof_intact(commit_proof) or any(not proof.get('files') or not proof_intact(proof) for proof in proofs.values())): raise TaskCenterError('quick_run_uncertain', '工程保存回读证明未覆盖全部暂存项。') + saved_protocol = commit_proof.get('marker_state') == 'project_saved' or commit_proof.get('validation_required') == 'saved_netlist_v1' + saved = commit_proof.get('saved_netlist', {}) + if saved_protocol and (commit_proof.get('validation_required') != 'saved_netlist_v1' + or saved.get('status') != 'verified' or set(saved.get('jobs', {})) != set(jobs) + or set(commit_proof.get('native_outcomes', {})) != set(jobs) + or any(state not in {'pending_save', 'no_match'} for state in commit_proof['native_outcomes'].values()) + or commit_proof.get('outcomes') != {job: 'saved_ok' if state == 'pending_save' else state + for job, state in commit_proof['native_outcomes'].items()} + or not saved.get('files') or not proof_intact(saved)): + raise TaskCenterError('quick_run_uncertain', '工程已保存,尚未完成原生数据核验。') records = connection.execute('''SELECT * FROM execution_operations WHERE task_id=? AND round_id=? AND state='pending_save' ''', (task_id, current['round_id'])).fetchall() records = [record for record in records if json.loads(record['receipt_json']).get('session_token') == session_token] @@ -672,14 +704,29 @@ class ExecutionJournal: proof = dict(proofs[job]) if proof.get('native_attempt') != receipt.get('proof', {}).get('native_attempt'): raise TaskCenterError('quick_run_uncertain', '保存回读与原暂存原生尝试不一致。') - proof['project_commit'] = commit_proof - proof['files'] = list(proof['files']) + list(commit_proof['files']) + if saved_protocol: + proof['project_commit'] = dict(session_token=session_token, project_path=commit_proof['project_path'], + validation_required='saved_netlist_v1', + operation_attempts={job: [record['operation_key'], record['attempt_id'], record['generation']]}, + saved_netlist={key: saved[key] for key in ('status', 'export_path', 'export_sha256')}) + command = json.loads(record['command_json']) + proof['baseline'] = dict(project_path=command['project_path'], schematic_name=command['schematic_name'], + sheet_number=command['sheet_number'], validation_mode='saved_netlist_v1', + state='N\tsaved_netlist_v1\t' + saved['export_sha256']) + shared = [{'path': saved['export_path'], 'sha256': saved['export_sha256']}] + if saved.get('verification_path'): + shared.append({'path': saved['verification_path'], 'sha256': saved['verification_sha256']}) + proof['files'] = list(proof['files']) + [item for item in shared if item not in proof['files']] + else: + proof['project_commit'] = commit_proof + proof['files'] = list(proof['files']) + list(commit_proof['files']) attempt = JournalAttempt(task_id, current['round_id'], record['operation_key'], record['attempt_id'], record['generation'], job) connection.execute('''UPDATE execution_operations SET state='prepared' WHERE task_id=? AND round_id=? AND operation_key=?''', (task_id, current['round_id'], record['operation_key'])) native_state = commit_proof.get('outcomes', {}).get(job, 'saved_ok') - self.finish(attempt, native_state, 'project_committed', '工程统一保存、关闭重开及回读校验通过。', proof=proof) + message = '工程统一保存,原生数据核验通过。' if saved_protocol else '工程统一保存、关闭重开及回读校验通过。' + self.finish(attempt, native_state, 'project_committed', message, proof=proof) connection.execute('''UPDATE execution_project_commits SET state='verified',proof_json=? WHERE task_id=? AND round_id=? AND session_token=?''', (_json(commit_proof), task_id, current['round_id'], session_token)) diff --git a/src/dx_productivity/trial_task_center/execution_proof.py b/src/dx_productivity/trial_task_center/execution_proof.py index 96a7a50..8d5423d 100644 --- a/src/dx_productivity/trial_task_center/execution_proof.py +++ b/src/dx_productivity/trial_task_center/execution_proof.py @@ -17,14 +17,35 @@ def proof_intact(proof): except (OSError,ValueError,KeyError,TypeError):return False -def capture_result(data_root,root,row,outcome,*,strict=False,persist=True): +def capture_result(data_root,root,row,outcome,*,strict=False,persist=True,project_commit=None): from .quick_run import _decode_vbs_field, _safe_run_token - from .native_helper import read_snapshot, require_resumable_transaction, snapshot_target_cell + from .native_helper import read_snapshot, require_resumable_transaction, snapshot_target_cell, saved_netlist_snapshot state,code,_=outcome proof={'files':[]} paths=[] try: _safe_run_token(row['job_id']) + snapshot = internal_path(root/f'snapshot-{row["job_id"]}.tsv') + saved_protocol = ((snapshot.is_file() and saved_netlist_snapshot(snapshot)) + or bool(project_commit and project_commit.get('validation_required') == 'saved_netlist_v1')) + if saved_protocol: + proof['validation_required'] = 'saved_netlist_v1' + if state in {'saved_ok', 'no_match'}: + saved = (project_commit or {}).get('saved_netlist', {}) + if saved.get('status') != 'verified' or row['job_id'] not in saved.get('jobs', {}): + raise ValueError('saved native netlist proof is required') + proof['saved_netlist'] = {key:saved[key] for key in ('status','export_path','export_sha256')} + proof['value_readback'] = saved['jobs'][row['job_id']] + if state == 'no_match' and persist: + destination = internal_path(data_root/'execution-proof'/uuid4().hex) + destination.mkdir(parents=True,exist_ok=False) + target = destination/f'no-match-{row["job_id"]}.json' + reference = dict(command=dict(row),session_token=project_commit['session_token'], + **{key:saved[key] for key in ('export_path','export_sha256','verification_path','verification_sha256')}) + data = json.dumps(reference,ensure_ascii=False,sort_keys=True).encode('utf-8') + with target.open('xb') as stream: + stream.write(data);stream.flush();os.fsync(stream.fileno()) + proof['files'].append({'path':str(canonical_path(target)),'sha256':hashlib.sha256(data).hexdigest()}) if row.get('execution_unit') == 'inventory_empty': from .component_scope import validate_empty_command if state != 'batch_skipped' or not validate_empty_command(root, row): @@ -39,7 +60,7 @@ def capture_result(data_root,root,row,outcome,*,strict=False,persist=True): if row.get('execution_unit') == 'inventory_empty': checked[manifest] = checked_manifest baseline=internal_path(root/f'post-state-{row["job_id"]}.tsv') - if baseline.is_file(): + if baseline.is_file() and not saved_protocol: checked[baseline]=baseline.read_bytes() with baseline.open(encoding='utf-8-sig',newline='') as stream: rows=list(csv.DictReader(stream,delimiter='\t')) @@ -53,7 +74,7 @@ def capture_result(data_root,root,row,outcome,*,strict=False,persist=True): proof['baseline']={'project_path':str(canonical_path(row['project_path'])).casefold(), 'schematic_name':actual['schematic_name'],'sheet_number':actual['sheet_number'],'state':actual['semantic_state']} paths.append(baseline) - elif strict and state in {'saved_ok','no_match','restored_ok','recovery_readback'}: + elif strict and not saved_protocol and state in {'saved_ok','no_match','restored_ok','recovery_readback'}: raise ValueError('missing verified semantic state') if state=='saved_ok' or (state=='pending_save' and code == 'session_staged') or (state=='restored_ok' and code in {'recovery_verified','recovery_saved_verified'}): snapshot=internal_path(root/f'snapshot-{row["job_id"]}.tsv') @@ -74,7 +95,8 @@ def capture_result(data_root,root,row,outcome,*,strict=False,persist=True): raise ValueError('snapshot command changed') attempt=report.get('batch_attempt') if strict: - if report.get('stage')!='native_replace_verified' or report.get('ok') is not True: + required_stage = 'native_replace_applied' if saved_protocol else 'native_replace_verified' + if report.get('stage')!=required_stage or report.get('ok') is not True: raise ValueError('native result is not verified') if (not isinstance(attempt,dict) or attempt.get('job_id')!=row['job_id'] or attempt.get('task_id')!=row['task_id'] or @@ -84,6 +106,10 @@ def capture_result(data_root,root,row,outcome,*,strict=False,persist=True): raise ValueError('native attempt differs from this job') proof['native_attempt']=attempt paths.extend((snapshot,report_path)) + if saved_protocol: + writer = internal_path(root/f'writer-expectations-{row["job_id"]}.tsv') + checked[writer] = writer.read_bytes() + paths.append(writer) if any(path.read_bytes()!=data for path,data in checked.items()): raise ValueError('execution evidence changed during receipt binding') if persist and paths: @@ -111,10 +137,12 @@ def capture_project_commit(data_root, root, commit): token, project, state = lines[0].split('\t') outcomes = [line.split('\t') for line in lines[1:] if line] jobs = json.loads(commit['jobs_json']) - if (token != commit['session_token'] or state != 'project_verified' + saved_only = state == 'project_saved' + allowed = {'pending_save', 'no_match'} if saved_only else {'saved_ok', 'no_match'} + if (token != commit['session_token'] or state not in {'project_verified', 'project_saved'} or str(canonical_path(_decode_vbs_field(project))).casefold() != commit['project_path'] or [outcome[0] for outcome in outcomes] != jobs - or any(len(outcome) != 2 or outcome[1] not in {'saved_ok', 'no_match'} for outcome in outcomes)): + or any(len(outcome) != 2 or outcome[1] not in allowed for outcome in outcomes)): raise ValueError('project commit does not cover staged prefix') destination = internal_path(data_root / 'execution-proof' / uuid4().hex) destination.mkdir(parents=True, exist_ok=False) @@ -123,8 +151,11 @@ def capture_project_commit(data_root, root, commit): stream.write(data); stream.flush(); os.fsync(stream.fileno()) if path.read_bytes() != data: raise ValueError('project marker changed during binding') - return dict(session_token=token, project_path=commit['project_path'], jobs=jobs, + proof = dict(session_token=token, project_path=commit['project_path'], jobs=jobs, outcomes=dict(outcomes), files=[dict(path=str(canonical_path(target)), sha256=hashlib.sha256(data).hexdigest())]) + if saved_only: + proof.update(marker_state=state, saved_only=True, validation_required='saved_netlist_v1', native_outcomes=dict(outcomes)) + return proof except (OSError, UnicodeError, ValueError, KeyError, TypeError, IndexError) as error: raise TaskCenterError('quick_run_uncertain', '工程统一保存或回读尚未得到完整证明,保留全部暂存项待核验。') from error diff --git a/src/dx_productivity/trial_task_center/native_helper.py b/src/dx_productivity/trial_task_center/native_helper.py index 34f15e2..b94ec25 100644 --- a/src/dx_productivity/trial_task_center/native_helper.py +++ b/src/dx_productivity/trial_task_center/native_helper.py @@ -142,6 +142,22 @@ def read_snapshot(path): return metadata[0], components +def saved_netlist_snapshot(snapshot): + rows = [line.split('\t') for line in Path(snapshot).read_text(encoding='utf-8-sig').splitlines() if line] + markers = [row for row in rows if row[0] == 'X'] + if ['X', 'saved_netlist_v1'] not in markers: + return False + if (markers != [['X', 'saved_netlist_v1']] or any(row[0] not in {'M', 'C', 'A', 'X', 'L'} for row in rows) + or not any(row[0] == 'C' for row in rows) + or any(len(row) != 8 or row[7] != 'NETLIST' for row in rows if row[0] == 'C')): + raise ValueError('Invalid saved native data snapshot scope') + _, components = read_snapshot(snapshot) + selected = {row[1] for row in components} + if any(len(row) != 12 or decode(row[1]) not in selected for row in rows if row[0] == 'A'): + raise ValueError('Invalid saved native data snapshot attributes') + return True + + def snapshot_value_mode(metadata): return metadata[5] if len(metadata) >= 6 else "part_label" @@ -496,7 +512,8 @@ def check_context(app, api, metadata, records, require_selection=True): or attribute_value(component, "Value") != old_value for component in candidates)): raise ValueError("Selected target changed since inventory") else: - actual = {_component_uid(component) for component in components if attribute_value(component, "Part Number", required=True).casefold() == metadata[2].casefold()} + scope = [component for component in components if _component_uid(component) in wanted] if all(row[7] == "NETLIST" for row in records) else components + actual = {_component_uid(component) for component in scope if attribute_value(component, "Part Number", required=True).casefold() == metadata[2].casefold()} if actual != wanted: raise ValueError(f"Source batch changed since snapshot: expected={sorted(wanted)!r} actual={sorted(actual)!r}") if require_selection: @@ -612,6 +629,21 @@ def select_snapshot_batch(app, api, metadata, records): return components +def applied_replacement_uids(components, records, target): + """Associate just the written targets while the native operation completes.""" + wanted = {row[1] for row in records} + targets = {_component_uid(component): component for component in components + if _component_uid(component) in wanted} + if len(targets) != len(records): + return None + for record in records: + component = targets[record[1]] + if (str(component.Refdes).strip().casefold() != record[2].strip().casefold() + or attribute_value(component, 'Part Number', required=True).casefold() != target.casefold()): + return None + return [record[1] for record in records] + + def existing_replacement_uids(components, records, target, binding, require_part_label=True): matches = replacement_matches(components, records, target, require_part_label, library_row=binding['library_row']) @@ -620,7 +652,7 @@ def existing_replacement_uids(components, records, target, binding, require_part return matches -def promote_pin_numbers(app, api, replacement_uids, slot_count=1, on_progress=None): +def promote_pin_numbers(app, api, replacement_uids, slot_count=1, on_progress=None, *, verify_pins=True): def progress(phase): if on_progress: on_progress(phase) @@ -634,6 +666,8 @@ def promote_pin_numbers(app, api, replacement_uids, slot_count=1, on_progress=No for slot in range(1, int(slot_count) + 1): progress(f'promote_slot_{slot}') app.ActiveView.Block.PromoteSymbolNumbers(1, slot) + if not verify_pins: + return [] progress('query_promoted_pins') promoted = [] for item in app.ActiveView.Query(4096, 0): @@ -733,6 +767,7 @@ def run_native(snapshot, report): from pywinauto import Desktop metadata, records = read_snapshot(snapshot) + native_mode = saved_netlist_snapshot(snapshot) target_cell = snapshot_target_cell(snapshot, required=False) require_part_label = snapshot_value_mode(metadata) == "part_label" app, api = attach() @@ -740,7 +775,7 @@ def run_native(snapshot, report): cell_proof = target_cell_catalog(app, snapshot, metadata, target_cell) if target_cell is not None else None components = components_on_sheet(app, api) wanted = {row[1] for row in records} - if len(metadata) == 10: + if len(metadata) == 10 and not native_mode: verify_unselected_snapshot(snapshot, components, wanted, api=api) source_uids = { _component_uid(component) @@ -751,6 +786,11 @@ def run_native(snapshot, report): binding = require_resumable_transaction(snapshot, report, metadata, records) if binding.get("cell_catalog") != cell_proof: raise ValueError("Current Cell catalog differs from recorded native transaction") + if native_mode: + if report.get("stage") == "native_replace_applied" and report.get("pin_promotion_phase") == "promotion_complete": + report["already_replaced"] = True + return + raise ValueError("Native replacement may already have been applied; verify saved native data before continuing") report["replaced_uids"] = existing_replacement_uids( components, records, metadata[3], binding, require_part_label=require_part_label ) @@ -770,7 +810,7 @@ def run_native(snapshot, report): return components = select_snapshot_batch(app, api, metadata, records) before_uids = {_component_uid(component) for component in components} - untouched = None if len(metadata) == 10 else {_component_uid(component): ( + untouched = None if native_mode or len(metadata) == 10 else {_component_uid(component): ( str(component.Refdes), *(attribute_value(component, name) for name in ("Part Number", "Value", "Part Name", "Part Label")) ) for component in components if _component_uid(component) not in wanted} @@ -937,6 +977,8 @@ def run_native(snapshot, report): def selected_replaced(): nonlocal replacement_poll_count replacement_poll_count += 1 + if native_mode: + return applied_replacement_uids(components_on_sheet(app, api), records, metadata[3]) selected = [api.IVdComp(component._oleobj_) for component in app.ActiveView.Query(128, 1)] if len(selected) == len(records): matches = replacement_matches(selected, records, metadata[3], require_part_label, library_row=columns) @@ -956,7 +998,7 @@ def run_native(snapshot, report): # Preserve the last observed identities without retrying a mutation. report['replacement_timeout'] = {'polls': replacement_poll_count} try: - current = components_on_sheet(app, api) + current = [] if native_mode else components_on_sheet(app, api) refs = {record[2] for record in records} report['replacement_timeout'].update( component_count=len(current), @@ -971,16 +1013,17 @@ def run_native(snapshot, report): except Exception as error: report['replacement_timeout']['target_control_error'] = str(error) raise - current = components_on_sheet(app, api) - verify_replacement_readback(snapshot, current, metadata, records, before_uids, - untouched, require_part_label, columns, report['replaced_uids'], api=api) + if not native_mode: + current = components_on_sheet(app, api) + verify_replacement_readback(snapshot, current, metadata, records, before_uids, + untouched, require_part_label, columns, report['replaced_uids'], api=api) report["stage"] = "native_replace_applied" save_report(snapshot, report) report["stage"] = "pin_promotion_started" save_report(snapshot, report) report["promoted_pins"] = promote_pin_numbers(app, api, report["replaced_uids"], slot_count, - lambda phase: _promotion_phase(snapshot, report, phase)) - report["stage"] = "native_replace_verified" + lambda phase: _promotion_phase(snapshot, report, phase), verify_pins=not native_mode) + report["stage"] = "native_replace_applied" if native_mode else "native_replace_verified" finally: if dialog and win32gui.IsWindow(dialog): close_button = dlg_item(dialog, 1696) diff --git a/src/dx_productivity/trial_task_center/native_netlist.py b/src/dx_productivity/trial_task_center/native_netlist.py index b0d6e5c..55a5397 100644 --- a/src/dx_productivity/trial_task_center/native_netlist.py +++ b/src/dx_productivity/trial_task_center/native_netlist.py @@ -185,6 +185,8 @@ def _parse_ascii(path, *, hierarchy_boundaries=(), require_connections=True): symbol['refdes'] = attrs.get('Ref Designator', '') elif attrs.get('Ref Designator') and attrs['Ref Designator'] != symbol['refdes']: symbol['source_refdes'], symbol['refdes'] = symbol['refdes'], attrs['Ref Designator'] + # Port names can contain '/', so retain the reported path even at the root. + symbol['instance_path'] = '' if paths[0] == 'root' else paths[0] if _is_pcb(symbol) and (not symbol['refdes'] or attrs.get('Ref Designator') != symbol['refdes']): raise ValueError(f'PCB component identity is ambiguous: {uid!r} / {symbol["refdes"]!r}') raw_identity = uid diff --git a/src/dx_productivity/trial_task_center/netlist_verification.py b/src/dx_productivity/trial_task_center/netlist_verification.py index 49f1b54..4e39960 100644 --- a/src/dx_productivity/trial_task_center/netlist_verification.py +++ b/src/dx_productivity/trial_task_center/netlist_verification.py @@ -1,5 +1,5 @@ """Overlap native exports with replacement, keeping each saved input immutable.""" -from concurrent.futures import ThreadPoolExecutor +from concurrent.futures import Future, ThreadPoolExecutor from dataclasses import asdict import json import hashlib @@ -54,7 +54,7 @@ def library_from_receipt(command, receipt): if receipt.get('native_state') not in {'saved_ok', 'restored_ok'}: return {} from .execution_proof import proof_intact - from .native_helper import read_snapshot, require_resumable_transaction + from .native_helper import read_snapshot, require_resumable_transaction, saved_netlist_snapshot from .path_access import canonical_path, internal_path proof = receipt.get('proof', {}) native_files = [Path(item['path']) for item in proof.get('files', ()) @@ -70,7 +70,11 @@ def library_from_receipt(command, receipt): if str(snapshot) not in paths: raise ValueError('原生库件证据缺少配套快照') report = json.loads(internal_path(path).read_text(encoding='utf-8')) - if report.get('ok') is not True or report.get('stage') != 'native_replace_verified': + saved_native = saved_netlist_snapshot(snapshot) + if saved_native and proof.get('saved_netlist', proof.get('project_commit', {}).get('saved_netlist', {})).get('status') != 'verified': + raise ValueError('已保存的原生数据尚未核验,不能使用写入回执声明成功') + stage = 'native_replace_applied' if saved_native else 'native_replace_verified' + if report.get('ok') is not True or report.get('stage') != stage: raise ValueError('原生库件回执未通过实际替换核验') metadata, records = read_snapshot(snapshot) binding = require_resumable_transaction(snapshot, report, metadata, records) @@ -101,9 +105,11 @@ def library_from_receipt(command, receipt): 'schematic_name': command.get('schematic_name',''), 'sheet_number': command.get('sheet_number','')} if uid in values: value = values[uid] + native_empty = (saved_native and value['actual_value'] == '' and value['actual_value_present'] is None + and value.get('value_presence_coverage') == 'native_ascii_empty_presence_unknown') if (value['actual_part_number'].casefold() != row[1].casefold() or not isinstance(value['actual_value'], str) - or type(value['actual_value_present']) is not bool): + or (type(value['actual_value_present']) is not bool and not native_empty)): raise ValueError('Value 回读证据与目标库件不符') identity.update(preserved_value=value['actual_value'], preserved_value_present=value['actual_value_present']) @@ -360,6 +366,18 @@ class NetlistVerification: return try: record['library'] = _library_expectations(record['child'], task_id) + preparer = getattr(record['child'], '_quick_run_preparer', None) + if preparer is not None: + from .saved_netlist_verification import load_saved_export + saved = load_saved_export(preparer.data_root / 'quick-run', + Path(record['before_capture']['project'])) + if saved is not None: + exported = Future() + exported.set_result(saved['result']) + record.update(after_capture=saved['capture'], + after_export=Path(saved['export_path']).parent, + after=exported) + return directory = record['directory'] attempt = uuid4().hex capture = native_netlist.capture_project(Path(record['before_capture']['project']), diff --git a/src/dx_productivity/trial_task_center/quick_run.py b/src/dx_productivity/trial_task_center/quick_run.py index c94ffbd..5472708 100644 --- a/src/dx_productivity/trial_task_center/quick_run.py +++ b/src/dx_productivity/trial_task_center/quick_run.py @@ -353,7 +353,7 @@ class QuickRunPreparer: journal_rows, ) - def _bind_journal_handoff(self, task_id, handoff): + def _bind_journal_handoff(self, task_id, handoff, *, append_only=False): journal = getattr(self, 'journal', None) if journal is None: return {} @@ -365,7 +365,8 @@ class QuickRunPreparer: proof_reader=lambda row,outcome:self.result_proof(handoff.command_path.parent,row,outcome)) additional = tuple((job, *outcome) for job, outcome in restored.items() if latest.get(job) != outcome) if additional: - _write_status_details(handoff.status_path, (*details, *additional)) + if append_only:_append_status_details(handoff.status_path,additional) + else:_write_status_details(handoff.status_path, (*details, *additional)) return {row['job_id']: row for row in rows} def reconcile_terminal_receipts(self, task_id): @@ -383,10 +384,10 @@ class QuickRunPreparer: _write_uncertain_flag(root/'uncertain.flag','uncommitted_receipt_requires_verification') raise - def result_proof(self, root, row, outcome, *, persist=True): + def result_proof(self, root, row, outcome, *, persist=True, project_commit=None): from .execution_proof import capture_result return capture_result(self._data_root,root,row,outcome, - strict=self._process_runner is _run_process,persist=persist) + strict=self._process_runner is _run_process,persist=persist,project_commit=project_commit) def _commit_staged_project(self, task_id, *, session_token=None, bind_source=False): journal = getattr(self, 'journal', None) @@ -410,16 +411,34 @@ class QuickRunPreparer: from .execution_proof import bind_project_commit_source commit_proof = bind_project_commit_source(commit_proof, self._data_root, root, commit['project_path']) commit_proof['operation_attempts'] = journal.project_commit_attempts(task_id, commit['session_token']) + staged = journal.staged_project_rows(task_id, commit['session_token']) + saved_protocol = commit_proof.get('validation_required') == 'saved_netlist_v1' + if saved_protocol: + from .saved_netlist_verification import verify_saved_project + for receipt in staged: + for item in receipt['proof'].get('files', ()): + name = Path(item['path']).name + if hashlib.sha256(_io_path(root/name).read_bytes()).hexdigest() != item['sha256']: + raise ValueError('staged native target evidence changed before saved export') + if not commit_proof.get('readback_files'): + names = [name for job, state in commit_proof['native_outcomes'].items() if state == 'pending_save' + for name in (f'snapshot-{job}.tsv', f'snapshot-{job}.tsv.native.json', f'writer-expectations-{job}.tsv')] + commit_proof['readback_files'] = {name:hashlib.sha256(_io_path(root/name).read_bytes()).hexdigest() for name in names} + journal.bind_project_commit_proof(task_id, commit['session_token'], commit_proof) + before_validation = commit_proof + commit_proof = verify_saved_project(self._data_root, root, commit_proof, [receipt['row'] for receipt in staged]) + journal.promote_project_commit_proof(task_id, commit['session_token'], before_validation, commit_proof) proofs = {} - for receipt in journal.staged_project_rows(task_id, commit['session_token']): + for receipt in staged: row = receipt['row'] - outcome = (commit_proof['outcomes'][row['job_id']], 'project_committed', '工程保存回读校验通过。') - proof = self.result_proof(root, row, outcome) + outcome = (commit_proof['outcomes'][row['job_id']], 'project_committed', + '工程统一保存,原生数据核验通过。' if saved_protocol else '工程保存回读校验通过。') + proof = self.result_proof(root, row, outcome, project_commit=commit_proof) if saved_protocol else self.result_proof(root,row,outcome) if outcome[0] == 'saved_ok': from .value_readback import capture_value_readback proof['value_readback'] = capture_value_readback(root, row, outcome, project_commit=commit_proof) proofs[row['job_id']] = proof - if bind_source and not commit.get('proof_json'): + if bind_source and not commit.get('proof_json') and not saved_protocol: commit_proof['readback_files'] = {Path(item['path']).name: item['sha256'] for proof in proofs.values() for item in proof.get('files', ())} for job, outcome in commit_proof['outcomes'].items(): @@ -428,6 +447,10 @@ class QuickRunPreparer: if value_path.is_file():commit_proof['readback_files'][value_path.name] = hashlib.sha256(value_path.read_bytes()).hexdigest() journal.bind_project_commit_proof(task_id, commit['session_token'], commit_proof) journal.commit_project_results(task_id, commit['session_token'], proofs, commit_proof) + if saved_protocol: + handoff = QuickRunResult(root/'QuickPartReplace.vbs',root/'command.tsv',root/'status.tsv', + root/'quick-part-replace.log',self.vbs_root_compatible) + self._bind_journal_handoff(task_id,handoff,append_only=True) record_operation(root, 'readback_proof', 'return', item_id=commit['session_token']) for job in commit_proof['jobs']: record_operation(root, 'item', 'return', item_id=job) @@ -461,7 +484,7 @@ class QuickRunPreparer: elif protection not in allowed and interrupted is None:return None if not confirmed: raise TaskCenterError('quick_run_recovery_confirmation', '工程提交回执核验需要明确确认。') - from .execution_proof import capture_project_commit, validate_project_commit_source + from .execution_proof import capture_project_commit, validate_project_commit_source, proof_intact from .execution_journal import read_command_rows, command_identity, _hash from .batch_resources import write_record try: @@ -470,14 +493,40 @@ class QuickRunPreparer: current = journal._round(task_id) if json.loads(current['plan_json']) != [_hash(command_identity(row)) for row in rows]: raise ValueError('frozen command plan changed') + positions = {row['job_id']:index for index,row in enumerate(rows)} + markers = {commit['session_token']:capture_project_commit(self._data_root,root,commit) for commit in commits} + ends = {token:max(positions[job] for job in marker['jobs']) for token,marker in markers.items()} + latest = {} + for commit in commits: + token = commit['session_token'] + if markers[token].get('validation_required') == 'saved_netlist_v1': + latest[commit['project_path']] = max(latest.get(commit['project_path'],-1),ends[token]) + historical = set() + def historical_intact(proof): + saved = proof['saved_netlist'] + verified = json.loads(_io_path(saved['verification_path']).read_text(encoding='utf-8')) + context = {key:proof[key] for key in ('session_token','project_path','saved_sources','command_sha256')} + context['marker_sha256'] = proof['files'][0]['sha256'] + return (proof_intact(proof) and saved.get('status') == 'verified' + and proof['command_sha256'] == hashlib.sha256(_io_path(root/'command.tsv').read_bytes()).hexdigest() + and hashlib.sha256(_io_path(saved['verification_path']).read_bytes()).hexdigest() == saved['verification_sha256'] + and hashlib.sha256(_io_path(saved['export_path']).read_bytes()).hexdigest() == saved['export_sha256'] + and verified.get('status') == 'verified' and verified.get('context') == context + and verified.get('export_path') == saved['export_path'] and verified.get('export_sha256') == saved['export_sha256'] + and verified.get('jobs') == saved.get('jobs') and set(saved['jobs']) == set(proof['jobs']) + and proof['outcomes'] == {job:'saved_ok' if state == 'pending_save' else state + for job,state in proof['native_outcomes'].items()}) covered = set() covered_attempts = [] for commit in commits: if Path(commit['evidence_root']).resolve() != root.resolve():raise ValueError('foreign commit root') proof = json.loads(commit['proof_json'] or '{}') + prior = (commit['state'] == 'verified' and proof.get('validation_required') == 'saved_netlist_v1' + and ends[commit['session_token']] < latest.get(commit['project_path'],-1)) + if prior:historical.add(commit['session_token']) if proof and proof.get('operation_attempts') != journal.project_commit_attempts(task_id, commit['session_token']): raise ValueError('original project attempts changed') - if not proof or interrupted is not None: + if not proof or interrupted is not None and not prior: from .batch_resources import _valid_record checkpoint = json.loads(_io_path(root / 'project-checkpoint.json').read_text(encoding='utf-8')) owner_path = Path(checkpoint['resource_record']) @@ -500,25 +549,28 @@ class QuickRunPreparer: or task_id not in supervisor.get('protected_task_ids', ())): raise ValueError('supervisor interruption is not bound to the closed native worker') proof = dict(proof, operation_attempts=journal.project_commit_attempts(task_id, commit['session_token'])) - if (not validate_project_commit_source(proof, root) + if (not (historical_intact(proof) if prior else validate_project_commit_source(proof, root)) or proof.get('operation_attempts') != journal.project_commit_attempts(task_id, commit['session_token'])): raise ValueError('saved source or original attempts changed') - marker = capture_project_commit(self._data_root, root, commit) - if (marker['jobs'] != proof.get('jobs') or marker['outcomes'] != proof.get('outcomes') + marker = markers[commit['session_token']] + if (marker['jobs'] != proof.get('jobs') or marker['outcomes'] != proof.get('native_outcomes',proof.get('outcomes')) or marker['files'][0]['sha256'] != proof['files'][0]['sha256']): raise ValueError('native project marker changed') covered.update(proof['jobs']) covered_attempts.extend(proof['operation_attempts'].values()) for row in rows: if row['job_id'] not in proof['jobs']:continue - outcome = (proof['outcomes'][row['job_id']], 'project_committed', '工程保存回读校验通过。') + saved_protocol = proof.get('validation_required') == 'saved_netlist_v1' + state = proof.get('native_outcomes',proof['outcomes'])[row['job_id']] if saved_protocol else proof['outcomes'][row['job_id']] + if saved_protocol and state == 'no_match':continue + outcome = (state, 'session_staged' if saved_protocol else 'project_committed', '工程保存回读校验通过。') result = self.result_proof(root, row, outcome) - if proof.get('native_attempt') and outcome[0] == 'saved_ok' and any( + if proof.get('native_attempt') and outcome[0] in {'saved_ok','pending_save'} and any( result.get('native_attempt', {}).get(key) != value for key, value in proof['native_attempt'].items()): raise ValueError('native result differs from the exited project worker') if any(proof.get('readback_files', {}).get(Path(item['path']).name) != item['sha256'] for item in result.get('files', ())): raise ValueError('saved native readback evidence changed') - if outcome[0] == 'saved_ok': + if outcome[0] == 'saved_ok' and not saved_protocol: from .value_readback import capture_value_readback if capture_value_readback(root, row, outcome, project_commit=proof).get('value_readback_status') != 'verified': raise ValueError('saved target Value readback is incomplete') @@ -535,7 +587,8 @@ class QuickRunPreparer: self._commit_staged_project(task_id) for commit in commits: proof = json.loads(commit['proof_json']) - if not validate_project_commit_source(proof, root):raise ValueError('saved source changed during recovery') + if not (historical_intact(proof) if commit['session_token'] in historical else validate_project_commit_source(proof, root)): + raise ValueError('saved source or historical proof changed during recovery') handoff = QuickRunResult(root/'QuickPartReplace.vbs', root/'command.tsv', root/'status.tsv', root/'quick-part-replace.log', self.vbs_root_compatible) self._bind_journal_handoff(task_id, handoff) if protection is not None: @@ -579,7 +632,8 @@ class QuickRunPreparer: def write_expected_baselines(self, task_id, root, project_path): journal=getattr(self,'journal',None) if journal is None:return - rows=journal.expected_baselines(task_id,project_path) + rows=tuple(row for row in journal.expected_baselines(task_id,project_path) + if row.get('validation_mode') != 'saved_netlist_v1') text='project_path\tschematic_name\tsheet_number\tsemantic_state\r\n' text+=''.join('\t'.join(_encode_vbs_field(row[key]) for key in ('project_path','schematic_name','sheet_number','state'))+'\r\n' for row in rows) @@ -618,6 +672,31 @@ class QuickRunPreparer: uncertain_path = self._data_root / "quick-run" / "uncertain.flag" if _io_path(uncertain_path).exists(): raise TaskCenterError("quick_run_uncertain", "a previous quick-run worker timed out or returned an uncorrelated status; reconcile the project before retrying") + if (self._process_runner is _run_process and getattr(self,'journal',None) is not None + and (project_session is None or not project_session.enabled)): + if not batch_mode: + from .single_step import prepare_private_single_step + prepare_private_single_step(self,task_id,projects,rules,copy_part_number_to_value, + **({'runtime':runtime} if runtime is not None else {})) + session = batch_session or self.begin_batch_session(task_id,projects,rules, + copy_part_number_to_value=copy_part_number_to_value,runtime=runtime) + if session.next_index >= len(session.commands): + raise TaskCenterError('quick_run_complete','all replacement rules in this queue are complete') + job = session.commands[session.next_index][1] + # A standalone or explicitly nonretained call still needs one closed, + # saved native prefix. The scope is held for this invocation only. + with self.project_session_scope(enabled=True,runtime=runtime) as scope: + result = self.execute_step(task_id,projects,rules,copy_part_number_to_value=copy_part_number_to_value, + expected_item=expected_item,batch_mode=True,batch_session=session,project_session=scope, + runtime=runtime,stop_event=stop_event) + if result.state == 'pending_save': + self.complete_project_session(task_id,scope,session,projects) + if result.state not in DONE_STATES | {'pending_save'}:return result + terminal = next(entry for entry in reversed(session.statuses) if entry[0] == job) + progress = session.progress + return QuickRunStepResult(result.script_path,result.command_path,result.status_path,result.log_path, + terminal[1],terminal[3],progress.next_project_path,progress.next_old_part_number, + progress.next_new_part_number,progress.next_schematic_name,progress.next_sheet_number,progress) if self._process_runner is _run_process and not batch_mode: from .single_step import prepare_private_single_step prepare_private_single_step(self, task_id, projects, rules, copy_part_number_to_value, @@ -1036,7 +1115,8 @@ class QuickRunPreparer: or (stop_event is not None and stop_event.is_set())): progress = self.complete_project_session(task_id, project_session, batch_session, projects) state = 'no_match' if code == 'session_staged_no_match' else 'saved_ok' - message = '工程统一保存、关闭重开及回读校验通过。' + message = ('工程统一保存,原生数据核验通过。' if proof.get('validation_required') == 'saved_netlist_v1' + else '工程统一保存、关闭重开及回读校验通过。') next_command = commands[batch_session.next_index] if batch_session is not None and batch_session.next_index < len(commands) else None next_sheet = batch_session.sheets.get(next_command[1], (None, None)) if batch_session is not None and next_command is not None and batch_session.sheets is not None else (None, None) return QuickRunStepResult(handoff.script_path, handoff.command_path, handoff.status_path, handoff.log_path, @@ -1763,6 +1843,22 @@ def _recover_pre_mutation_hard_failures( ) +def _append_status_details(path: Path, statuses: tuple[tuple[str, str, str, str], ...]) -> None: + """Publish closed-project receipts without replacing an active batch stream.""" + payload = ''.join('\t'.join(_encode_vbs_field(field) for field in entry)+'\r\n' for entry in statuses).encode('utf-8') + try: + with _io_path(path).open('r+b') as stream: + stream.seek(0,os.SEEK_END) + end = stream.tell() + if end: + stream.seek(-1,os.SEEK_END) + if stream.read(1) != b'\n':raise ValueError('cannot append to an incomplete status stream') + stream.seek(0,os.SEEK_END) + stream.write(payload);stream.flush();os.fsync(stream.fileno()) + except (OSError,ValueError) as error: + raise TaskCenterError('quick_run_status','cannot publish saved project status') from error + + def _write_status_details(path: Path, statuses: tuple[tuple[str, str, str, str], ...]) -> None: temporary = path.with_name(f".{path.name}.{uuid4().hex}.tmp") text = "job_id\tstate\tcode\tmessage\r\n" diff --git a/src/dx_productivity/trial_task_center/saved_netlist_verification.py b/src/dx_productivity/trial_task_center/saved_netlist_verification.py new file mode 100644 index 0000000..79b8e34 --- /dev/null +++ b/src/dx_productivity/trial_task_center/saved_netlist_verification.py @@ -0,0 +1,273 @@ +"""Validate a closed project's applied targets through one saved native export.""" +import hashlib +import json +import re +from collections import Counter +from pathlib import Path + +from . import native_netlist +from .batch_resources import write_record +from .execution_proof import proof_intact, validate_project_commit_source +from .path_access import canonical_path, internal_path +from .quick_run_protocol import _decode_vbs_field + + +def _hash(path): + return hashlib.sha256(internal_path(path).read_bytes()).hexdigest() + + +def _fields(line): + return [_decode_vbs_field(value) for value in line.split('\t')] + + +def _context(proof): + return {key: proof[key] for key in ('session_token', 'project_path', 'saved_sources', 'command_sha256')} + + +def _intact(record): + return (record.get('files') and proof_intact(record) + and all(_hash(path) == digest for path, digest in record['context']['saved_sources'].items()) + and _hash(record['export_path']) == record['export_sha256']) + + +def _authoritative_export(record): + """The mutable lookup record cannot supply graph data or captured inputs.""" + result = json.loads(internal_path(record['export_path']).read_text(encoding='utf-8')) + capture = result['capture'] + source_hashes = {str(canonical_path(path)).casefold():digest for path,digest in capture['source_hashes'].items()} + if (result.get('status') != 'success' or result.get('complete') is not True + or canonical_path(capture['project']) != canonical_path(record['context']['project_path']) + or any(source_hashes.get(str(canonical_path(path)).casefold()) != digest + for path,digest in record['context']['saved_sources'].items()) + or set(result['outputs'].values()) != set(record['output_hashes']) + or any(_hash(path) != record['output_hashes'][path] for path in result['outputs'].values())): + raise ValueError('immutable saved native export differs from its original source binding') + native_netlist._check_capture(capture) + return result + + +def load_saved_export(root, project): + """Return a verified intact shared export for the current saved source, or None.""" + try: + record = json.loads(internal_path(Path(root) / 'saved-netlist-export.json').read_text(encoding='utf-8')) + if (record.get('status') == 'verified' + and canonical_path(record['context']['project_path']) == canonical_path(project) + and record['context']['command_sha256'] == _hash(Path(root) / 'command.tsv') + and record['context']['marker_sha256'] == _hash(Path(root) / ('project-commit-' + record['context']['session_token'] + '.tsv')) + and _intact(record)): + if _hash(record['verification_path']) != record['verification_sha256']: + raise ValueError('immutable saved target verification changed') + verified = json.loads(internal_path(record['verification_path']).read_text(encoding='utf-8')) + if any(verified.get(key) != record[key] for key in ('status','context','export_path','export_sha256')): + raise ValueError('saved target lookup differs from its immutable verification') + record['jobs'] = verified['jobs'] + record['result'] = _authoritative_export(record) + record['capture'] = record['result']['capture'] + return record + except (OSError, ValueError, KeyError, TypeError):pass + return None + + +def compact_saved_netlist(record, *, include_jobs=True): + result = {key: record[key] for key in ('status', 'export_path', 'export_sha256')} + result.update(verification_path=record['verification_path'], verification_sha256=record['verification_sha256']) + if include_jobs: + result.update(context=record['context'], jobs=record['jobs'], files=record['files']) + return result + + +def _expectations(root, row): + from .execution_proof import capture_result + from .native_helper import read_snapshot, require_resumable_transaction, saved_netlist_snapshot + snapshot = internal_path(root / f'snapshot-{row["job_id"]}.tsv') + if not saved_netlist_snapshot(snapshot):raise ValueError('saved netlist target snapshot protocol required') + # This validates the command, selected original target set and native attempt. + capture_result(root.parent, root, row, ('pending_save', 'session_staged', ''), strict=True, persist=False) + metadata, components = read_snapshot(snapshot) + report_path = Path(str(snapshot) + '.native.json') + report = json.loads(report_path.read_text(encoding='utf-8')) + binding = require_resumable_transaction(snapshot, report, metadata, components) + library = binding['library_row'] + if library[1].casefold() != row['new_part'].casefold():raise ValueError('native library target changed') + writer = internal_path(root / f'writer-expectations-{row["job_id"]}.tsv') + records = [_fields(line) for line in writer.read_text(encoding='utf-8-sig').splitlines() if line] + header = ['W', '1', row['task_id'], row['job_id'], row['project_path'], + row.get('schematic_name',''), row.get('sheet_number',''), snapshot.read_bytes().decode('utf-8-sig')] + if not records or records[0] != header:raise ValueError('writer expectations are not bound to the original snapshot and command') + original = {item[1]: item[2] for item in components} + if row.get('target_scope') == 'targets': + selectors = [value.split('\x1f') for value in row.get('target_selectors','').split('\x1e')] + if (not selectors or any(len(value) != 3 or not value[1].strip() for value in selectors) + or {value[1].strip().casefold() for value in selectors} != {ref.strip().casefold() for ref in original.values()}): + raise ValueError('native snapshot reference set differs from the frozen target selectors') + old_values = {} + for line in snapshot.read_text(encoding='utf-8-sig').splitlines(): + fields = _fields(line) + if fields[0] == 'A' and len(fields) == 12 and fields[2].casefold() == 'value': + if fields[1] in old_values:raise ValueError('original Value is ambiguous') + old_values[fields[1]] = fields[4] or fields[3] + has_nc = lambda text: '/' in text and any(part.strip().casefold() == 'nc' for part in text.split('/')) + expected = {} + for fields in records[1:]: + if len(fields) != 9 or fields[0] != 'C':raise ValueError('malformed writer target expectation') + _, uid, ref, value, present, name, label, part, cell = fields + if (uid not in original or uid in expected or ref != original[uid] or present not in {'0','1'} + or name != library[4] or label != library[5] or part.casefold() != row['new_part'].casefold() + or cell != row.get('target_cell','')): + raise ValueError('writer target expectation differs from native library/command') + mode = row['value_mode'] + if mode != 'preserve': + policy_value = {'custom': row.get('custom_value',''), 'part_number': row['new_part'], 'part_label': library[5]}[mode] + if row.get('sync_nc','1') == '1' and has_nc(old_values.get(uid,'')) and not has_nc(policy_value): + policy_value = policy_value.rstrip(' ') + ('NC' if policy_value.rstrip(' ').endswith('/') else '/NC') + if present != '1' or value != policy_value:raise ValueError('writer Value contradicts the frozen write policy') + if row.get('sync_nc','1') == '1' and has_nc(old_values.get(uid,'')) and not has_nc(value): + raise ValueError('required original NC marker was not retained') + expected[uid] = dict(refdes=ref, value=value, present=present == '1', old_value=old_values.get(uid), + attributes={'Part Number': part, 'Part Name': name, 'Part Label': label}, target_cell=cell) + if set(expected) != set(original):raise ValueError('writer target set is incomplete') + return expected, binding, [snapshot, report_path, writer] + + +def _scope(component, row): + return all(not row.get(key) or component.get(field) == row[key] + for key, field in (('schematic_name','source_schematic'), ('sheet_number','source_page'))) + + +def _observations(graph, row, expected, binding): + observations = [] + counts = Counter(item['refdes'].strip().casefold() for item in expected.values()) + remaining = {} + for uid, item in expected.items(): + ref = item['refdes'].strip().casefold() + if ref not in remaining: + keys = native_netlist.reference_targets(graph, item['refdes'], + sheet=row.get('sheet_number',''), schematic=row.get('schematic_name','')) + if len(keys) != counts[ref] or not keys: + raise ValueError('saved native target units are missing or ambiguous') + if any(not _scope(graph['components'][key],row) or graph['components'][key].get('ambiguous_attributes') for key in keys): + raise ValueError('saved native target sheet or attributes are ambiguous') + remaining[ref] = list(keys) + # Match the declared multiset within one physical reference. Native UIDs + # may change; no expected property is inferred from the exported graph. + matches = [] + for key in remaining[ref]: + attrs = graph['components'][key]['attributes'] + if (all(attrs.get(name) is not None and + (attrs[name].casefold() == value.casefold() if name == 'Part Number' else attrs[name] == value) + for name,value in item['attributes'].items()) + and (not item['target_cell'] or attrs.get('Cell Name') == item['target_cell']) + and attrs.get('Value','') == item['value']): + matches.append(key) + if not matches:raise ValueError('saved native target library attributes, Cell or Value differ from the write policy') + key = matches[0] + remaining[ref].remove(key) + symbol = graph['components'][key].get('symbol','') + if symbol: + target = re.fullmatch(r'(?:[^:\s]+:)?([^:\s]+?)(?:\.(\d+))?', binding['target_symbol']) + actual = re.match(r'([^\s]+?)\.(\d+) type ', symbol) + if (not target or not actual or target[1] != actual[1] + or target[2] is not None and target[2] != actual[2] + or not 1 <= int(actual[2]) <= binding['slot_count']): + raise ValueError('saved native target symbol differs from the selected library') + actual = graph['components'][key]['attributes'] + observations.append(dict(uid=uid, refdes=item['refdes'], old_part_number=row['old_part'], + actual_part_number=actual['Part Number'], old_value=item['old_value'], actual_value=actual.get('Value',''), + old_value_present=item['old_value'] is not None, + actual_value_present=True if actual.get('Value') else None, + value_presence_coverage='native_ascii_empty_presence_unknown', actual_cell=actual.get('Cell Name',''))) + return dict(value_readback_status='verified', value_readback=observations, value_readback_job_id=row['job_id'], + project_path=row['project_path'], schematic_name=row.get('schematic_name',''), sheet_number=row.get('sheet_number',''), + coverage_limits=['Native ASCII empty Value does not prove attribute presence; CAD display/layout is not checked.']) + + +def verify_saved_project(data_root, root, proof, rows, *, stop_event=None): + """Export once, validate all applied targets, and return the verified commit proof.""" + from .netlist_verification import _export_saved_capture + root, data_root = Path(root), Path(data_root) + if proof.get('validation_required') != 'saved_netlist_v1' or not validate_project_commit_source(proof, root): + raise ValueError('saved source-bound project proof is required') + def readbacks_intact(): + return all(Path(name).name == name and _hash(root/name) == digest + for name,digest in proof.get('readback_files',{}).items()) + if not readbacks_intact():raise ValueError('native writer evidence changed before saved export') + rows = {row['job_id']: row for row in rows} + if not set(proof['jobs']) <= rows.keys():raise ValueError('saved prefix is outside the frozen command plan') + context = _context(proof) + context['marker_sha256'] = proof['files'][0]['sha256'] + evidence, inputs = {}, [] + for job in proof['jobs']: + if proof.get('native_outcomes', proof['outcomes'])[job] == 'pending_save': + evidence[job] = _expectations(root, rows[job]) + inputs.extend(evidence[job][2]) + pointer = root / 'saved-netlist-export.json' + record = None + try: + candidate = json.loads(internal_path(pointer).read_text(encoding='utf-8')) + if candidate['context'] == context and _intact(candidate):record = candidate + except (OSError, ValueError, KeyError, TypeError):pass + if record is None: + directory = data_root / 'execution-proof' / ('saved-netlist-' + proof['session_token']) + capture_path = directory / 'capture/capture.json' + if capture_path.is_file(): + capture = json.loads(capture_path.read_text(encoding='utf-8')) + native_netlist._check_capture(capture) + source_hashes = {str(canonical_path(path)).casefold():digest for path,digest in capture['source_hashes'].items()} + if (canonical_path(capture['project']) != canonical_path(proof['project_path']) + or any(source_hashes.get(str(canonical_path(path)).casefold()) != digest for path,digest in proof['saved_sources'].items())): + raise ValueError('saved native capture belongs to a different original source') + else: + capture = native_netlist.capture_project(Path(proof['project_path']), directory / 'capture') + if not validate_project_commit_source(proof, root):raise ValueError('saved source changed while capturing the native database') + result = _export_saved_capture(capture, directory / 'export', stop_event=stop_event) + if result.get('status') != 'success' or result.get('complete') is not True: + raise ValueError('complete native saved export unavailable: ' + str(result.get('reason',''))) + manifest = directory / 'export/netlist.json' + paths = [Path(capture['manifest_path']), manifest, *map(Path,result['outputs'].values()), + *(Path(capture['root']) / name for name in capture['capture_hashes'])] + for path in inputs: + target = internal_path(directory / 'inputs' / path.name) + target.parent.mkdir(parents=True,exist_ok=True) + data = internal_path(path).read_bytes(); target.write_bytes(data) + if internal_path(path).read_bytes() != data:raise ValueError('native target evidence changed during capture') + paths.append(target) + files = [{'path':str(canonical_path(path)), 'sha256':_hash(path)} for path in dict.fromkeys(paths)] + record = dict(status='exported', context=context, capture=capture, result=result, + export_path=str(canonical_path(manifest)), export_sha256=_hash(manifest), + output_hashes={str(canonical_path(path)):_hash(path) for path in result['outputs'].values()}, files=files) + write_record(pointer, record) + record['result'] = _authoritative_export(record) + record['capture'] = record['result']['capture'] + graph, jobs = record['result']['graph'], {} + for job in proof['jobs']: + row = rows[job] + if job in evidence: + expected, binding, _ = evidence[job] + jobs[job] = _observations(graph, row, expected, binding) + else: + candidates = [item for item in graph['components'].values() if _scope(item,row)] + if row.get('target_scope') == 'targets': + refs = {item.split('\x1f')[1].strip().casefold() for item in row['target_selectors'].split('\x1e')} + candidates = [item for item in candidates if item.get('refdes','').strip().casefold() in refs] + if any(item['attributes'].get('Part Number','').casefold() == row['old_part'].casefold() for item in candidates): + raise ValueError('native no-match claim still has original targets in the saved scope') + jobs[job] = dict(value_readback_status='verified',value_readback=[],value_readback_job_id=job, + project_path=row['project_path'],schematic_name=row.get('schematic_name',''),sheet_number=row.get('sheet_number','')) + if not validate_project_commit_source(proof,root) or not _intact(record) or not readbacks_intact(): + raise ValueError('saved source/export or writer evidence changed during target validation') + record.update(status='verified',jobs=jobs) + verification = Path(record['export_path']).parent / 'verification.json' + verification_value = {key:record[key] for key in ('status','context','export_path','export_sha256','jobs')} + if verification.is_file(): + if json.loads(verification.read_text(encoding='utf-8')) != verification_value: + raise ValueError('saved native target verification changed on resume') + else:write_record(verification,verification_value) + record.update(verification_path=str(canonical_path(verification)),verification_sha256=_hash(verification)) + if not any(item['path'] == str(canonical_path(verification)) for item in record['files']): + record['files'].append({'path':str(canonical_path(verification)),'sha256':_hash(verification)}) + write_record(pointer,record) + result = dict(proof, saved_netlist=compact_saved_netlist(record)) + result['native_outcomes'] = proof.get('native_outcomes',proof['outcomes']) + result['outcomes'] = {job:'saved_ok' if state == 'pending_save' else state for job,state in result['native_outcomes'].items()} + result['files'] = list({(item['path'],item['sha256']):item for item in [*proof['files'],*record['files']]}.values()) + return result diff --git a/src/dx_productivity/trial_task_center/value_readback.py b/src/dx_productivity/trial_task_center/value_readback.py index 115314c..acc4b58 100644 --- a/src/dx_productivity/trial_task_center/value_readback.py +++ b/src/dx_productivity/trial_task_center/value_readback.py @@ -142,6 +142,18 @@ def _validated(root, row, outcome, *, project_commit=None): def capture_value_readback(root, row, outcome, *, project_commit=None): try: + if project_commit and project_commit.get('validation_required') == 'saved_netlist_v1': + saved = project_commit['saved_netlist'] + details = saved['jobs'][row['job_id']] + binding = dict(command=dict(row),terminal=[row['job_id'],*outcome], + verification_path=saved['verification_path'], verification_sha256=saved['verification_sha256'], + export_path=saved['export_path'], export_sha256=saved['export_sha256']) + if (saved.get('status') != 'verified' or details.get('value_readback_status') != 'verified' + or details.get('value_readback_job_id') != row['job_id'] or outcome[0] != 'saved_ok'): + raise ValueError('saved native target Value proof differs') + _, path, _ = _paths(root,row) + write_record(path,dict(schema=3,binding=binding,details=details)) + return details details, binding = _validated(root, row, outcome, project_commit=project_commit) _, saved, _ = _paths(root, row) write_record(saved, dict(schema=2, binding=binding, details=details)) @@ -152,10 +164,26 @@ def capture_value_readback(root, row, outcome, *, project_commit=None): return {'value_readback_status': 'rejected', 'value_readback_reason': str(error)} +def _load_saved_netlist_value(binding,row,outcome): + if (binding['command'] != dict(row) or binding['terminal'] != [row['job_id'],*outcome] + or _digest(_read(internal_path(binding['verification_path']))) != binding['verification_sha256'] + or _digest(_read(internal_path(binding['export_path']))) != binding['export_sha256']): + raise ValueError('saved native Value evidence binding changed') + verified = json.loads(_read(internal_path(binding['verification_path']))) + if (verified['status'] != 'verified' or verified['export_path'] != binding['export_path'] + or verified['export_sha256'] != binding['export_sha256']): + raise ValueError('saved native target verification is incomplete') + return verified['jobs'][row['job_id']] + + def load_value_readback(root, row, outcome): try: _, saved, _ = _paths(root, row) persisted = json.loads(_read(saved)) + if persisted.get('schema') == 3: + details = _load_saved_netlist_value(persisted['binding'],row,outcome) + if details != persisted['details']:raise ValueError('persisted native Value observation changed') + return details details, binding = _validated(root, row, outcome, project_commit=persisted.get('binding',{}).get('project_commit')) if persisted != dict(schema=2, binding=binding, details=details): diff --git a/tests/v1_1/test_native_cli_netlist.py b/tests/v1_1/test_native_cli_netlist.py index 43a812b..a237597 100644 --- a/tests/v1_1/test_native_cli_netlist.py +++ b/tests/v1_1/test_native_cli_netlist.py @@ -254,6 +254,20 @@ def test_hierarchy_has_no_arbitrary_depth_limit(tmp_path): native_netlist._check_hierarchy_graph(path, {'components': {identity: {}}}, 'b0') +def test_root_port_name_with_slash_is_not_a_hierarchy_instance(tmp_path): + from dx_productivity.trial_task_center import native_netlist + effective = tmp_path / 'effective.txt' + effective.write_text(ascii_report() + ' Symbol LED2/RXDLY\tref des \tpage \n' + '\tPath \n\tSymbol name out.1 type \n') + components, nets = native_netlist._parse_ascii(effective) + hierarchy = tmp_path / 'hier.txt' + hierarchy.write_text(ascii_report().split('Config ')[0].replace('FLAT BLOCKS', 'HIER BLOCKS') + + 'Block board \tRoot\n Symbol $1I1\tpage 1\n\tProp Ref Designator R1\n' + + ' Symbol LED2/RXDLY\tpage 1\n\tSymbol name out.1 type \n') + native_netlist._check_hierarchy_graph(hierarchy, {'components': components, 'nets': nets}, 'board') + assert components['LED2/RXDLY']['source_page'] == '1' + + def test_duplicate_nonidentity_attributes_are_preserved_and_require_declared_resolution(tmp_path): from dx_productivity.trial_task_center import native_netlist graph(tmp_path) diff --git a/tests/v1_1/test_native_selected_capture.py b/tests/v1_1/test_native_selected_capture.py index 8c0e153..7145850 100644 --- a/tests/v1_1/test_native_selected_capture.py +++ b/tests/v1_1/test_native_selected_capture.py @@ -1,4 +1,5 @@ -"""Full selected C/A frames share a correlated read with untouched baselines.""" +"""Selected writer snapshots and legacy correlated native capture frames.""" +import re import subprocess import pytest @@ -61,7 +62,7 @@ End If ''') -def test_generated_capture_uses_original_selected_snapshot_and_untouched_reader(tmp_path): +def test_legacy_generated_capture_uses_original_selected_snapshot_and_untouched_reader(tmp_path): source=tmp_path/'source.vbs' source.write_text(reader.MAIN.read_text(encoding='ascii')+'\n'+reader.ADAPTER.read_text(encoding='ascii'),encoding='ascii') generated=tmp_path/'generated.vbs';result=tmp_path/'capture.tsv' @@ -87,43 +88,62 @@ QPWriteUtf8 ''' + reader.quote(generated) + ''',Text assert reader.PAIR in text and text.endswith('END\tnonce\t2\r\n') -@pytest.mark.parametrize('changed', ['', 'part', 'value', 'refdes']) -def test_capture_consumes_native_targets_without_external_pin_read_and_rechecks_scope(tmp_path, changed): - state = STATE.replace('\tOLD\t', '\tSAME\t') + 'A\tu1\tPart Number\tOLD\t\t0\t0\t1\t2\t3\t0\t1\r\n' - if changed == 'part': - state = state.replace('Part Number\tOLD', 'Part Number\tOTHER') - elif changed == 'value': - state = state.replace('Value\tSAME', 'Value\tCHANGED') - elif changed == 'refdes': - state = state.replace('C\tu1\tR1', 'C\tu1\tR9') - (tmp_path/'native-target.tsv').write_bytes(state.encode('ascii')) +@pytest.mark.parametrize('changed', ['', 'part', 'value', 'refdes', 'missing']) +def test_capture_reads_selected_com_attributes_without_native_or_fullpage_validation(tmp_path, changed): fake=reader.NATIVE_FAKES.replace('Dim App,Comp', 'Dim App,Comp,Attr').replace( 'App.ActiveView.Components.Add Comp,True', 'Set Attr=New FullAttribute:Comp.Attributes.Add Attr,True\n' ' Set Attr=New FullAttribute:Attr.Name="Part Number":Attr.Value="OLD":Attr.InstanceValue="OLD":Comp.Attributes.Add Attr,True\n' ' App.ActiveView.Components.Add Comp,True',1) - def replace_native(code): - import re - code=re.sub(r'(?ms)^Function QPUseNativeSnapshot\([^\n]*\n.*?^End Function', - 'Function QPUseNativeSnapshot()\n QPUseNativeSnapshot=True\nEnd Function',code) - return re.sub(r'(?ms)^Function QPNativeCapture\([^\n]*\n.*?^End Function', '''Function QPNativeCapture(ByRef Selected) -Dim Result,Targets -Set Result=CreateObject("Scripting.Dictionary"):Set Targets=CreateObject("Scripting.Dictionary") -Targets.Add "u1",QPReadUtf8(QP_Fso.BuildPath(QP_Root,"native-target.tsv")) -Result.Add "total",2:Result.Add "text","":Result.Add "selected",Targets -Set QPNativeCapture=Result -End Function''',code) + fake=fake.replace('Comp.UID="u2": Comp.Refdes="R2"', + 'Comp.UID="u2": Comp.Refdes="R2":Comp.RaiseOnFind=True') + fake=fake.replace(' If Kind=128 Then Set Query=Components Else Set Query=Pins', + ' If Kind<>128 Then Err.Raise 59000,"Forbidden","pin query"\n Set Query=Components') + if changed == 'part': + fake=fake.replace('Attr.Value="OLD":Attr.InstanceValue="OLD"', + 'Attr.Value="OTHER":Attr.InstanceValue="OTHER"') + elif changed == 'value': + fake=fake.replace('Set Attr=New FullAttribute:Comp.Attributes.Add Attr,True', + 'Set Attr=New FullAttribute:Attr.Value="CHANGED":Attr.InstanceValue="CHANGED":Comp.Attributes.Add Attr,True') + elif changed == 'refdes': + fake=fake.replace('Comp.UID="u1": Comp.Refdes="R1"','Comp.UID="u1": Comp.Refdes="R9"') + elif changed == 'missing': + fake=fake.replace('App.ActiveView.Components.Add Comp,True','',1) + + def forbid_validation(code): + for name in ('QPUseNativeSnapshot', 'QPNativeCapture', 'QPNativeReadUntouched', + 'QPCurrentSemanticState', 'QPVerifyUntouched', 'QPUntouchedComponent', 'QPComponentPins'): + pattern=rf'(?m)^(Function|Sub) {name}\([^\n]*\n[\s\S]*?^End \1' + def forbidden(match): + return match[0].split('\n',1)[0] + '\n Err.Raise 59000,"Forbidden","' + name + '"\nEnd ' + match[1] + code,count=re.subn(pattern,forbidden,code) + assert count==1,name + return code + output=reader.run_composed_fixture(tmp_path, ''' -Dim Command,Failure +Dim Command,Failure,FailureSource Set Command=CreateObject("Scripting.Dictionary") Command.Add "project_path","c:\\board.prj":Command.Add "old_part_number","OLD":Command.Add "new_part_number","NEW" Command.Add "job_id","job":Command.Add "value_mode","preserve":Command.Add "custom_value","":Command.Add "sync_nc","1" Command.Add "target_scope","targets":Command.Add "target_selectors",QPEncode("u1" & Chr(31) & "R1" & Chr(31) & "SAME") On Error Resume Next QPCaptureAndSelect Command,QP_Fso.BuildPath(QP_Root,"snapshot.tsv") -Failure=Err.Number +Failure=Err.Number:FailureSource=Err.Source +Err.Clear On Error GoTo 0 WScript.Echo CStr(Failure<>0) WScript.Echo CStr(QP_Fso.FileExists(QP_Fso.BuildPath(QP_Root,"snapshot.tsv"))) -''',native_app=fake,routines_transform=replace_native) - assert output==(['True','False'] if changed else ['False','True']) +WScript.Echo CStr(FailureSource<>"Forbidden") +If Failure<>0 Then WScript.Echo FailureSource +''',native_app=fake,routines_transform=forbid_validation) + if changed: + assert output==['True','False','True','QuickPartReplace.Target'] + return + assert output==['False','True','True'] + rows=[line.split('\t') for line in (tmp_path/'snapshot.tsv').read_text(encoding='utf-8-sig').splitlines() if line] + assert [row for row in rows if row[0]=='X']==[['X','saved_netlist_v1']] + assert [row for row in rows if row[0]=='C']==[['C','u1','R1','0','0','0','1','NETLIST']] + assert not any(row[0] in {'U','G'} for row in rows) + attributes=[row for row in rows if row[0]=='A'] + assert {row[1] for row in attributes}=={'u1'} + assert {row[2]:row[3:5] for row in attributes}=={'Part Number':['OLD','OLD'],'Value':['SAME','SAME']} diff --git a/tests/v1_1/test_project_commit_runtime_checkpoint.py b/tests/v1_1/test_project_commit_runtime_checkpoint.py index c55945e..31d9e62 100644 --- a/tests/v1_1/test_project_commit_runtime_checkpoint.py +++ b/tests/v1_1/test_project_commit_runtime_checkpoint.py @@ -35,3 +35,63 @@ def test_native_closed_checkpoint_binds_project_marker_and_saved_source(tmp_path assert validate_project_commit_source(proof, root) marker.write_text('changed') assert not validate_project_commit_source(proof, root) + + +@pytest.mark.parametrize('damage', [None, 'foreign_attempt', 'missing_native', 'bad_manifest', 'missing_expectations', 'old_snapshot']) +def test_saved_native_checkpoint_only_authorizes_export_validation(tmp_path, monkeypatch, damage): + from test_batch_runtime import command_for, worker_runtime + from dx_productivity.trial_task_center.worker_monitor import WorkerMonitorError + command, project = command_for(tmp_path) + root = Path(command[3]) + token = 'a' * 32 + (root / 'project-session.request').write_text(f'{token}\t{project}\tjob') + marker = root / ('project-commit-' + token + '.tsv') + def monitor(*args, **kwargs): + marker.write_text(f'{token}\t{project}\tproject_saved\njob\t' + ('saved_ok' if damage == 'bad_manifest' else 'pending_save') + '\n') + (root / 'snapshot-job.tsv').write_text('M\ttarget snapshot\n' + ('' if damage == 'old_snapshot' else 'X\tsaved_netlist_v1\n')) + if damage != 'missing_expectations': + (root / 'writer-expectations-job.tsv').write_text('bound target writer expectations') + if damage != 'missing_native': + expected = dict(runtime._current_attempts[0][1]) + from dx_productivity.trial_task_center import batch_attempt + batch_attempt._publish(runtime._current_attempts[0][0], dict(expected, state='mutation_possible')) + if damage == 'foreign_attempt': expected['attempt_id'] = 'f' * 32 + (root / 'snapshot-job.tsv.native.json').write_text(json.dumps({ + 'ok': True, 'stage': 'native_replace_applied', 'batch_attempt': expected})) + return subprocess.CompletedProcess(command, 0, '', '') + runtime = worker_runtime(tmp_path, monkeypatch, monitor) + monkeypatch.setattr(runtime, '_retain_uncertain', lambda *args: None) + with runtime: + if damage: + with pytest.raises((WorkerMonitorError, OSError)): + runtime.run_worker(command, 5) + return + runtime.run_worker(command, 5) + proof = json.loads((root / 'project-checkpoint.json').read_text(encoding='utf-8'))['project_commit_source'] + assert proof['marker_state'] == 'project_saved' and proof['saved_only'] is True + assert proof['validation_required'] == 'saved_netlist_v1' + assert proof['outcomes'] == {'job': 'pending_save'} + assert proof['native_outcomes'] == {'job': 'pending_save'} + assert set(proof['readback_files']) == {'snapshot-job.tsv', 'snapshot-job.tsv.native.json', 'writer-expectations-job.tsv'} + assert not list(root.glob('post-state-*')) and not list(root.glob('value-readback-*')) + assert validate_project_commit_source(proof, root) + project.write_text('unexplained change after saved closure') + assert not validate_project_commit_source(proof, root) + + +def test_saved_native_no_match_checkpoint_requires_unmutated_attempt(tmp_path, monkeypatch): + from test_batch_runtime import command_for, worker_runtime + command, project = command_for(tmp_path) + root = Path(command[3]) + token = 'a' * 32 + (root / 'project-session.request').write_text(f'{token}\t{project}\tjob') + def monitor(*args, **kwargs): + (root / ('project-commit-' + token + '.tsv')).write_text(f'{token}\t{project}\tproject_saved\njob\tno_match\n') + return subprocess.CompletedProcess(command, 0, '', '') + runtime = worker_runtime(tmp_path, monkeypatch, monitor) + with runtime: + runtime.run_worker(command, 5) + proof = json.loads((root / 'project-checkpoint.json').read_text(encoding='utf-8'))['project_commit_source'] + assert proof['saved_only'] is True and proof['outcomes'] == {'job': 'no_match'} + assert proof['validation_required'] == 'saved_netlist_v1' and proof['readback_files'] == {} + assert validate_project_commit_source(proof, root) diff --git a/tests/v1_1/test_refdes_identity_closure.py b/tests/v1_1/test_refdes_identity_closure.py index 1f0cd2b..abf2a5e 100644 --- a/tests/v1_1/test_refdes_identity_closure.py +++ b/tests/v1_1/test_refdes_identity_closure.py @@ -377,11 +377,12 @@ def test_multiunit_value_evidence_covers_physical_selector_without_dropping_unit def test_real_vbs_capture_records_all_units_of_one_physical_selector(tmp_path): import test_accuracy_vbs_guards as guards - names=guards.UNTOUCHED_ROUTINES+['QPCaptureAndSelect','QPSnapshotComponent','QPCommandTargets', + names=['QPCaptureAndSelect','QPSnapshotComponent','QPCommandTargets','QPReadSnapshot','QPReadUtf8','QPWriteUtf8', + 'QPSnapshotAttribute','QPSortSnapshotLines','QPOptionalAttributeField','QPFindCurrentAttribute','QPInvalidatePinIndex', 'QPBooleanText','QPLogField','QPTargetCell','QPRequireUniqueAttributeNames','QPAttributeObservations'] path=tmp_path/'units.tsv' output=guards.run_vbs(tmp_path,names,''' -Dim A,B,Attr,Pin,Command,Records,Comp +Dim A,B,Attr,Command,Records,Comp Set QP_App=New FakeApp Set A=New FullComponent:A.UID="u1":A.Refdes="U1":A.X=0 Set B=New FullComponent:B.UID="u2":B.Refdes="U1":B.X=100 @@ -391,8 +392,6 @@ For Each Comp In Array(A,B) Set Attr=New FullAttribute:Attr.Name="Value":Attr.Value="1K":Attr.InstanceValue="1K" Comp.Attributes.Add Attr,True QP_App.ActiveView.Components.Add Comp,True - Set Pin=New FakePin:Set Pin.Component=Comp:Pin.Number="1":Pin.X=Comp.X:Pin.Y=0 - Set Pin.Connection=Nothing:QP_App.ActiveView.Pins.Add Pin,True Next Set Command=CreateObject("Scripting.Dictionary") Command.Add "job_id","test":Command.Add "old_part_number","OLD":Command.Add "new_part_number","NEW" @@ -403,9 +402,21 @@ Set Records=QPReadSnapshot("'''+str(path)+'''") WScript.Echo Records("components").Count WScript.Echo CapturedState ''',prelude=guards.LOG_STUB+guards.FULL_FAKE+''' -Dim CapturedState +Dim CapturedState,QP_SavedNetlistMode Sub QPBuildComponentIndex(ByRef Components) End Sub +Function QPComponentPins(ByVal Uid) + Err.Raise 59001,"Forbidden","pin query" +End Function +Function QPUseNativeSnapshot() + Err.Raise 59002,"Forbidden","native CAD read" +End Function +Function QPCurrentSemanticState() + Err.Raise 59003,"Forbidden","whole page" +End Function +Sub QPVerifyUntouched(ByRef Records) + Err.Raise 59004,"Forbidden","unselected validation" +End Sub Function QPValueMode(ByRef Command) QPValueMode="preserve" End Function @@ -420,6 +431,14 @@ Sub QPWriteStatus(ByVal Root,ByVal Job,ByVal State,ByVal Code,ByVal Message) End Sub ''') assert output.splitlines()==['2','awaiting_native_replace'] + rows=[line.split('\t') for line in path.read_text(encoding='utf-8-sig').splitlines() if line] + assert [row for row in rows if row[0]=='X']==[['X','saved_netlist_v1']] + assert [row for row in rows if row[0]=='C']==[ + ['C','u1','U1','0','0','0','1','NETLIST'], + ['C','u2','U1','100','0','0','1','NETLIST']] + assert {(row[1],row[2],row[3],row[4]) for row in rows if row[0]=='A'}=={ + (uid,name,value,value) for uid in ('u1','u2') for name,value in (('Part Number','OLD'),('Value','1K'))} + assert not any(row[0] in {'U','G'} for row in rows) def test_fresh_vbs_recovery_restores_interleaved_unselected_unit_aliases(tmp_path): diff --git a/tests/v1_1/test_resource_isolation_prewrite_pause.py b/tests/v1_1/test_resource_isolation_prewrite_pause.py index 86a13ea..16f5067 100644 --- a/tests/v1_1/test_resource_isolation_prewrite_pause.py +++ b/tests/v1_1/test_resource_isolation_prewrite_pause.py @@ -11,8 +11,9 @@ from dx_productivity.trial_task_center.stop_control import StopControl from dx_productivity.trial_task_center.worker_monitor import WorkerMonitorError +@pytest.mark.parametrize('saved_native', [False, True]) @pytest.mark.parametrize('damage', [None, 'current_mutated', 'marker_missing', 'uncovered_prefix', 'source_unexplained', 'checkpoint']) -def test_prewrite_pause_certifies_only_current_job_and_hash_binds_committed_prefix(tmp_path, monkeypatch, damage): +def test_prewrite_pause_certifies_only_current_job_and_hash_binds_committed_prefix(tmp_path, monkeypatch, damage, saved_native): from test_batch_runtime import command_for, worker_runtime, Cad command, project = command_for(tmp_path) root = Path(command[3]) @@ -34,9 +35,16 @@ def test_prewrite_pause_certifies_only_current_job_and_hash_binds_committed_pref (root / ('project-pause-' + 'a'*32 + '.tsv')).write_text(f'{"a"*32}\t{project}\tnext\tprewrite_closed') if damage != 'source_unexplained': (root / ('project-commit-' + 'a'*32 + '.tsv')).write_text( - f'{"a"*32}\t{project}\tproject_verified\n' + ('foreign' if damage == 'uncovered_prefix' else 'job') + '\tsaved_ok\n') - for name in ('post-state-job.tsv', 'snapshot-job.tsv', 'snapshot-job.tsv.native.json', 'value-readback-job.tsv'): - (root / name).write_text('bound native prefix evidence') + f'{"a"*32}\t{project}\t' + ('project_saved' if saved_native else 'project_verified') + '\n' + + ('foreign' if damage == 'uncovered_prefix' else 'job') + ('\tpending_save\n' if saved_native else '\tsaved_ok\n')) + if saved_native: + (root / 'snapshot-job.tsv').write_text('M\ttarget snapshot\nX\tsaved_netlist_v1\n') + (root / 'writer-expectations-job.tsv').write_text('bound target writer expectations') + (root / 'snapshot-job.tsv.native.json').write_text(__import__('json').dumps({ + 'ok': True, 'stage': 'native_replace_applied', 'batch_attempt': paths['job'][1]})) + else: + for name in ('post-state-job.tsv', 'snapshot-job.tsv', 'snapshot-job.tsv.native.json', 'value-readback-job.tsv'): + (root / name).write_text('bound native prefix evidence') if damage == 'checkpoint': runtime.cad.checkpoint = lambda *args: (_ for _ in ()).throw(WorkerMonitorError('project still open')) result = subprocess.CompletedProcess(command, 75, '', '') @@ -57,7 +65,9 @@ def test_prewrite_pause_certifies_only_current_job_and_hash_binds_committed_pref assert proof['phase'] == 'before_native_dispatch' and proof['job_id'] == 'next' assert len(proof['batch_attempts']) == 1 assert proof['batch_attempts'][0]['expected']['job_id'] == 'next' - assert proof['committed_prefix'] == {'job': 'saved_ok'} + assert proof['committed_prefix'] == {'job': 'pending_save' if saved_native else 'saved_ok'} + if saved_native: + assert proof['prefix_marker_state'] == 'project_saved' and proof['prefix_validation_required'] is True assert proof['native_dispatch_not_started'] and proof['project_closed'] assert proof['files'] diff --git a/tests/v1_1/test_saved_netlist_consumers.py b/tests/v1_1/test_saved_netlist_consumers.py new file mode 100644 index 0000000..74d60b0 --- /dev/null +++ b/tests/v1_1/test_saved_netlist_consumers.py @@ -0,0 +1,80 @@ +import hashlib +import json +from pathlib import Path +from threading import Event +from types import ModuleType, SimpleNamespace + +import pytest +from test_execution_proof import proof_case + +from dx_productivity.trial_task_center.native_helper import read_snapshot, transaction_binding +from dx_productivity.trial_task_center.target_plan import ComponentTarget, TargetPlanRow + + +@pytest.mark.parametrize('actual,present', [('33R', True), ('', None)]) +def test_applied_writer_receipt_uses_saved_native_proof_instead_of_cad_readback(proof_case, actual, present): + from dx_productivity.trial_task_center.netlist_verification import library_from_receipt + _, root, command = proof_case + snapshot = root / 'snapshot-job.tsv' + text = snapshot.read_text(encoding='utf-8').replace('\tpins\n', '\tNETLIST\n') + snapshot.write_text(text + 'X\tsaved_netlist_v1\n', encoding='utf-8') + metadata, records = read_snapshot(snapshot) + report_path = Path(str(snapshot) + '.native.json') + report = json.loads(report_path.read_text(encoding='utf-8')) + report.update(stage='native_replace_applied', transaction=transaction_binding( + snapshot, metadata, records, ['lib', 'NEW', 'sym', '', 'name', 'label'], 'sym')) + report_path.write_text(json.dumps(report), encoding='utf-8') + proof = {'files': [{'path': str(p), 'sha256': hashlib.sha256(p.read_bytes()).hexdigest()} + for p in (snapshot, report_path)], + 'saved_netlist': {'status': 'verified'}} + receipt = {'native_state': 'saved_ok', 'job_id': 'job', 'proof': proof} + proof['value_readback'] = dict(value_readback_status='verified', value_readback_job_id='job', + project_path=command['project_path'], schematic_name=command['schematic_name'], sheet_number=command['sheet_number'], + value_readback=[dict(uid='uid', actual_part_number='NEW', actual_value=actual, actual_value_present=present, + value_presence_coverage='native_ascii_empty_presence_unknown')]) + assert library_from_receipt(command, receipt)['uid']['attributes']['Part Number'] == 'NEW' + assert library_from_receipt(command, receipt)['uid']['preserved_value_present'] is present + proof.pop('saved_netlist') + with pytest.raises(ValueError): + library_from_receipt(command, receipt) + report['stage'] = 'native_replace_verified' + report_path.write_text(json.dumps(report), encoding='utf-8') + proof['files'][1]['sha256'] = hashlib.sha256(report_path.read_bytes()).hexdigest() + with pytest.raises(ValueError): + library_from_receipt(command, receipt) + + +def test_independent_comparison_reuses_verified_saved_export(tmp_path, monkeypatch): + import sys + from dx_productivity.trial_task_center import native_netlist + from dx_productivity.trial_task_center.netlist_verification import NetlistVerification + project = tmp_path / 'board.prj' + project.write_text('project', encoding='utf-8') + row = TargetPlanRow(ComponentTarget(project, 'MAIN', '1', 'u', 'R1', 'OLD', '33R'), True, 'NEW') + child = SimpleNamespace(target_plan=lambda _: (row,), projects=lambda _: (SimpleNamespace(path=project),), + get_task=lambda _: SimpleNamespace(copy_part_number_to_value=False), + _quick_run_preparer=SimpleNamespace(data_root=tmp_path / 'data/tasks/task')) + captures = [] + def capture(source, destination): + captures.append(source) + destination.mkdir(parents=True) + return {'project': str(source), 'root': str(destination)} + def graph(part): + return {'components': {'u': {'refdes': 'R1', 'attributes': {'Part Number': part, 'Value': '33R'}}}, + 'nets': [{'name': 'N', 'endpoints': [['u', '1']]}]} + before = {'status': 'success', 'complete': True, 'graph': graph('OLD'), 'outputs': {}} + after = {'status': 'success', 'complete': True, 'graph': graph('NEW'), 'outputs': {}} + saved = {'status': 'verified', 'capture': {'project': str(project), 'root': str(tmp_path / 'saved')}, + 'result': after, 'export_path': str(tmp_path / 'saved-export/netlist.json')} + # The saved-source verifier is a separately exercised native I/O boundary. + module = ModuleType('dx_productivity.trial_task_center.saved_netlist_verification') + module.load_saved_export = lambda root, path: saved + monkeypatch.setitem(sys.modules, module.__name__, module) + monkeypatch.setattr(native_netlist, 'capture_project', capture) + monkeypatch.setattr(native_netlist, 'export_netlist', lambda *a, **kw: before) + with NetlistVerification(tmp_path / 'data', 'run', Event()) as checks: + checks.before_task(child, 'task') + checks.after_task('task', execution_summary={'saved_items': 1}) + result = checks.finish()['task'] + assert len(captures) == 1, 'already verified after-export must not be captured/exported again' + assert result['verified'] is True diff --git a/tests/v1_1/test_saved_netlist_journal.py b/tests/v1_1/test_saved_netlist_journal.py new file mode 100644 index 0000000..e037df5 --- /dev/null +++ b/tests/v1_1/test_saved_netlist_journal.py @@ -0,0 +1,78 @@ +import hashlib +import json + +import pytest +from test_project_commit_journal import staged_case + +from dx_productivity.trial_task_center.errors import TaskCenterError + + +def test_saved_proof_promotion_is_compare_and_swap_and_keeps_source_binding(staged_case, tmp_path): + store, journal, task, rows, proof = staged_case + token = 'a' * 32 + attempt = journal.claim(task, rows[0]) + journal.stage_project_result(attempt, rows[0], session_token=token, root=tmp_path, proof=proof) + source = dict(proof, session_token=token, project_path=rows[0]['project_path'], jobs=['job1'], + marker_state='project_saved', saved_only=True, validation_required='saved_netlist_v1', + native_outcomes={'job1': 'pending_save'}, outcomes={'job1': 'pending_save'}) + journal.bind_project_commit_proof(task, token, source) + verified = dict(source, outcomes={'job1': 'saved_ok'}, saved_netlist={'status': 'verified'}) + with pytest.raises(TaskCenterError): + journal.promote_project_commit_proof(task, token, dict(source, jobs=[]), verified) + with pytest.raises(TaskCenterError): + journal.promote_project_commit_proof(task, token, source, dict(verified, project_path='other.prj')) + journal.promote_project_commit_proof(task, token, source, verified) + journal.promote_project_commit_proof(task, token, source, verified) + stored, = journal.pending_project_commits(task) + assert json.loads(stored['proof_json']) == verified + + +def test_saved_project_requires_native_export_before_committing_receipts(staged_case, tmp_path): + store, journal, task, rows, old_proof = staged_case + proof = {'files': old_proof['files']} + for row in rows: + journal.stage_project_result(journal.claim(task, row), row, + session_token='a' * 32, root=tmp_path, proof=proof) + jobs = [row['job_id'] for row in rows] + commit = dict(proof, session_token='a' * 32, project_path=rows[0]['project_path'], jobs=jobs, + marker_state='project_saved', saved_only=True, validation_required='saved_netlist_v1', + native_outcomes={job: 'pending_save' for job in jobs}, + outcomes={job: 'saved_ok' for job in jobs}) + with pytest.raises(TaskCenterError): + journal.commit_project_results(task, 'a' * 32, dict.fromkeys(jobs, proof), commit) + assert [r[0] for r in store._connection.execute('SELECT state FROM execution_operations')] == ['pending_save'] * 2 + + +def test_native_baseline_and_commit_references_do_not_duplicate_all_job_payloads(staged_case, tmp_path): + store, journal, task, rows, old_proof = staged_case + proof = {'files': old_proof['files']} + attempts = {} + for row in rows: + attempt = journal.claim(task, row) + attempts[row['job_id']] = [attempt.operation_key, attempt.attempt_id, attempt.generation] + journal.stage_project_result(attempt, row, session_token='a' * 32, root=tmp_path, proof=proof) + jobs = list(attempts) + exported = tmp_path / 'netlist.json' + exported.write_text('{"export":"saved native data"}', encoding='utf-8') + digest = hashlib.sha256(exported.read_bytes()).hexdigest() + saved = {'status': 'verified', 'export_path': str(exported), 'export_sha256': digest, + 'files': [{'path': str(exported), 'sha256': digest}], + 'jobs': {job: {'value_readback_status': 'verified'} for job in jobs}} + other_input = tmp_path / 'other-job-input.tsv' + other_input.write_text('another target snapshot', encoding='utf-8') + saved['files'].append({'path': str(other_input), 'sha256': hashlib.sha256(other_input.read_bytes()).hexdigest()}) + commit = dict(proof, session_token='a' * 32, project_path=rows[0]['project_path'], jobs=jobs, + marker_state='project_saved', saved_only=True, validation_required='saved_netlist_v1', + native_outcomes={job: 'pending_save' for job in jobs}, outcomes={job: 'saved_ok' for job in jobs}, + saved_netlist=saved, operation_attempts=attempts) + journal.commit_project_results(task, 'a' * 32, dict.fromkeys(jobs, proof), commit) + records = store._connection.execute('SELECT receipt_json FROM execution_operations').fetchall() + for record, job in zip(records, jobs): + bound = json.loads(record[0])['proof']['project_commit'] + assert 'jobs' not in bound.get('saved_netlist', {}), 'per-job receipts must not repeat every target' + assert set(bound['operation_attempts']) == {job} + assert str(other_input) not in {item['path'] for item in json.loads(record[0])['proof']['files']} + baseline, = journal.expected_baselines(task, rows[0]['project_path']) + assert baseline['validation_mode'] == 'saved_netlist_v1' + assert baseline['state'] == 'N\tsaved_netlist_v1\t' + digest + assert journal.project_commit_attempts(task, 'a' * 32) == attempts diff --git a/tests/v1_1/test_saved_netlist_verification.py b/tests/v1_1/test_saved_netlist_verification.py new file mode 100644 index 0000000..ef7f49e --- /dev/null +++ b/tests/v1_1/test_saved_netlist_verification.py @@ -0,0 +1,405 @@ +import json +from pathlib import Path + +import pytest + +from dx_productivity.trial_task_center.errors import TaskCenterError +from dx_productivity.trial_task_center.execution_proof import capture_project_commit +from dx_productivity.trial_task_center.quick_run import QuickRunPreparer, _encode_vbs_field as enc, _run_process, _write_uncertain_flag +from dx_productivity.trial_task_center.native_helper import read_snapshot, transaction_binding +from dx_productivity.trial_task_center.logging_setup import configure_logging +from dx_productivity.trial_task_center.history_store import HistoryRepository +from dx_productivity.trial_task_center.models import TaskStatus +from dx_productivity.trial_task_center.service import TaskCenterService +from dx_productivity.trial_task_center.store import TaskStore + + +def test_saved_marker_is_pending_until_native_netlist_verifies(tmp_path): + root = tmp_path / 'quick-run'; root.mkdir() + project = tmp_path / 'board.prj'; project.write_text('saved') + token = 'a' * 32 + (root / f'project-commit-{token}.tsv').write_text( + f'{token}\t{project}\tproject_saved\njob\tpending_save\n') + proof = capture_project_commit(tmp_path, root, dict(session_token=token, + project_path=str(project.resolve()).casefold(), jobs_json=json.dumps(['job']))) + assert proof['validation_required'] == 'saved_netlist_v1' + assert proof['marker_state'] == 'project_saved' + assert proof['outcomes'] == {'job': 'pending_save'} + assert 'saved_netlist' not in proof + + +@pytest.fixture +def saved_case(tmp_path, monkeypatch, request): + from dx_productivity.trial_task_center import native_netlist + from test_native_cli_netlist import project_fixture, ascii_report + monkeypatch.setattr('dx_productivity.trial_task_center.scanner._is_schematic_project', lambda _: True) + project = project_fixture(tmp_path) + project.write_text(project.read_text().replace('"board"', '"MAIN"')) + data = tmp_path / 'data' + preparer = QuickRunPreparer(data, process_runner=_run_process, + cscript_resolver=lambda: Path('cscript.exe'), sheet_discoverer=lambda _: (('MAIN', '1'),)) + store = TaskStore(tmp_path / 'tasks.db') + service = TaskCenterService(store, configure_logging(data), quick_run_preparer=preparer) + task = service.create_task('saved native netlist') + service.scan_projects(task.task_id, project.parent) + for selected in service.projects(task.task_id):service.set_project_selected(selected.project_id, True) + service.add_rule(task.task_id, 'OLD1', 'NEW1',target_cell='CELL'); service.add_rule(task.task_id, 'OLD2', 'NEW2',target_cell='CELL') + handoff = preparer.prepare(task.task_id, service.projects(task.task_id), service.rules(task.task_id), + sheet_targets={str(project.resolve()).casefold(): (('MAIN', '1'),)}) + rows = list(preparer._bind_journal_handoff(task.task_id, handoff).values()) + session = preparer.begin_batch_session(task.task_id,service.projects(task.task_id),service.rules(task.task_id)) + root = data / 'quick-run'; token = 'a'*32 + for index, row in enumerate(rows, 1): + job, uid, ref = row['job_id'], f'$1I{index}', f'R{index}' + path = root / f'snapshot-{job}.tsv' + path.write_text('\t'.join(map(enc, ['M', str(project), row['old_part'], row['new_part'], 'MAIN:1', 'preserve', '', '1'])) + '\n' + + f'L\tCELL\nX\tsaved_netlist_v1\nC\t{uid}\t{ref}\t0\t0\t0\t1\tNETLIST\nA\t{uid}\tValue\tOLD_VALUE\tOLD_VALUE\t0\t0\t0\t0\t1\t0\t1\n') + metadata, components = read_snapshot(path) + report = dict(ok=True, stage='native_replace_applied', transaction=transaction_binding(path, metadata, components, + ['lib', row['new_part'], 'symbol', '', 'NAME'+str(index), 'LABEL'+str(index)], 'symbol'), + batch_attempt=dict(task_id=task.task_id,job_id=job,project_path=str(project),session_id='b'*32,attempt_id='c'*32,generation=1)) + Path(str(path)+'.native.json').write_text(json.dumps(report)) + expectation = [['W','1',task.task_id,job,str(project),'MAIN','1',path.read_bytes().decode()], + ['C',uid,ref,'10K','1','NAME'+str(index),'LABEL'+str(index),row['new_part'],'CELL']] + (root / f'writer-expectations-{job}.tsv').write_text('\n'.join('\t'.join(map(enc, line)) for line in expectation)+'\n') + if getattr(request,'param',None) != 'execute': + attempt = preparer.journal.claim(task.task_id, row) + staged = preparer.result_proof(root, row, ('pending_save','session_staged','applied')) + preparer.journal.stage_project_result(attempt,row,session_token=token,root=root,proof=staged) + (root / f'project-commit-{token}.tsv').write_text(f'{token}\t{project}\tproject_saved\n'+ + ''.join(row['job_id']+'\tpending_save\n' for row in rows)) + installation = tmp_path / 'installation' + for name in ('iCDB/win32/bin/icdb2ascii.exe','wv/win32/bin/KeyinNetlist.exe'): + executable = installation / name; executable.parent.mkdir(parents=True,exist_ok=True); executable.touch() + monkeypatch.setattr(native_netlist,'installation_root',lambda:installation) + control = {'calls':[], 'damage':None, 'session':session} + class Scope: + cleanup_record = {'workers_closed':True} + def __enter__(self):return self + def __exit__(self,*args):pass + def start_process(self,command,*,cwd,**kwargs): + control['calls'].append(command) + parts = [] + for index in (1,2): + part = 'WRONG' if control['damage']=='part' and index==2 else 'NEW'+str(index) + value = 'WRONG' if control['damage']=='value' and index==2 else '10K' + base = ascii_report(part).replace('$1I1',f'$1I{index}').replace('R1',f'R{index}').replace('page \t','page 1\t') + base = base.replace('ref des '+f'R{index}'+'\tpage \n',f'ref des R{index}\tpage 1\n') + symbol = base[base.index(' Symbol '):].replace('Prop Value 10K','Prop Value '+value) + symbol += f'\tProp Part Name NAME{index}\n\tProp Part Label LABEL{index}\n' + symbol += '\tProp Cell Name '+('WRONG' if control['damage']=='cell' and index==2 else 'CELL')+'\n' + parts.append(symbol) + if '-h' in command: + text = ascii_report().split('Config default')[0].replace('FLAT BLOCKS','HIER BLOCKS')+'Block MAIN \tRoot\n' + for index in (1,2): + text += f' Symbol $1I{index}\tpage 1\n\tProp Ref Designator R{index}\n\tProp Part Number NEW{index}\n\tProp Value 10K\n' + if control['damage']=='partial':text += ' Symbol $1I3\tpage 1\n\tProp Part Number MISSING\n' + path = next(arg[6:] for arg in command if arg.startswith('-file=')) + elif '-f' in command: + text = ascii_report().split('Config default')[0]+'Config default\tview none\n\tNet N1\n' + text += ''.join(f'\t\tConn $1I{i} pin A page 1\n\t\tPath root\n' for i in (1,2))+''.join(parts) + path = next(arg[6:] for arg in command if arg.startswith('-file=')) + else: + text = ';; V4.1.0\n%net\n%page=MAIN\n\\N1\\ \\R1\\-\\1\\ \\R2\\-\\1\\\n%Part\n\\NEW1\\ \\R1\\\n\\NEW2\\ \\R2\\\n' + path = next(arg[5:] for arg in command if arg.startswith('-out=')) + Path(path).write_text(text) + if control['damage']=='source':(project.parent/'database/icdb.dat').write_bytes(b'changed during export') + return type('Process',(),{'poll':lambda self:0})() + monkeypatch.setattr(native_netlist,'OwnedCliScope',Scope) + monkeypatch.setattr(TaskCenterService,'_owned_cad_operation',lambda *a,**k:pytest.fail('CAD fallback/replay')) + yield service,store,task.task_id,preparer,project,rows,control + store.close() + + +def test_saved_prefix_exports_once_and_commits_without_cad_readback(saved_case): + service,store,task,preparer,project,rows,control = saved_case + preparer._commit_staged_project(task,bind_source=True) + assert len(control['calls']) == 3 + operations = store._connection.execute('SELECT state,receipt_json FROM execution_operations').fetchall() + assert [row['state'] for row in operations] == ['verified','verified'] + for item in operations: + proof = json.loads(item['receipt_json'])['proof'] + assert proof['saved_netlist']['status']=='verified' + assert proof['value_readback']['value_readback_status']=='verified' + assert proof['baseline']['validation_mode']=='saved_netlist_v1' + assert proof['baseline']['state'].startswith('N\tsaved_netlist_v1\t') + assert not list((preparer.data_root/'quick-run').glob('post-state-*')) + assert not list((preparer.data_root/'quick-run').glob('value-readback-*.tsv')) + preparer.write_expected_baselines(task,preparer.data_root/'quick-run',str(project)) + assert (preparer.data_root/'quick-run'/'expected-baselines.tsv').read_text().splitlines() == [ + 'project_path\tschematic_name\tsheet_number\tsemantic_state'] + from dx_productivity.trial_task_center.saved_netlist_verification import load_saved_export + pointer = preparer.data_root/'quick-run/saved-netlist-export.json' + cached = json.loads(pointer.read_text()) + cached['result']['graph']['components']['$1I1']['attributes']['Value']='MUTABLE_WRONG' + cached['jobs'][rows[0]['job_id']]['value_readback'][0]['actual_value']='MUTABLE_WRONG' + pointer.write_text(json.dumps(cached)) + loaded = load_saved_export(preparer.data_root/'quick-run',project) + assert loaded['result']['graph']['components']['$1I1']['attributes']['Value']=='10K' + assert loaded['jobs'][rows[0]['job_id']]['value_readback'][0]['actual_value']=='10K' + + +@pytest.mark.parametrize('damage',['part','value','cell','partial','source','unavailable','writer_evidence']) +def test_saved_prefix_export_failure_keeps_all_items_pending(saved_case,damage,monkeypatch): + service,store,task,preparer,project,rows,control = saved_case + control['damage']=damage + if damage=='unavailable': + from dx_productivity.trial_task_center import native_netlist + monkeypatch.setattr(native_netlist,'installation_root',lambda:preparer.data_root/'missing-installation') + elif damage=='writer_evidence': + path = preparer.data_root/'quick-run'/f'writer-expectations-{rows[0]["job_id"]}.tsv' + path.write_text(path.read_text().replace('10K','WRONG')) + with pytest.raises((TaskCenterError,ValueError)):preparer._commit_staged_project(task,bind_source=True) + assert all(row[0]=='pending_save' for row in store._connection.execute('SELECT state FROM execution_operations')) + + +def test_saved_export_recovers_real_service_after_history_failure_and_restart(saved_case,monkeypatch): + service,store,task,preparer,project,rows,control = saved_case + original = HistoryRepository.append + monkeypatch.setattr(HistoryRepository,'append',lambda *a,**k:(_ for _ in ()).throw(OSError('history disk full'))) + with pytest.raises(OSError):preparer._commit_staged_project(task,bind_source=True) + monkeypatch.setattr(HistoryRepository,'append',original) + root = preparer.data_root/'quick-run' + _write_uncertain_flag(root/'uncertain.flag','receipt_commit_failed') + store.set_task_status(task,TaskStatus.BLOCKED) + reopened = TaskStore(store.path) + try: + worker = QuickRunPreparer(preparer.data_root,process_runner=_run_process) + resumed = TaskCenterService(reopened,configure_logging(preparer.data_root),quick_run_preparer=worker) + assert resumed.recover_quick_run(task,confirmed=True).progress.saved_items==2 + assert reopened.get_task(task).status is TaskStatus.COMPLETED + assert len(control['calls'])==3 + assert resumed.recover_quick_run(task,confirmed=True).state=='saved_ok' + assert len(control['calls'])==3 + finally:reopened.close() + + +@pytest.mark.parametrize('damage',[None,'source','writer']) +def test_runtime_saved_checkpoint_recovers_before_sql_callback_after_restart(saved_case,damage): + from types import SimpleNamespace + from test_batch_runtime import Desktop + from dx_productivity.trial_task_center.batch_runtime import BatchCadRuntime + from dx_productivity.trial_task_center.batch_attempt import prepare_attempt, _publish + service,store,task,preparer,project,rows,control = saved_case + root = preparer.data_root/'quick-run' + runtime = BatchCadRuntime(preparer.data_root,'execution',desktop_factory=Desktop,session_id='b'*32) + runtime._ensure_desktop() + runtime.cad = SimpleNamespace(checkpoint=lambda _:None) + runtime.record['active_job'] = rows[0]['job_id'] + for row in rows: + path = runtime.path.parent/'attempts'/f'{row["job_id"]}.json' + expected = prepare_attempt(path,session_id='b'*32,generation=1,task_id=task, + job_id=row['job_id'],project_path=str(project),attempt_id='c'*32) + _publish(path,dict(expected,state='mutation_possible')) + runtime._current_attempts.append((path,expected)) + (root/'project-session.request').write_text('a'*32+'\t'+str(project)+'\t'+rows[0]['job_id']) + runtime._checkpoint(root,project,'c'*32) + runtime.desktop.close(); runtime.record['cleanup']=runtime.desktop.cleanup_record + runtime.desktop=runtime.cad=None; runtime._record_release() + assert preparer.journal.project_commit_records(task)[0]['proof_json'] is None + if damage=='source':(project.parent/'database/icdb.dat').write_bytes(b'changed after close') + elif damage=='writer':(root/f'writer-expectations-{rows[0]["job_id"]}.tsv').write_text('changed after close') + _write_uncertain_flag(root/'uncertain.flag','project_commit_unverified') + store.set_task_status(task,TaskStatus.BLOCKED) + reopened = TaskStore(store.path) + try: + worker = QuickRunPreparer(preparer.data_root,process_runner=_run_process) + resumed = TaskCenterService(reopened,configure_logging(preparer.data_root),quick_run_preparer=worker) + if damage: + with pytest.raises(TaskCenterError):resumed.recover_quick_run(task,confirmed=True) + assert (root/'uncertain.flag').is_file() + assert not control['calls'] + else: + assert resumed.recover_quick_run(task,confirmed=True).progress.saved_items==2 + assert reopened.get_task(task).status is TaskStatus.COMPLETED + assert len(control['calls'])==3 + finally:reopened.close() + + +def test_mutable_export_pointer_cannot_override_immutable_native_graph(saved_case): + service,store,task,preparer,project,rows,control = saved_case + control['damage']='value' + with pytest.raises(ValueError):preparer._commit_staged_project(task,bind_source=True) + pointer = preparer.data_root/'quick-run/saved-netlist-export.json' + record = json.loads(pointer.read_text()) + for component in record['result']['graph']['components'].values():component['attributes']['Value']='10K' + pointer.write_text(json.dumps(record)) + with pytest.raises(ValueError):preparer._commit_staged_project(task) + assert all(row[0]=='pending_save' for row in store._connection.execute('SELECT state FROM execution_operations')) + + +def test_saved_prefix_mixed_applied_and_no_match_commits_after_one_export(saved_case): + service,store,task,preparer,project,rows,control = saved_case + root = preparer.data_root/'quick-run'; job = rows[1]['job_id'] + record = store._connection.execute('SELECT operation_key,receipt_json FROM execution_operations ORDER BY rowid DESC LIMIT 1').fetchone() + receipt = json.loads(record['receipt_json']); receipt['proof']={'files':[]}; receipt['code']='session_staged_no_match' + store._connection.execute('UPDATE execution_operations SET receipt_json=? WHERE operation_key=?',(json.dumps(receipt),record['operation_key'])) + for name in (f'snapshot-{job}.tsv',f'snapshot-{job}.tsv.native.json',f'writer-expectations-{job}.tsv'):(root/name).unlink() + marker = root/('project-commit-'+'a'*32+'.tsv') + marker.write_text(marker.read_text().replace(job+'\tpending_save',job+'\tno_match')) + preparer._commit_staged_project(task,bind_source=True) + records = store._connection.execute('SELECT state,receipt_json FROM execution_operations ORDER BY rowid').fetchall() + assert [row['state'] for row in records]==['verified','no_match'] + assert json.loads(records[1]['receipt_json'])['proof']['files'] + assert len(control['calls'])==3 + + +def test_scoped_multiunit_preserve_checks_each_declared_library_default(): + from dx_productivity.trial_task_center.saved_netlist_verification import _observations + row = dict(task_id='task',job_id='job',project_path='board.prj',old_part='OLD',new_part='NEW',schematic_name='MAIN',sheet_number='1') + attrs = {'Part Number':'NEW','Part Name':'NAME','Part Label':'LABEL'} + graph = {'components':{uid:dict(refdes='U1',source_page='1',source_schematic='MAIN',attributes=dict(attrs,Value=value)) + for uid,value in (('native-a','10K'),('native-b','20K'))}} + expected = {uid:dict(refdes='U1',attributes=attrs,value=value,present=True,old_value='OLD',target_cell='') + for uid,value in (('original-a','10K'),('original-b','20K'))} + values = _observations(graph,row,expected,dict(target_symbol='symbol',slot_count=2))['value_readback'] + assert [item['actual_value'] for item in values]==['10K','20K'] + + +def test_native_commit_preserves_active_batch_status_identity_and_incremental_tail(saved_case): + from types import SimpleNamespace + service,store,task,preparer,project,rows,control = saved_case + session = control['session'] + original_identity = session.status_identity + preparer._commit_staged_project(task,bind_source=True) + progress = preparer.complete_project_session(task,SimpleNamespace(worker=None),session,service.projects(task)) + assert progress.saved_items==2 and progress.queue_complete + assert session.status_identity==original_identity + + +@pytest.mark.parametrize('saved_case',['execute'],indirect=True) +@pytest.mark.parametrize('entrypoint',['single','disabled_scope','retained_scope']) +def test_nonretained_entrypoint_commits_one_saved_native_prefix(saved_case,monkeypatch,entrypoint): + import subprocess + from contextlib import contextmanager + from types import SimpleNamespace + service,store,task,preparer,project,rows,control = saved_case + root = preparer.data_root/'quick-run' + monkeypatch.setattr('dx_productivity.trial_task_center.cell_catalog.preflight_command_target',lambda *a:None) + control['closes']=0 + class Boundary: + enabled=True + worker=None + on_commit=None + def prepare(self,project):pass + def run_step(self,project,command,timeout): + assert self.enabled + self.job=command[-1] + if self.worker is None:self.jobs=[] + self.jobs.append(self.job) + self.worker=SimpleNamespace(root=root,token='e'*32) + with (root/'status.tsv').open('a') as stream:stream.write(self.job+'\tpending_save\tsession_staged\tstaged native write\n') + return subprocess.CompletedProcess(command,0,'','') + def close(self): + if self.worker is None:return + control['closes']+=1 + (root/f'project-commit-{self.worker.token}.tsv').write_text(self.worker.token+'\t'+str(project)+'\tproject_saved\n'+ + ''.join(job+'\tpending_save\n' for job in self.jobs)) + if self.on_commit:self.on_commit(self.worker) + self.worker=None + @contextmanager + def scope(**kwargs): + assert kwargs.get('enabled',True) + boundary=Boundary() + try:yield boundary + finally:boundary.close() + preparer.project_session_scope=scope + runtime=SimpleNamespace() + if entrypoint=='single':result=service.execute_quick_run(task,runtime=runtime) + elif entrypoint=='retained_scope': + with scope(enabled=True) as boundary: + staged=preparer.execute_step(task,service.projects(task),service.rules(task),batch_mode=True, + batch_session=control['session'],project_session=boundary,runtime=runtime) + assert staged.state=='pending_save' and control['closes']==0 + result=preparer.execute_step(task,service.projects(task),service.rules(task),batch_mode=True, + batch_session=control['session'],project_session=boundary,runtime=runtime) + else: + disabled=SimpleNamespace(enabled=False,run_step=lambda *a:pytest.fail('disabled legacy native path used')) + result=preparer.execute_step(task,service.projects(task),service.rules(task),batch_mode=True, + batch_session=control['session'],project_session=disabled,runtime=runtime) + completed = 2 if entrypoint=='retained_scope' else 1 + assert result.state=='saved_ok' and result.progress.saved_items==completed + assert result.progress.completed_items==completed and result.progress.queue_complete is (completed==2) + assert control['closes']==1 and len(control['calls'])==3 + assert [row[0] for row in store._connection.execute('SELECT state FROM execution_operations ORDER BY rowid')]==( + ['verified','verified'] if completed==2 else ['verified','pending']) + from dx_productivity.trial_task_center.value_readback import value_readback_details + assert value_readback_details(result)['value_readback']['value_readback_status']=='verified' + + +@pytest.mark.parametrize('saved_case',['execute'],indirect=True) +@pytest.mark.parametrize(('failure','damage'),[('history',None),('before_sql',None),('after_sql',None), + ('history','historical_marker'),('history','historical_artifact'),('history','historical_attempt'), + ('history','current_source'),('history','later_actual')]) +def test_two_saved_prefixes_recover_latest_source_without_replaying_history(saved_case,monkeypatch,failure,damage): + from types import SimpleNamespace + from test_batch_runtime import Desktop + from dx_productivity.trial_task_center.batch_runtime import BatchCadRuntime + from dx_productivity.trial_task_center.batch_attempt import prepare_attempt, _publish + from dx_productivity.trial_task_center.batch_supervisor import _mark_interrupted + service,store,task,preparer,project,rows,control = saved_case + root=preparer.data_root/'quick-run'; first='a'*32; second='f'*32 + attempt=preparer.journal.claim(task,rows[0]) + proof=preparer.result_proof(root,rows[0],('pending_save','session_staged','first native prefix')) + preparer.journal.stage_project_result(attempt,rows[0],session_token=first,root=root,proof=proof) + (root/f'project-commit-{first}.tsv').write_text(f'{first}\t{project}\tproject_saved\n{rows[0]["job_id"]}\tpending_save\n') + preparer._commit_staged_project(task,session_token=first,bind_source=True) + first_attempt=tuple(store._connection.execute('SELECT attempt_id,generation FROM execution_operations ORDER BY rowid LIMIT 1').fetchone()) + (project.parent/'database/icdb.dat').write_bytes(b'saved second prefix changes the live engineering database') + attempt=preparer.journal.claim(task,rows[1]) + proof=preparer.result_proof(root,rows[1],('pending_save','session_staged','second native prefix')) + preparer.journal.stage_project_result(attempt,rows[1],session_token=second,root=root,proof=proof) + (root/f'project-commit-{second}.tsv').write_text(f'{second}\t{project}\tproject_saved\n{rows[1]["job_id"]}\tpending_save\n') + if failure=='before_sql': + runtime=BatchCadRuntime(preparer.data_root,'execution',desktop_factory=Desktop,session_id='b'*32) + runtime._ensure_desktop(); runtime.cad=SimpleNamespace(checkpoint=lambda _:None) + runtime.record.update(active_job=rows[1]['job_id'],active_task=task) + path=runtime.path.parent/'attempts'/f'{rows[1]["job_id"]}.json' + expected=prepare_attempt(path,session_id='b'*32,generation=1,task_id=task, + job_id=rows[1]['job_id'],project_path=str(project),attempt_id='c'*32) + _publish(path,dict(expected,state='mutation_possible'));runtime._current_attempts=[(path,expected)] + (root/'project-session.request').write_text(second+'\t'+str(project)+'\t'+rows[1]['job_id']) + runtime._checkpoint(root,project,'c'*32) + runtime.desktop.close();runtime.record['cleanup']=runtime.desktop.cleanup_record + runtime.desktop=runtime.cad=None;runtime._record_release() + _mark_interrupted(preparer.data_root,dict(batch_id=runtime.session_id,operation='execute_task_queue', + task_ids=[task],uncertainty_roots={task:str(preparer.data_root)}),'parent crashed before second SQL callback') + else: + original=HistoryRepository.append + if failure=='history': + monkeypatch.setattr(HistoryRepository,'append',lambda *a,**k:(_ for _ in ()).throw(OSError('second prefix history failure'))) + with pytest.raises(OSError):preparer._commit_staged_project(task,session_token=second,bind_source=True) + monkeypatch.setattr(HistoryRepository,'append',original) + else:preparer._commit_staged_project(task,session_token=second,bind_source=True) + _write_uncertain_flag(root/'uncertain.flag','receipt_commit_failed') + store.set_task_status(task,TaskStatus.BLOCKED) + if damage=='historical_marker':(root/f'project-commit-{first}.tsv').write_text('changed historical marker') + elif damage=='historical_artifact': + original_proof=json.loads(next(item for item in preparer.journal.project_commit_records(task) if item['session_token']==first)['proof_json']) + Path(original_proof['saved_netlist']['verification_path']).write_text('{}') + elif damage=='historical_attempt': + store._connection.execute('UPDATE execution_operations SET generation=generation+1 WHERE operation_key=?', + (preparer.journal.project_commit_attempts(task,first)[rows[0]['job_id']][0],)) + elif damage=='current_source':(project.parent/'database/icdb.dat').write_bytes(b'unexplained latest-source modification') + elif damage=='later_actual': + item=dict(store._connection.execute('SELECT * FROM execution_operations LIMIT 1').fetchone()) + command=json.loads(item['command_json']);command['old_part']='LATER' + store._connection.execute('''INSERT INTO execution_operations(task_id,round_id,operation_key,command_json,state,attempt_id,generation) + VALUES (?,?,?,?,'prepared',?,1)''',(task,item['round_id'],'later-operation',json.dumps(command),'d'*32)) + calls_before=len(control['calls']) + reopened=TaskStore(store.path) + try: + worker=QuickRunPreparer(preparer.data_root,process_runner=_run_process) + resumed=TaskCenterService(reopened,configure_logging(preparer.data_root),quick_run_preparer=worker) + if damage: + with pytest.raises(TaskCenterError):resumed.recover_quick_run(task,confirmed=True) + assert reopened.get_task(task).status is TaskStatus.BLOCKED + assert (root/'uncertain.flag').is_file() and len(control['calls'])==calls_before + return + assert resumed.recover_quick_run(task,confirmed=True).progress.saved_items==2 + assert resumed.recover_quick_run(task,confirmed=True).progress.saved_items==2 + assert reopened.get_task(task).status is TaskStatus.COMPLETED + assert tuple(reopened._connection.execute('SELECT attempt_id,generation FROM execution_operations ORDER BY rowid LIMIT 1').fetchone())==first_attempt + assert len([item for item in HistoryRepository(reopened).page().rows if item['operation']=='器件替换'])==2 + assert len(control['calls'])==calls_before+(3 if failure=='before_sql' else 0) + finally:reopened.close() diff --git a/tests/v1_1/test_saved_netlist_writer.py b/tests/v1_1/test_saved_netlist_writer.py new file mode 100644 index 0000000..114e142 --- /dev/null +++ b/tests/v1_1/test_saved_netlist_writer.py @@ -0,0 +1,266 @@ +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from dx_productivity.trial_task_center import native_helper +import test_accuracy_vbs_guards as guards + + +def test_new_snapshot_mode_requires_exact_marker_and_selected_only(tmp_path): + path=tmp_path/'snapshot.tsv' + path.write_text('M\tboard\tOLD\tNEW\tMAIN:1\tpreserve\nX\tsaved_netlist_v1\nC\tu1\tR1\t0\t0\t0\t1\tNETLIST\n') + assert native_helper.saved_netlist_snapshot(path) + for extra in ('X\tuntouched_full_v1\n','X\tsaved_netlist_v1\n','U\tu2\tR2\tOLD\tv\tn\tl\n'): + path.write_text('M\tboard\tOLD\tNEW\tMAIN:1\nX\tsaved_netlist_v1\nC\tu1\tR1\t0\t0\t0\t1\tNETLIST\n'+extra) + with pytest.raises(ValueError):native_helper.saved_netlist_snapshot(path) + + +@pytest.mark.parametrize('extra', ['', 'X\tuntouched_full_v1\n', 'U\tu2\tR2\tOLD\tv\tn\tl\n', + 'A\tu2\tValue\tv\tv\t0\t0\t1\t2\t3\t0\t1\n']) +def test_vbs_snapshot_reader_selects_new_protocol_strictly(tmp_path,extra): + snapshot=tmp_path/'snapshot.tsv' + snapshot.write_text('M\tboard.prj\tOLD\tNEW\tMAIN:1\tpreserve\n' + 'X\tsaved_netlist_v1\nC\tu1\tR1\t0\t0\t0\t1\tNETLIST\n' + 'A\tu1\tValue\tv\tv\t0\t0\t1\t2\t3\t0\t1\n'+extra) + output=guards.run_vbs(tmp_path,['QPReadSnapshot','QPReadUtf8'],''' +Dim Records,Code +On Error Resume Next +Set Records=QPReadSnapshot("'''+str(snapshot)+'''") +Code=Err.Number:Err.Clear +WScript.Echo CStr(Code=0) +If Code=0 Then WScript.Echo CStr(QP_SavedNetlistMode) +''', ''' +Dim QP_SavedNetlistMode +''') + assert output.splitlines()==(['True','True'] if not extra else ['False']) + + +def test_capture_uses_selected_attributes_without_page_or_pin_validation(tmp_path): + path=tmp_path/'snapshot.tsv' + output=guards.run_vbs(tmp_path,['QPCaptureAndSelect','QPCommandTargets','QPSnapshotComponent', + 'QPRequireUniqueAttributeNames','QPAttributeObservations','QPBooleanText','QPLogField','QPTargetCell', + 'QPSnapshotAttribute','QPSortSnapshotLines','QPOptionalAttributeField','QPFindCurrentAttribute','QPWriteUtf8','QPReadUtf8','QPInvalidatePinIndex','QPInvalidateComponentIndex'],''' +Dim Comp,Other,Attr,Command,Text +Set QP_App=New FakeApp +Set Comp=New FullComponent:Comp.UID="u1":Comp.Refdes="R1" +Set Other=New FullComponent:Other.UID="u2":Other.Refdes="R2":Other.RaiseOnFind=True +Set Attr=New FullAttribute:Attr.Name="Part Number":Attr.Value="OLD":Attr.InstanceValue="OLD":Comp.Attributes.Add Attr,True +Set Attr=New FullAttribute:Attr.Name="Value":Attr.Value="1K":Attr.InstanceValue="1K":Comp.Attributes.Add Attr,True +QP_App.ActiveView.Components.Add Comp,True:QP_App.ActiveView.Components.Add Other,True +Set Command=CreateObject("Scripting.Dictionary") +Command.Add "job_id","job":Command.Add "old_part_number","OLD":Command.Add "new_part_number","NEW" +Command.Add "target_scope","targets":Command.Add "target_selectors",QPEncode("u1" & Chr(31) & "R1" & Chr(31) & "1K") +QPCaptureAndSelect Command,"'''+str(path)+'''" +Text=QPReadUtf8("'''+str(path)+'''") +WScript.Echo CStr(InStr(Text,"X" & vbTab & "saved_netlist_v1")>0) +WScript.Echo CStr(InStr(Text,"NETLIST")>0) +WScript.Echo CStr(InStr(Text,vbCrLf & "U" & vbTab)=0 And InStr(Text,vbCrLf & "G" & vbTab)=0) +''',prelude=guards.LOG_STUB+guards.FULL_FAKE+''' +Dim QP_SavedNetlistMode +Sub QPProgress(ByVal Stage,ByVal Done,ByVal Total) +End Sub +Function QPValueMode(ByRef Command) + QPValueMode="preserve" +End Function +Function QPCustomValue(ByRef Command) + QPCustomValue="" +End Function +Function QPSyncNc(ByRef Command) + QPSyncNc=False +End Function +Sub QPWriteStatus(ByVal Root,ByVal Job,ByVal State,ByVal Code,ByVal Message) +End Sub +Function QPComponentPins(ByVal Uid) + Err.Raise 59001,"Forbidden","pin query" +End Function +Function QPCurrentSemanticState() + Err.Raise 59002,"Forbidden","whole page" +End Function +Sub QPVerifyUntouched(ByRef Records) + Err.Raise 59003,"Forbidden","unselected validation" +End Sub +Function QPUseNativeSnapshot() + Err.Raise 59004,"Forbidden","native CAD read" +End Function +''') + assert output.splitlines()==['True','True','True'] + + +def test_saved_commit_closes_once_and_leaves_applied_rows_pending(tmp_path): + output = guards.run_vbs(tmp_path, ['QPCommitSavedNetlistProject', 'QPWriteUtf8', 'QPReadUtf8'], ''' +Dim Applied, Unchanged, Manifest +QP_Root="'''+str(tmp_path)+'''" +QP_SessionProject="board.prj":QP_SessionToken="session" +Set QP_SessionItems=CreateObject("Scripting.Dictionary") +Set QP_SessionDocuments=CreateObject("Scripting.Dictionary") +Set Applied=CreateObject("Scripting.Dictionary") +Applied.Add "saved_netlist",True:Applied.Add "final_state","restored_ok" +Set Unchanged=CreateObject("Scripting.Dictionary") +Unchanged.Add "saved_netlist",True:Unchanged.Add "final_state","no_match" +QP_SessionItems.Add "job1",Applied:QP_SessionItems.Add "job2",Unchanged +QPCommitSavedNetlistProject +Manifest=QPReadUtf8(QP_Fso.BuildPath(QP_Root,"project-commit-session.tsv")) +WScript.Echo CloseCount +WScript.Echo CStr(InStr(Manifest,"project_saved")>0 And InStr(Manifest,"job1" & vbTab & "pending_save")>0) +WScript.Echo CStr(InStr(Manifest,"job2" & vbTab & "no_match")>0 And InStr(Manifest,"saved_ok")=0) +''', guards.LOG_STUB+''' +Dim QP_SessionProject,QP_SessionToken,QP_SessionItems,QP_SessionDocuments,CloseCount +Sub QPCloseBatchProject(ByVal Path,ByVal Save) + If Not Save Then Err.Raise 59001,"Test","must save applied project" + CloseCount=CloseCount+1 +End Sub +Sub QPWriteStatus(ByVal Root,ByVal Job,ByVal State,ByVal Code,ByVal Message) +End Sub +Function QPCurrentSemanticState() + Err.Raise 59002,"Forbidden","whole page" +End Function +Sub QPEnsureProject(ByRef App,ByVal Path) + Err.Raise 59003,"Forbidden","saved reopen" +End Sub +''') + assert output.splitlines()==['1','True','True'] + + +def test_staging_reloads_command_without_recapturing_written_values(tmp_path): + output=guards.run_vbs(tmp_path,['QPStageSessionItem','QPWriteUtf8'],''' +QP_Root="'''+str(tmp_path)+'''" +Set QP_App=New StageView +Set QP_SessionItems=CreateObject("Scripting.Dictionary") +QP_BatchState="restored_ok":QP_CurrentJobId="job":QP_SavedNetlistMode=True +QPStageSessionItem +WScript.Echo CStr(QP_SessionItems("job")("saved_netlist")) +WScript.Echo CStr(QP_SessionItems("job")("snapshot_path")="snapshot-job.tsv") +''',guards.LOG_STUB+''' +Dim QP_App,QP_SessionItems,QP_BatchState,QP_CurrentJobId,QP_SavedNetlistMode,QP_SessionToken +Class StageView + Public Property Get ActiveView() + Set ActiveView=Me + End Property + Public Property Get Block() + Set Block=Me + End Property + Public Property Get SheetNum() + SheetNum="1" + End Property + Function GetName(ByVal Kind) + GetName="MAIN" + End Function +End Class +Function QPReadCommand(ByVal Path) + If QP_BatchState<>"" Then Err.Raise 59001,"Test","cached command state not cleared" + Set QPReadCommand=CreateObject("Scripting.Dictionary") +End Function +Function QPReadSnapshot(ByVal Path) + QP_SavedNetlistMode=True + Set QPReadSnapshot=CreateObject("Scripting.Dictionary") +End Function +Function QPJobSnapshotPath(ByVal Job) + QPJobSnapshotPath="snapshot-" & Job & ".tsv" +End Function +Sub QPRequireCommandSnapshot(ByRef Command,ByVal Path) +End Sub +Function QPCurrentSemanticState() + Err.Raise 59002,"Forbidden","whole page" +End Function +Sub QPVerifyUntouched(ByRef Records) + Err.Raise 59003,"Forbidden","unselected verification" +End Sub +Function QPCaptureValueState(ByRef Candidate) + Err.Raise 59004,"Forbidden","expected Value derived after writing" +End Function +Sub QPWriteStatus(ByVal Root,ByVal Job,ByVal State,ByVal Code,ByVal Message) + WScript.Echo State +End Sub +''') + assert output.splitlines()==['pending_save','True','True'] + + +def test_native_target_completion_reads_no_unselected_attributes(monkeypatch): + target=SimpleNamespace(UID='u1',Refdes='R1') + other=SimpleNamespace(UID='u2',Refdes='R2') + def attribute(component,name,**kwargs): + assert component is target + assert name=='Part Number' + return 'NEW' + monkeypatch.setattr(native_helper,'attribute_value',attribute) + records=[['C','u1','R1','0','0','0','1','NETLIST']] + assert native_helper.applied_replacement_uids([other,target],records,'NEW')==['u1'] + + +def test_native_pin_promotion_does_not_query_pins_in_saved_mode(monkeypatch): + target=SimpleNamespace(UID='u1',Refdes='R1') + monkeypatch.setattr(native_helper,'components_on_sheet',lambda app,api:[target]) + monkeypatch.setattr(native_helper,'selection',lambda component,state:None) + slots=[] + class View: + Block=SimpleNamespace(PromoteSymbolNumbers=lambda kind,slot:slots.append(slot)) + def Query(self,*args): + raise AssertionError('CAD pin validation forbidden') + assert native_helper.promote_pin_numbers(SimpleNamespace(ActiveView=View()),None,['u1'],2,verify_pins=False)==[] + assert slots==[1,2] + + +@pytest.mark.parametrize(('mode','present','nc','expected'), [ + ('preserve', True, False, 'library-value'), + ('preserve', False, False, ''), + ('custom', True, False, 'custom-value'), + ('part_number', True, False, 'NEW'), + ('part_label', True, False, 'library-label'), + ('preserve', True, True, 'library-value/NC'), +]) +def test_expectations_bind_snapshot_and_pre_restore_target_value(tmp_path,mode,present,nc,expected): + output=guards.run_vbs(tmp_path,['QPWriteWriterExpectations','QPWriteUtf8','QPReadUtf8','QPBooleanText','QPAppendNcMarker','QPValueHasNcMarker'],''' +Dim Command,Records,Components,Record,States,Before,Text,Rows,Fields +QP_Root="'''+str(tmp_path)+'''" +Set QP_App=New ExpectApp +Set Command=CreateObject("Scripting.Dictionary") +Command.Add "task_id","task":Command.Add "job_id","job":Command.Add "project_path","board.prj" +Command.Add "new_part_number","NEW" +Set Components=CreateObject("Scripting.Dictionary") +Set Record=CreateObject("Scripting.Dictionary"):Record.Add "uid","u1":Record.Add "refdes","R1" +Components.Add "0",Record +Set Records=CreateObject("Scripting.Dictionary"):Records.Add "components",Components +Set States=CreateObject("Scripting.Dictionary") +Set Before=CreateObject("Scripting.Dictionary") +Before.Add "value","'''+('library-value' if present else '')+'''":Before.Add "exists",'''+str(present)+''' +Before.Add "part_name","library-name":Before.Add "part_label","library-label" +Before.Add "nc_required",'''+str(nc)+''':States.Add "0",Before +QPWriteUtf8 QPJobSnapshotPath("job"),"original snapshot" & vbCrLf +QPWriteWriterExpectations Command,Records,States +Text=QPReadUtf8(QP_Fso.BuildPath(QP_Root,"writer-expectations-job.tsv")) +Rows=Split(Text,vbCrLf):Fields=Split(Rows(0),vbTab) +WScript.Echo CStr(QPDecode(Fields(7))=("original snapshot" & vbCrLf)) +Fields=Split(Rows(1),vbTab) +WScript.Echo QPDecode(Fields(3)) +WScript.Echo Fields(4) +''',guards.LOG_STUB+''' +Dim QP_App +Class ExpectApp + Public Property Get ActiveView() + Set ActiveView=Me + End Property + Public Property Get Block() + Set Block=Me + End Property + Public Property Get SheetNum() + SheetNum="1" + End Property + Function GetName(ByVal Kind) + GetName="MAIN" + End Function +End Class +Function QPJobSnapshotPath(ByVal Job) + QPJobSnapshotPath=QP_Fso.BuildPath(QP_Root,"snapshot-" & Job & ".tsv") +End Function +Function QPValueMode(ByRef Command) + QPValueMode="'''+mode+'''" +End Function +Function QPCustomValue(ByRef Command) + QPCustomValue="custom-value" +End Function +Function QPTargetCell(ByRef Command) + QPTargetCell="cell" +End Function +''') + assert output.splitlines()==['True',expected,'1' if present or mode!='preserve' or nc else '0'] diff --git a/tools/measure_project_session.py b/tools/measure_project_session.py index ec46d5e..132d42f 100644 --- a/tools/measure_project_session.py +++ b/tools/measure_project_session.py @@ -90,16 +90,23 @@ def main(): text = (evidence / 'quick-part-replace.log').read_text(encoding='utf-8') report['worker_starts'] = len(tuple(evidence.glob('monitor-*.ready'))) report['open_project_calls'] = text.count('stage=open_project target=') + report['save_project_calls'] = text.count('save_requested job=') + report['whole_page_native_captures'] = text.count('stage=native_snapshot_verified') events = [json.loads(line) for line in service.tail_log(task.task_id, limit=None)] report['timings'] = [event for event in events if event['operation'] in {'execution_timing', 'quick_run_executed'}] reader = QuickRunPreparer(output / 'independent-read') started = time.perf_counter() actual = reader._discover_project_sheets(project, (args.old, args.new), collect_components=True) report['readback_seconds'] = time.perf_counter() - started - by_key = {(row.schematic_name, row.sheet_number, row.uid): row for row in actual.components} + by_key = {} + for row in actual.components: + key = (row.schematic_name, row.sheet_number, row.refdes) + by_key.setdefault(key, []).append(row) comparisons = [] for target in inventory: - row = by_key[(target.schematic_name, target.sheet_number, target.uid)] + matches = by_key[(target.schematic_name, target.sheet_number, target.refdes)] + assert len(matches) == 1, 'measurement requires unique scoped reference designators' + row = matches[0] expected_part = args.new if target.refdes in selected else target.old_part_number comparisons.append({'refdes': target.refdes, 'sheet': target.sheet_number, 'expected': expected_part, 'actual': row.old_part_number})