fix: address PR review identity and snapshot safety gaps

This commit is contained in:
阿白叔 committed 2026-10-30 17:48:08 +08:00
1 parent 131b6dbbb3
commit f0a0131aac
15 files changed
+312 -64

No files matched your search

@@ -11,10 +11,10 @@
| Part Name | 替换后库身份校验 | 替换回读阶段必需;缺失/异常失败,不继续提交为成功 |
| Part Label | 仅在 Value 策略为 Part Label 或库回读证明要求时必需 | 不需要时可为空;需要时缺失/异常失败 |
| Cell Name、NC、用户属性 | 规则或可选策略 | 未启用对应策略时不读取或回退默认;启用时变为必需并校验 |
| 坐标、字体、颜色、可见性等显示字段 | 未选择器件的完整状态和展示证据 | 使用安全默认值并写 WARN;若后续完整回读证明不一致,停止恢复/报告失败 |
| 坐标、字体、颜色、可见性等显示字段 | 原始状态保存、恢复和完整回读证据 | 读取失败保留为空的无效状态并写 WARN;需要保留该状态时在快照阶段阻断替换,恢复预检拒绝缺失字段;不将默认 0 写回工程 |
| 引脚/网络/坐标几何 | 连接和引脚号晋级证明 | 需要该证明时失败;不把缺失网络伪装成可验证的连接 |
Python native helper 现在对可选属性捕获 COM 异常并返回空值,对身份和源料号使用 required 模式;真实 UID 缺失时,当前页枚举和选择/回读统一使用 `@REFDES|...` fallback identity,并检测重复位号。VBS 增加了可选属性安全读取、显示字段默认值和警告日志;必需字段仍通过显式 required 读取。所有失败都回到有限错误出口,监督器可收集状态,不进入等待循环。
Python native helper 对可选属性捕获 COM 异常并返回空值,对身份和源料号使用 required 模式;真实 UID 缺失时,当前页枚举、引脚、选择、回读和恢复统一使用 `@REFDES|...` fallback identity,并检测重复位号。VBS 对可选库存字段允许空值降级;作为原始快照写回依据的 Value、InstanceValue、显示字段必须成功采集。不可读字段不能用默认值代替原始状态,必须在修改前停止。所有失败都回到有限错误出口,监督器可收集状态,不进入等待循环。
安全原则是“缺字段可降级,身份不可猜测”:如果降级会影响替换对象、保存回读或恢复判断,就停止而不是继续。诊断中会保留阶段、字段名和错误,但不会把错误的默认值当作成功证据。
@@ -40,4 +40,6 @@ $env:TMP=$env:TEMP
后续核对发现,原虚拟环境指向的 Codex Python 运行时已经缺少 `Lib/os.py`、`Lib/encodings/__init__.py`,运行时报告 `Could not find platform independent libraries <prefix>`;工具自带 PowerShell 部分模块也不可用。未修改原虚拟环境或这些共享运行时,改用本机完整 CPython 3.12.10 建立临时验证环境,在 `.pth` 中引用原有依赖与 Win32 DLL 目录。隔离启动实际导入 Win32、Qt 成功;发布前集合和 Value 恢复集合共 **1085 passed、2 warnings、285.51 秒**。剩余 2 项是在原依赖目录缺少 `win32ui` 的环境中导入 pywinauto 失败,属于验证环境依赖损坏,不是业务断言;需在目标机安装完整 pywin32 后复测。
后续 PR 审查复测确认:临时验证环境遗漏 `Pythonwin` 搜索路径导致上述 2 项 `win32ui` 导入失败,并非依赖文件不存在。补齐临时 `.pth` 后真实导入成功。该历史运行结果保留;当前代码、审查修复与精确测试范围见 [PR #9 审查修复记录](2026-10-30-pr9-review-fixes.md)。
Windows 10 实机、真实无 UID DxDesigner 7.9.5 工程保存重开回读、网络共享和其他机器许可证/中央库条件,仍需现场证据。
@@ -0,0 +1,49 @@
# PR #9 审查修复记录
审查来源:[评论 88](https://git.simgreek.com/Skyworth_Digital_Hardware/dxdesigner-part-replacement/pulls/9#issuecomment-88)、[评论 89](https://git.simgreek.com/Skyworth_Digital_Hardware/dxdesigner-part-replacement/pulls/9#issuecomment-89)。被审查提交为 `131b6db`。
## 阻断项
1. 旧格式原生回读把未选器件比较移回循环;新增零个未选器件、两个未选器件、首个未选器件被修改的回归。
2. `replacement_matches` 返回本地身份键;一/多个无 UID 目标的匹配结果直接流入 `promote_pin_numbers`,验证引脚归属不丢失。
3. VBS 组件索引、引脚索引、连接签名、捕获集合、保存重开回读和恢复预检统一使用 `QPComponentIdentityKey`。独立原生读取脚本携带同一身份函数。无 UID 且无位号不再生成 `@ANON`,与 Python 一致地阻断;fallback 使用标志在每次捕获前重置。
4. 不可读的显示字段返回空值状态,不再返回伪造的 `0`。快照在缺少需要保留的显示状态时立即失败;恢复预检和直接显示恢复入口在任何写入前拒绝缺失字段。基础 Value、InstanceValue 作为原始快照证据也必须可读,可选库存 Value 仍可降级为空。六项故障注入覆盖颜色、字体、字号、方向、可见性、坐标,确认 getter 恢复后仍不会写入默认值。
新增 VBS 流程回归使用生产函数、真实 `cscript.exe` 和带引脚 COM 替身,覆盖无 UID 捕获、目标/非目标集合区分、恢复、保存、重开和 `saved_ok` 回读。其 CAD 打开与命令传输使用替身,不能解释为真实 DxDesigner 验收通过。
## 其他意见的处理
- 损坏/不可读 `session.json`、错误 `cad_shutdown` 或 `cleanup_errors` 类型转为 `application_shutdown_failed`,保留业务结果,并将监督记录改为 blocked。
- 进度发布失败写 WARN,避免磁盘/权限错误静默丢失等待核验状态。
- 强制终止状态已存在时仍检查进程存活;存活则重试终止,已退出则避免重复调用。
- 已存在但为空的中断保护文件补写原因、flush、fsync;非空证据保持原样。
- 控制异常等待通过 `StopControl.waiting_for_resolution`、`resolution_error` 暴露状态,并每 15 秒写等待日志。保留进程所有权直至确认退出或明确强制结束;任意超时自动杀进程会破坏已有的安全停止约定,未采用该做法。
- worker 的等待允许由 GUI supervisor 终止其自有 Job 结束,见 `stop_control.wait_for_resolution` 的说明;普通取消不等于强制终止。现有真实监督器/Job 测试继续覆盖此边界。
- CAD 从未完成身份绑定、或者进程创建失败的边界继续保留保守保护;本轮不把“调用创建函数抛错”直接当作“绝无子进程/绝无写入”的证据。资源收尾失败与原始启动失败仍应结合诊断记录判断,尚未取得这些场景的现场 CAD 证据。
## 运行环境和数字口径
本轮使用 Windows 11 x64、本机完整 CPython 3.12.10、临时虚拟环境,复用项目依赖。临时 `.pth` 必须包含 `win32`、`win32/lib`、`Pythonwin` 和 Win32 DLL 路径。此前 1085 passed / 2 import errors 中的 `win32ui` 问题是临时环境遗漏 `Pythonwin`,不是原依赖文件不存在;现已验证真实导入 pywinauto 和 win32ui 成功,原虚拟环境未改写。
历史报告中的 957、960、986、923、1147 对应不同日期、提交和测试范围,不能相加或当作同一版本全量验收。本轮结果只引用下面的具体命令;旧的 Beta 4 发布日期保留其 2026-10-26 历史日期。兼容性 JSON 的本机路径作为内部环境证据保留,对外分发需另行脱敏。
```powershell
$env:TEMP='F:\dxpart-test-temp'
$env:TMP=$env:TEMP
& F:\dxpart-test-temp\verification-venv\Scripts\python.exe -m pytest -q tests/v1_1 tests/trial_task_center/test_execution_safety.py tests/trial_task_center/test_worker_monitor.py tests/integration/test_quick_value_modes.py tests/integration/test_automatic_replacement_regression.py tests/integration/test_quick_part_replace_contract.py --basetemp F:\dxpart-test-temp\pr9-review-final --junitxml build\pr9-review-final.xml --tb=short
```
专项初验:144 passed / 1 个测试替身缺失 Selected 属性;替身已修正。显示字段故障注入:6 passed。收尾记录、强制重试、保护文件与日志专项:8 passed。独立原生读取与收尾子集:77 passed、8 deselected。最终审查关键专项:127 passed。
上述扩大集合最终以 `--basetemp F:\dxpart-test-temp\pr9-review-green --junitxml build\pr9-review-green.xml` 重跑,结果:**1115 passed,1 warning,624.93 秒**。唯一提示是既有 pywinauto STA COM 模式提示;这包含修复后的 `tests/v1_1`、执行安全、工作进程监视、Value 全恢复、原生替换和 VBS 契约测试。首轮同范围结果 1109 passed / 1 failed,是旧契约要求直接访问 `CmpPin.Component.UID`;断言改为统一身份函数后重新验证,历史报告不覆盖。
冻结包由上述完整 CPython 3.12.10 构建成功;`tools/verify_packaged_runtime.py` 实际运行 EXE 验证监督器、Job/进程身份、`win32timezone` 和资源释放通过。源码/包内文件 SHA256 一致:
| 文件 | SHA256 |
|---|---|
| QuickPartReplace.vbs | `4380E5DFD5421F2B2BF104EFAC43128FAFEE4B281AB12F972AFE37CE46D7352E` |
| NativeSnapshotReader.vbs | `46519AA1191DAC97A778D0F4074F2CF3AAF23667E2863A6C7E2057045FCAF099` |
`git diff --check` 和 `python -m compileall -q src` 通过。
Windows 10 实机、真实 DxDesigner 7.9.5 无 UID 工程、中央库/许可证和网络共享条件仍待现场验收。
@@ -222,7 +222,7 @@ Function QPNativeCollectMode(ByRef SelectedUids, ByVal Token, ByVal Project, ByV
Count = 0
QPProgress "native_snapshot_read", 0, Components.Count
For Each Comp In Components
Uid = CStr(Comp.UID)
Uid = QPComponentIdentityKey(Comp)
If Len(Uid) = 0 Or Seen.Exists(Uid) Then QPNativeReadInvalid "duplicate or empty component UID"
Seen.Add Uid, True
If SelectedUids.Exists(Uid) Then
@@ -281,7 +281,7 @@ Function QPBuildNativeReadScript(ByVal Source, ByRef SelectedUids, ByVal Token,
"If QP_NR_Code<>0 Then QP_NR_Text=""ERROR"" & vbTab & " & QPNativeExpression(Token) & _
" & vbTab & CStr(QP_NR_Code) & vbTab & QPEncode(QP_NR_Source) & vbTab & QPEncode(QP_NR_Description) & vbCrLf" & vbCrLf & _
"QPWriteUtf8 " & QPNativeExpression(ResultPath) & ",QP_NR_Text" & vbCrLf & "On Error GoTo 0" & vbCrLf
Names = Split("QPNativeCollectMode QPNativeRequireContext QPNativeReadInvalid QPSnapshotComponent QPUntouchedComponent QPUntouchedFullState QPUntouchedIdentity QPComponentPins QPInvalidatePinIndex QPConnectionSignatureFromPins QPAddSortedSignature QPSnapshotAttribute QPReadOptionalAttributeValue QPOptionalAttributeField QPSortSnapshotLines QPEncode QPDecode QPProjectPath QPSheetIdentity QPCanonicalPath QPEnsureProjectAccess QPReadUtf8 QPWriteUtf8", " ")
Names = Split("QPNativeCollectMode QPNativeRequireContext QPNativeReadInvalid QPSnapshotComponent QPUntouchedComponent QPUntouchedFullState QPUntouchedIdentity QPComponentPins QPComponentIdentityKey QPInvalidatePinIndex QPConnectionSignatureFromPins QPAddSortedSignature QPSnapshotAttribute QPReadOptionalAttributeValue QPOptionalAttributeField QPSortSnapshotLines QPEncode QPDecode QPProjectPath QPSheetIdentity QPCanonicalPath QPEnsureProjectAccess QPReadUtf8 QPWriteUtf8", " ")
Pattern.Global = False
For Each Name In Names
Pattern.Pattern = "^(Function|Sub) " & Name & "\([^\n]*\n[\s\S]*?^End \1[ \t]*"
+54 -47
View File
@@ -414,7 +414,7 @@ Sub QPBuildComponentIndex(ByRef Components)
Set Uids = CreateObject("Scripting.Dictionary")
Count = 0
For Each Comp In Components
QPAddComponentIndexEntry Uids, CStr(Comp.UID), Comp
QPAddComponentIndexEntry Uids, QPComponentIdentityKey(Comp), Comp
Count = Count + 1
If Count Mod 25 = 0 Then QPProgress "index_components", Count, 0
Next
@@ -480,8 +480,7 @@ Function QPComponentPins(ByVal ComponentUid)
Set AllPins = QP_App.ActiveView.Query(VDM_COMPPIN, VD_ALL)
Count = 0
For Each CmpPin In AllPins
Owner = CStr(CmpPin.Component.UID)
If Len(Owner) = 0 Then Err.Raise vbObjectError + 862, "QuickPartReplace", "pin owner UID is empty"
Owner = QPComponentIdentityKey(CmpPin.Component)
If Not LocalIndex.Exists(Owner) Then
Set Bucket = CreateObject("Scripting.Dictionary")
LocalIndex.Add Owner, Bucket
@@ -815,17 +814,7 @@ Function QPComponentIdentityKey(ByRef Comp)
QPComponentIdentityKey = "@REFDES|" & Trim(CStr(Refdes))
QPLog QP_Root, "WARN", "component_uid_missing_using_refdes_fallback refdes=" & CStr(Refdes)
Else
Dim Point
On Error Resume Next
Set Point = Comp.GetLocation()
If Err.Number <> 0 Or Point Is Nothing Then
Err.Clear
On Error GoTo 0
Err.Raise vbObjectError + 872, "QuickPartReplace.Discovery", "component UID and Refdes are empty"
End If
QPComponentIdentityKey = "@ANON|" & CStr(Point.X) & "|" & CStr(Point.Y)
Err.Clear
On Error GoTo 0
Err.Raise vbObjectError + 872, "QuickPartReplace.Discovery", "component UID and Refdes are empty"
End If
End If
End Function
@@ -1017,7 +1006,7 @@ Sub QPFinishBatchItem()
For Index = 0 To Records.Item("components").Count - 1
Set Record = Records.Item("components").Item(CStr(Index))
Set Candidate = QPFindUniqueByOldLocation(Record)
If CStr(Candidate.UID) <> CStr(Record("uid")) Then _
If QPComponentIdentityKey(Candidate) <> CStr(Record("uid")) Then _
Err.Raise vbObjectError + 871, "QuickPartReplace.Batch", "saved component UID differs"
Plans.Add CStr(Index), Candidate
Next
@@ -1226,6 +1215,7 @@ Sub QPCaptureAndSelect(ByRef Command, ByVal SnapshotPath)
Dim Index
Dim Selectors, Selector, Uid, ValueAttr, ValueText, MatchedUids, UntouchedCount, NativeRead
QP_FallbackIdentityUsed = False
If StrComp(CStr(Command("old_part_number")), CStr(Command("new_part_number")), vbTextCompare) = 0 Then _
Err.Raise vbObjectError + 829, "QuickPartReplace", "source and target must differ"
QPInvalidatePinIndex
@@ -1318,7 +1308,7 @@ Sub QPCaptureAndSelect(ByRef Command, ByVal SnapshotPath)
UntouchedCount = 0
If NativeRead Is Nothing Then
For Each Comp In Components
If Not MatchedUids.Exists(CStr(Comp.UID)) Then
If Not MatchedUids.Exists(QPComponentIdentityKey(Comp)) Then
QPProgress "capture_untouched", UntouchedCount, Components.Count - Matches.Count
Snapshot = Snapshot & QPUntouchedComponent(Comp)
UntouchedCount = UntouchedCount + 1
@@ -1433,17 +1423,15 @@ End Function
Function QPUntouchedFullState(ByRef Comp)
Dim Point, Pins, Connections, Attr, AttributeText, Result, Uid, Identity
Uid = CStr(Comp.UID)
Identity = Uid
If Len(Trim(Uid)) = 0 Then Identity = "@REFDES|" & Trim(CStr(Comp.Refdes))
Identity = QPComponentIdentityKey(Comp)
Set Point = Comp.GetLocation()
Set Pins = QPComponentPins(Uid)
Set Pins = QPComponentPins(Identity)
If Pins.Count = 0 Then
' A genuinely empty query is valid for annotation symbols; COM errors
' still propagate. Selected replacement symbols continue to require pins.
Connections = "NO_PINS"
Else
Connections = QPConnectionSignatureFromPins(Uid, Pins)
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)) & _
@@ -1506,7 +1494,7 @@ Sub QPVerifyUntouched(ByRef Records)
' Read new component/pin proxies after each native mutation, restore or reopen.
QPInvalidatePinIndex
QPInvalidateComponentIndex
If QPUseNativeSnapshot() Then
If QPUseNativeSnapshot() And Not QP_FallbackIdentityUsed Then
If QPTryNativeVerifyUntouched(Records) Then Exit Sub
End If
Set Components = QP_App.ActiveView.Query(VDM_COMP, VD_ALL)
@@ -1579,12 +1567,10 @@ Function QPSnapshotComponent(ByRef Comp)
Dim ErrorDescription
Dim Uid, Identity, Pins
Uid = CStr(Comp.UID)
Identity = Uid
If Len(Trim(Uid)) = 0 Then Identity = "@REFDES|" & Trim(CStr(Comp.Refdes))
Identity = QPComponentIdentityKey(Comp)
Set Point = Comp.GetLocation()
Set Pins = QPComponentPins(Uid)
Connections = QPConnectionSignatureFromPins(Uid, Pins)
Set Pins = QPComponentPins(Identity)
Connections = QPConnectionSignatureFromPins(Identity, Pins)
Result = "C" & vbTab & QPEncode(Identity) & vbTab & _
QPEncode(CStr(Comp.Refdes)) & vbTab & QPEncode(CStr(Point.X)) & _
vbTab & QPEncode(CStr(Point.Y)) & vbTab & _
@@ -1638,7 +1624,7 @@ Function QPSortSnapshotLines(ByVal Text)
End Function
Function QPSnapshotAttribute(ByVal ComponentUid, ByRef Attr)
Dim Instance, Value, Point, ErrorNumber, ErrorDescription
Dim Instance, Value, Point, ErrorNumber, ErrorDescription, Field
Dim LocationX
Dim LocationY
Dim Color
@@ -1653,23 +1639,31 @@ Function QPSnapshotAttribute(ByVal ComponentUid, ByRef Attr)
Err.Clear
Instance = CStr(Attr.InstanceValue)
If Err.Number <> 0 Then
Instance = ""
QPLog QP_Root, "WARN", "optional_attribute_unavailable field=instance_value"
Err.Clear
On Error GoTo 0
Err.Raise vbObjectError + 836, "QuickPartReplace.Snapshot", "attribute InstanceValue unreadable; replacement blocked before mutation"
End If
Err.Clear
Value = CStr(Attr.Value)
If Err.Number <> 0 Then
Value = ""
QPLog QP_Root, "WARN", "optional_attribute_unavailable field=value"
Err.Clear
On Error GoTo 0
Err.Raise vbObjectError + 836, "QuickPartReplace.Snapshot", "attribute Value unreadable; replacement blocked before mutation"
End If
Err.Clear
Set Point = Nothing
Set Point = Attr.GetLocation()
If Err.Number = 0 And Not Point Is Nothing Then
LocationX = CStr(Point.X)
LocationY = CStr(Point.Y)
Else
LocationX = "0"
LocationY = "0"
ErrorNumber = Err.Number
Err.Clear
LocationX = ""
LocationY = ""
If ErrorNumber = 0 Then
If Not Point Is Nothing Then
LocationX = CStr(Point.X)
LocationY = CStr(Point.Y)
End If
End If
If Len(LocationX) = 0 Or Len(LocationY) = 0 Then
QPLog QP_Root, "WARN", "optional_display_field_unavailable field=location"
End If
Err.Clear
@@ -1679,6 +1673,10 @@ Function QPSnapshotAttribute(ByVal ComponentUid, ByRef Attr)
Size = QPOptionalAttributeField(Attr, "size")
Orientation = QPOptionalAttributeField(Attr, "orientation")
Visible = QPOptionalAttributeField(Attr, "visible")
For Each Field In Array(LocationX, LocationY, Color, Font, Size, Orientation, Visible)
If Len(CStr(Field)) = 0 Then Err.Raise vbObjectError + 836, _
"QuickPartReplace.Snapshot", "attribute display state unreadable; replacement blocked before mutation"
Next
QPSnapshotAttribute = "A" & vbTab & QPEncode(ComponentUid) & vbTab & _
QPEncode(CStr(Attr.Name)) & vbTab & QPEncode(Value) & _
vbTab & QPEncode(CStr(Instance)) & vbTab & QPEncode(LocationX) & _
@@ -1722,7 +1720,7 @@ Function QPOptionalAttributeField(ByRef Attr, ByVal FieldName)
Err.Clear
On Error GoTo 0
If ErrorNumber <> 0 Then
QPOptionalAttributeField = "0"
QPOptionalAttributeField = ""
QPLog QP_Root, "WARN", "optional_display_field_unavailable field=" & CStr(FieldName) & _
" description=" & CStr(ErrorDescription)
Else
@@ -1761,9 +1759,9 @@ Sub QPRestoreAfterOperatorReplace(ByRef Command, ByVal SnapshotPath)
For Index = 0 To Records.Item("components").Count - 1
Set ComponentRecord = Records.Item("components").Item(CStr(Index))
Set Candidate = QPFindUniqueByOldLocation(ComponentRecord)
If Used.Exists(CStr(Candidate.UID)) Then _
If Used.Exists(QPComponentIdentityKey(Candidate)) Then _
Err.Raise vbObjectError + 831, "QuickPartReplace", "duplicate replacement association"
Used.Add CStr(Candidate.UID), True
Used.Add QPComponentIdentityKey(Candidate), True
QPRestorePreflight Candidate, ComponentRecord, Records.Item("attributes"), _
CStr(Command("new_part_number")), QPValueMode(Command)
Plans.Add CStr(Index), Candidate
@@ -1920,9 +1918,9 @@ Sub QPRecoverSavedJob(ByRef Command, ByVal SnapshotPath)
QPRequireSnapshotContext SnapshotPath
Set Record = Records.Item("components").Item(CStr(Index))
Set Candidate = QPFindUniqueByOldLocation(Record)
If CStr(Candidate.UID) <> CStr(Record("uid")) Or Used.Exists(CStr(Candidate.UID)) Then _
If QPComponentIdentityKey(Candidate) <> CStr(Record("uid")) Or Used.Exists(QPComponentIdentityKey(Candidate)) Then _
Err.Raise vbObjectError + 865, "QuickPartReplace.Recovery", "saved component UID changed or duplicated"
Used.Add CStr(Candidate.UID), True
Used.Add QPComponentIdentityKey(Candidate), True
PartNumber = QPRequiredAttributeValue(Candidate, "Part Number")
If StrComp(PartNumber, CStr(Command("old_part_number")), vbTextCompare) = 0 Then
OldCount = OldCount + 1
@@ -2029,7 +2027,7 @@ End Function
Sub QPRestorePreflight(ByRef Comp, ByRef ComponentRecord, _
ByRef Attributes, ByVal NewPartNumber, ByVal ValueMode)
Dim Index
Dim Index, Field
Dim Record
Dim LabelAttr
Dim ValueAttr
@@ -2039,7 +2037,7 @@ Sub QPRestorePreflight(ByRef Comp, ByRef ComponentRecord, _
Dim CurrentConnections
Dim SavedConnections
If CStr(Comp.UID) <> CStr(ComponentRecord("uid")) Or _
If QPComponentIdentityKey(Comp) <> CStr(ComponentRecord("uid")) Or _
CStr(Comp.Refdes) <> CStr(ComponentRecord("refdes")) Then _
Err.Raise vbObjectError + 831, "QuickPartReplace", "replacement component UID or Refdes differs from snapshot; no restoration writes allowed"
If StrComp(QPRequiredAttributeValue(Comp, "Part Number"), _
@@ -2057,6 +2055,15 @@ Sub QPRestorePreflight(ByRef Comp, ByRef ComponentRecord, _
Err.Raise vbObjectError + 804, "QuickPartReplace", _
"connection validation failed"
End If
For Index = 0 To Attributes.Count - 1
Set Record = Attributes.Item(CStr(Index))
If CStr(Record("uid")) = CStr(ComponentRecord("uid")) Then
For Each Field In Array("x", "y", "color", "font", "size", "orientation", "visible")
If Len(CStr(Record(Field))) = 0 Then Err.Raise vbObjectError + 836, _
"QuickPartReplace.Snapshot", "attribute display state unavailable; no restoration writes allowed"
Next
End If
Next
If ValueMode = "preserve" Or ValueMode = "custom" Then Exit Sub
HasOldValue = False
Set ValueRecord = Nothing
@@ -2777,7 +2784,7 @@ End Function
Function QPConnectionSignature(ByRef Comp)
Dim Pins, Uid
Uid = CStr(Comp.UID)
Uid = QPComponentIdentityKey(Comp)
Set Pins = QPComponentPins(Uid)
QPConnectionSignature = QPConnectionSignatureFromPins(Uid, Pins)
End Function
@@ -2806,7 +2813,7 @@ Function QPConnectionSignatureFromPins(ByVal ComponentUid, ByRef Pins)
PinReadCount = 0
For Each PinIndexKey In Pins.Keys
Set CmpPin = Pins.Item(CStr(PinIndexKey))
If StrComp(CStr(CmpPin.Component.UID), ComponentUid, _
If StrComp(QPComponentIdentityKey(CmpPin.Component), ComponentUid, _
vbBinaryCompare) = 0 Then
Set Point = CmpPin.GetLocation()
PinKey = CStr(CmpPin.Number) & "|" & CStr(Point.X) & "|" & _
@@ -62,7 +62,8 @@ def _force_owned_supervisor(root, journal, process):
"""Persist uncertainty before terminating the exact process/Job we own."""
from .batch_resources import write_record
path = Path(root) / 'batch-resources' / journal['batch_id'] / 'supervisor.json'
if journal.get('force_state') in {'termination_requested', 'confirmed'}:
if (journal.get('force_state') in {'termination_requested', 'confirmed'}
and process.poll() is not None):
return
journal['stop_mode'] = 'forced'
journal.setdefault('force_requested_at', time.time())
@@ -97,6 +98,8 @@ def _retain_supervisor_after_control_error(root, journal, process, control, erro
"""Do not turn a GUI/transport exception into an unconfirmed Job kill."""
from .batch_resources import write_record
control.set()
control.waiting_for_resolution = True
control.resolution_error = str(error)
control.control_error = '控制通信异常,已请求安全停止并保留应用;可导出诊断或明确强制结束:' + str(error)
journal['protect_all_targets'] = True
try:
@@ -108,7 +111,14 @@ def _retain_supervisor_after_control_error(root, journal, process, control, erro
{'version': VERSION, 'batch_id': journal['batch_id'], 'attempt_id': journal['attempt_id']})
except OSError:
pass # Keep ownership; failure to request stop is not permission to kill.
last_notice = time.monotonic()
while True:
if time.monotonic() - last_notice >= 15:
import logging
logging.getLogger(__name__).warning(
'supervisor_retained_waiting_for_resolution batch_id=%s error=%s',
journal['batch_id'], control.control_error)
last_notice = time.monotonic()
if control.force_event.is_set():
try:
_force_owned_supervisor(root, journal, process)
@@ -249,7 +259,19 @@ def _finish_response(root, journal, response, context):
resource = json.loads(resource_path.read_text(encoding='utf-8'))
except FileNotFoundError:
resource = {}
shutdown = resource.get('cad_shutdown') or {}
except (OSError, ValueError, TypeError) as failure:
journal.update(state='blocked', shutdown_record_error=str(failure))
write_record(Path(root) / 'batch-resources' / journal['batch_id'] / 'supervisor.json', journal)
raise application_shutdown_error(result, error, primary) from failure
shutdown = resource.get('cad_shutdown') if isinstance(resource, dict) else None
if shutdown is None and isinstance(resource, dict):
shutdown = {}
if (not isinstance(shutdown, dict)
or not isinstance(shutdown.get('cleanup_errors', ()), (list, tuple))
or any(not isinstance(item, dict) for item in shutdown.get('cleanup_errors', ()))):
journal.update(state='blocked', shutdown_record_error='invalid shutdown record shape')
write_record(Path(root) / 'batch-resources' / journal['batch_id'] / 'supervisor.json', journal)
raise application_shutdown_error(result, error, primary)
if (shutdown.get('orderly_shutdown') is False or shutdown.get('forced_termination')
or shutdown.get('diagnostic_errors')
or any(item.get('stage') != 'desktop_release' for item in shutdown.get('cleanup_errors', ()))):
@@ -558,7 +558,7 @@ def replacement_matches(components, records, target, require_part_label, *, libr
if expected_name is not None and (part_name != expected_name
or (expected_label and part_label != expected_label)):
raise ValueError(f'Native replacement does not match the selected target library identity; uid={candidate.UID}')
matches.append(str(candidate.UID))
matches.append(_component_uid(candidate))
if len(set(matches)) != len(records):
raise ValueError("Duplicate replacement association")
return matches
@@ -578,7 +578,7 @@ def verify_replacement_readback(snapshot, components, metadata, records, before_
actual = None if component is None else (
str(component.Refdes), *(attribute_value(component, name)
for name in ('Part Number', 'Value', 'Part Name', 'Part Label')))
if actual != identity:
if actual != identity:
raise ValueError('An unselected component was changed')
verified = replacement_matches(components, records, metadata[3], require_part_label,
library_row=library_row)
@@ -31,6 +31,9 @@ def protect_interruption(root, reason):
# A previous create/write/fsync may have failed. Existence alone does
# not establish durable evidence; preserve its bytes but sync again.
with marker.open('r+b') as existing:
if not existing.read(1):
existing.write(str(reason).encode('utf-8'))
existing.flush()
os.fsync(existing.fileno())
else:
with stream:
@@ -131,8 +131,10 @@ def _atomic_text(path: Path, text: str) -> None:
def _publish_progress(path: Path, snapshot: dict) -> None:
try:
_atomic_text(path, json.dumps(snapshot, ensure_ascii=False))
except OSError:
pass # Display telemetry failure must not terminate a possible CAD write.
except OSError as error:
# Telemetry cannot interrupt a CAD write, but the lost state must remain diagnosable.
import logging
logging.getLogger(__name__).warning('worker_progress_publish_failed path=%s error=%s', path, error)
def _decode(data: bytes) -> str:
@@ -26,7 +26,7 @@ def test_quick_part_replace_is_an_ascii_current_sheet_automatic_contract() -> No
"Comp.Orientation",
"Comp.Scale",
"QP_App.ActiveView.Query(VDM_COMPPIN, VD_ALL)",
"CmpPin.Component.UID",
"QPComponentIdentityKey(CmpPin.Component)",
"Set Connection = CmpPin.Connection",
"Set Net = Connection.Net",
"Net.UID",
+22 -1
View File
@@ -14,7 +14,7 @@ FAKES = next(ast.literal_eval(statement.value) for statement in TREE.body
for target in statement.targets))
EXTRA = r'''
Class ValueComponent
Public UID, Refdes, Orientation, Scale, Attributes, AddCount
Public UID, Refdes, Orientation, Scale, Attributes, AddCount, Selected
Private Point
Private Sub Class_Initialize()
Set Point=New TestPoint
@@ -371,6 +371,27 @@ Require InStr(QPReadUtf8(QP_Fso.BuildPath(QP_Root,"status.tsv")),"saved_ok")>0,"
''', routines_transform=_batch_readback_fixture)
def test_missing_uid_capture_restore_save_and_reopen(tmp_path):
run_vbs(tmp_path, 'part_number', '''
Dim FullChecks, Captured
FullChecks=0
Command.Add "project_path",QPProjectPath()
Comp.FindAttribute("Part Number").Value="OLD"
QPCaptureAndSelect Command,SnapshotPath
Set Captured=QPReadSnapshot(SnapshotPath)
Require Captured.Item("components").Item("0")("uid")="@REFDES|R1","fallback lost in snapshot"
Require Captured.Item("untouched").Count=0,"target incorrectly captured as untouched"
Comp.FindAttribute("Part Number").Value="NEW"
QP_BatchMode=True:QP_SessionMode=False
QP_OwnedProject=True:QP_OwnedProjectPath=QPProjectPath()
QPRestoreAfterOperatorReplace Command,SnapshotPath
QPFinishBatchItem
Require QP_App.SaveCount=1,"replacement was not saved exactly once"
Require Len(QP_App.ProjectPath)=0,"reopened project was not closed"
Require InStr(QPReadUtf8(QP_Fso.BuildPath(QP_Root,"status.tsv")),"saved_ok")>0,"missing saved readback proof"
''', before='Comp.UID=""', routines_transform=_batch_readback_fixture)
def test_non_session_no_match_closes_without_any_save(tmp_path):
run_vbs(tmp_path, 'part_number', '''
Dim FullChecks
+56 -4
View File
@@ -128,12 +128,12 @@ End Class
''') == '1234'
def test_optional_attribute_fields_degrade_to_safe_defaults(tmp_path):
def test_unreadable_display_fields_retain_missing_state(tmp_path):
output = run_vbs(tmp_path, ['QPOptionalAttributeField', 'QPReadOptionalAttributeValue'], '''
Dim Attr
Set Attr = New BrokenOptionalAttribute
WScript.Echo QPOptionalAttributeField(Attr, "color")
WScript.Echo QPOptionalAttributeField(Attr, "location_x")
WScript.Echo "color=" & QPOptionalAttributeField(Attr, "color")
WScript.Echo "x=" & QPOptionalAttributeField(Attr, "location_x")
WScript.Echo QPReadOptionalAttributeValue(Attr)
''', LOG_STUB + '''
Class BrokenOptionalAttribute
@@ -155,7 +155,7 @@ Class BrokenOptionalAttribute
End Property
End Class
''')
assert output.splitlines() == ['0', '0']
assert output.splitlines() == ['color=', 'x=']
def test_optional_component_label_read_failure_is_not_identity_failure(tmp_path):
@@ -415,6 +415,58 @@ WScript.Echo Replace(Text,vbCrLf,"")
assert output.splitlines() == ['1', 'A\tu1\tValue\tSAME\tSAME\t0\t0\t1\t2\t3\t0\t1']
@pytest.mark.parametrize('field', ['Color', 'Font', 'Size', 'Orientation', 'Visible', 'location'])
def test_unreadable_style_blocks_snapshot_and_never_writes_default(tmp_path, field):
fake = FULL_FAKE
if field == 'location':
fake = fake.replace('Function GetLocation()\n Dim Point:',
'Function GetLocation()\n If FailRead Then Err.Raise 1234,"FakeCOM","unavailable"\n Dim Point:', 1)
record_field = 'x'
else:
fake = fake.replace('Color, Font, Size, Orientation, Visible',
', '.join(x for x in ['Color', 'Font', 'Size', 'Orientation', 'Visible'] if x != field), 1)
marker = ' Private Sub Class_Initialize\n Name = "Value"'
fake = fake.replace(marker, f''' Private Stored
Property Get {field}
If FailRead Then Err.Raise 1234,"FakeCOM","unavailable"
{field}=Stored
End Property
Property Let {field}(ByVal NewValue)
Stored=NewValue:Writes=Writes+1
End Property
Private Sub Class_Initialize
Name = "Value"''', 1)
record_field = field.lower()
output = run_vbs(tmp_path, ['QPSnapshotAttribute', 'QPOptionalAttributeField', 'QPEncode',
'QPRestoreDisplay'], f'''
Dim Attr,Text,Failure,Record,Key,FailRead,Writes
FailRead=False
Set Attr=New FullAttribute
Writes=0:FailRead=True
On Error Resume Next
Text=QPSnapshotAttribute("u1",Attr)
Failure=Err.Number:Err.Clear
On Error GoTo 0
WScript.Echo CStr(Failure<>0)
FailRead=False
Set Record=CreateObject("Scripting.Dictionary")
For Each Key In Array("x","y","color","font","size","orientation","visible")
Record.Add Key,"1"
Next
Record("{record_field}")=""
On Error Resume Next
QPRestoreDisplay Attr,Record,"R1"
Failure=Err.Number:Err.Clear
On Error GoTo 0
WScript.Echo CStr(Failure<>0)
WScript.Echo Writes
''', LOG_STUB + fake + '''
Sub QPVerifyDisplay(ByRef Attr,ByRef Record,ByVal Refdes)
End Sub
''')
assert output.splitlines() == ['True', 'True', '0']
@pytest.mark.parametrize('instance', ['', 'OVERRIDE'])
def test_snapshot_preserves_base_value_separately_from_instance_override(tmp_path, instance):
output = run_vbs(tmp_path, ['QPSnapshotAttribute', 'QPOptionalAttributeField', 'QPEncode'], f'''
@@ -43,6 +43,46 @@ def test_native_readback_checks_each_unselected_attribute_once(tmp_path, target_
assert other.reads == {'Part Number': 1, 'Value': 1, 'Part Name': 1, 'Part Label': 1}
@pytest.mark.parametrize('others,changed', [(0, False), (2, False), (2, True)])
def test_legacy_readback_checks_every_unselected_component(tmp_path, others, changed):
target = Component('u1', 'R1', **{'Part Number': 'NEW', 'Part Name': 'TARGET'})
components, baseline = [target], {}
for index in range(others):
uid, refdes = f'u{index + 2}', f'R{index + 2}'
baseline[uid] = (refdes, 'OLD', 'V0', 'NAME', 'LABEL')
components.append(Component(uid, refdes, **{'Part Number': 'OLD',
'Value': 'CHANGED' if changed and index == 0 else 'V0',
'Part Name': 'NAME', 'Part Label': 'LABEL'}))
def verify():
return native.verify_replacement_readback(tmp_path / 'snapshot.tsv', components,
['M', 'project', 'OLD', 'NEW', 'sheet', 'preserve'], [['C', 'u1', 'R1']],
{c.UID for c in components}, baseline, False, None, ['u1'])
if changed:
with pytest.raises(ValueError, match='unselected component'):
verify()
else:
assert verify() == ['u1']
@pytest.mark.parametrize('count', [1, 2])
def test_missing_uid_matches_flow_into_pin_promotion(monkeypatch, count):
components = [Component('', f'R{i+1}', **{'Part Number': 'NEW', 'Part Name': 'TARGET'})
for i in range(count)]
records = [['C', f'@REFDES|R{i+1}', f'R{i+1}'] for i in range(count)]
matches = native.replacement_matches(components, records, 'NEW', False)
assert matches == [row[1] for row in records]
pins = [SimpleNamespace(Component=c, Number='1') for c in components]
for pin in pins:
pin._oleobj_ = pin
app = SimpleNamespace(ActiveView=SimpleNamespace(
Block=SimpleNamespace(PromoteSymbolNumbers=lambda *args: None),
Query=lambda *args: pins))
monkeypatch.setattr(native, 'components_on_sheet', lambda *args: components)
monkeypatch.setattr(native, 'selection', lambda *args: None)
promoted = native.promote_pin_numbers(app, SimpleNamespace(IVdCmpPin=lambda p: p), matches)
assert [pin['uid'] for pin in promoted] == matches
def test_preselection_context_does_not_query_an_unused_selection(monkeypatch):
target = Component('u1', 'R1', **{'Part Number': 'OLD', 'Value': 'V0'})
target._oleobj_ = target
+21 -1
View File
@@ -135,7 +135,8 @@ def test_repeated_force_does_not_terminate_twice(tmp_path):
from types import SimpleNamespace
from dx_productivity.trial_task_center.batch_supervisor import _force_owned_supervisor
calls = []
process = SimpleNamespace(terminate=lambda: calls.append('terminate'))
process = SimpleNamespace(terminate=lambda: calls.append('terminate'),
poll=lambda: 0 if calls else None)
journal = {'operation': 'execute_task_queue', 'batch_id': 'a' * 32, 'attempt_id': 'b' * 32,
'task_ids': ['task'], 'state': 'running'}
_force_owned_supervisor(tmp_path, journal, process)
@@ -144,6 +145,25 @@ def test_repeated_force_does_not_terminate_twice(tmp_path):
assert journal['force_state'] == 'termination_requested'
def test_force_retry_terminates_again_if_process_is_still_alive(tmp_path):
from types import SimpleNamespace
from dx_productivity.trial_task_center.batch_supervisor import _force_owned_supervisor
calls = []
process = SimpleNamespace(terminate=lambda: calls.append('terminate'), poll=lambda: None)
journal = {'operation': 'execute_task_queue', 'batch_id': 'a' * 32, 'attempt_id': 'b' * 32,
'task_ids': ['task'], 'state': 'running', 'force_state': 'termination_requested'}
_force_owned_supervisor(tmp_path, journal, process)
assert calls == ['terminate']
def test_empty_interruption_marker_is_repaired_before_force(tmp_path):
from dx_productivity.trial_task_center.stop_control import protect_interruption
marker = tmp_path / 'uncertain.flag'
marker.touch()
protect_interruption(tmp_path, 'reason=interrupted')
assert marker.read_text(encoding='utf-8') == 'reason=interrupted'
def test_force_already_performed_remains_forced_when_exit_diagnostics_fail(tmp_path):
from types import SimpleNamespace
from dx_productivity.trial_task_center.batch_supervisor import _force_owned_supervisor
+30
View File
@@ -1,6 +1,36 @@
import pytest
@pytest.mark.parametrize('content', ['{bad', '[]', '{"cad_shutdown": 5}',
'{"cad_shutdown": {"cleanup_errors": [1]}}'])
def test_corrupt_shutdown_evidence_keeps_result_and_blocks(tmp_path, monkeypatch, content):
from dx_productivity.trial_task_center import batch_resources
from dx_productivity.trial_task_center.batch_supervisor import _finish_response
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.logging_setup import configure_logging
from dx_productivity.trial_task_center.supervisor_protocol import encode
journal = {'operation': 'probe', 'batch_id': 'a' * 32}
root = tmp_path / 'batch-resources' / journal['batch_id']
root.mkdir(parents=True)
(root / 'session.json').write_text(content, encoding='utf-8')
monkeypatch.setattr(batch_resources, 'cleanup_pending_resources', lambda *args, **kwargs: ())
response = {'business_succeeded': True, 'status': 'ok', 'result': encode({'verified': True})}
with pytest.raises(TaskCenterError) as caught:
_finish_response(tmp_path, journal, response, configure_logging(tmp_path))
assert caught.value.code == 'application_shutdown_failed'
assert caught.value.completed_result == {'verified': True}
assert journal['state'] == 'blocked'
def test_failed_progress_publish_emits_warning(tmp_path, monkeypatch, caplog):
from dx_productivity.trial_task_center import worker_monitor
def fail(*args):
raise OSError('disk full')
monkeypatch.setattr(worker_monitor, '_atomic_text', fail)
worker_monitor._publish_progress(tmp_path / 'progress.json', {'stage': 'awaiting_reconciliation'})
assert 'worker_progress_publish_failed' in caplog.text
@pytest.mark.parametrize('body', [None, {}, {'status':'ok','business_succeeded':'yes','result':'bad'},
{'status':'ok','business_succeeded':True,'result':'wrong type'}])
def test_invalid_result_cannot_finish_resource_gate(tmp_path, body):