fix: release completed attempts before later failures

This commit is contained in:
阿白叔 committed 2026-10-31 09:25:30 +08:00
1 parent f0a0131aac
commit 5ed8444d5d
6 files changed
+81 -7

No files matched your search

@@ -0,0 +1,33 @@
# PR #9 生命周期复审修复
复审评论:PR #9 评论 91、92、93。阻断问题是:已完成工程的历史 attempt 仍保持 `mutation_possible`,下一工程启动前的普通异常会把整个批次送入 `wait_for_resolution`,保留 CAD/桌面并无限等待强制结束。
## 根因与修复
`BatchCadRuntime.__exit__` 原先把 `_project_attempts` 中所有历史 attempt 传给不确定性判断。成功工程在 `_checkpoint()` 后已经写入 `project-checkpoint.json` 并证明 CAD/工程关闭,但历史 attempt 文件仍然是 `mutation_possible`,因此 `can_retry_attempt()` 永远返回 False。
现在运行时只保留 `_active_attempts` 作为在途写入证据:
- `_prepare_attempts()` 成功后设置当前 generation 的 attempt 集合;
- `_checkpoint()` 完成 CAD 关闭和 checkpoint 发布后清空 `_active_attempts`;
- `__exit__` 只对当前未完成 attempt 调用 `_retain_uncertain`;
- 历史 attempt 文件、禁止重放证据和 checkpoint 审计仍保留,不会被清除或重新授权重放。
这样,已完成工程之后的下一工程备份/启动异常会正常释放自有 CAD/桌面并传播原始异常;当前 attempt 尚未获得关闭 checkpoint 时,仍然保留原有安全等待。
## 连带收口
- VBS 身份函数在真实 UID 非空时提前返回并去除首尾空格,只有 fallback 才读取 Refdes;fallback WARN 按位号去重,每次捕获按 job 重置。
- Python 超时诊断使用 `_component_uid()`,无 UID 结果显示 `@REFDES|...`。
- 进度发布失败告警按路径 15 秒节流,避免磁盘满时每秒刷写日志。
- 独立 VBS 函数入口在 fallback 告警字典未初始化时惰性创建。
## 验证
- `tests/v1_1/test_batch_runtime.py tests/v1_1/test_safe_user_stop.py tests/v1_1/test_supervisor_result.py`:**67 passed**。
- `tests/v1_1/test_accuracy_vbs_guards.py::test_missing_component_uid_uses_stable_refdes_fallback tests/v1_1/test_missing_uid_inventory.py`:**14 passed**。
- 新增回归 `test_completed_project_does_not_hold_resolution_wait_for_next_project_failure` 覆盖成功工程后下一工程启动异常,断言不进入 `waiting_for_resolution` 且不污染已完成工程的 `uncertain.flag`。
Windows 10、真实 DxDesigner 7.9.5 无 UID 工程、中央库/许可证和网络共享仍需现场验证。
冻结包已从本次代码重建,`verify_packaged_runtime.py` 通过;`QuickPartReplace.vbs` SHA256 为 `7752FD937EF1513744F49B3A529DC075D4BD81AA743460254306FAA1BC385C92`,`NativeSnapshotReader.vbs` SHA256 为 `46519AA1191DAC97A778D0F4074F2CF3AAF23667E2863A6C7E2057045FCAF099`。
+11 -2
View File
@@ -26,6 +26,7 @@ Dim QP_PinIndex
Dim QP_PinContext Dim QP_PinContext
Dim QP_ComponentUidIndex, QP_ComponentRefdesIndex, QP_ComponentLocationIndex Dim QP_ComponentUidIndex, QP_ComponentRefdesIndex, QP_ComponentLocationIndex
Dim QP_FallbackIdentityUsed Dim QP_FallbackIdentityUsed
Dim QP_FallbackIdentityWarnings
Dim QP_ComponentIndexContext Dim QP_ComponentIndexContext
Dim QP_NativeCallActive Dim QP_NativeCallActive
Dim QP_BatchMode, QP_OwnedProject, QP_BatchState, QP_BatchCode, QP_BatchMessage Dim QP_BatchMode, QP_OwnedProject, QP_BatchState, QP_BatchCode, QP_BatchMessage
@@ -71,6 +72,7 @@ Set QP_ComponentRefdesIndex = Nothing
Set QP_ComponentLocationIndex = Nothing Set QP_ComponentLocationIndex = Nothing
QP_ComponentIndexContext = "" QP_ComponentIndexContext = ""
QP_FallbackIdentityUsed = False QP_FallbackIdentityUsed = False
Set QP_FallbackIdentityWarnings = CreateObject("Scripting.Dictionary")
QP_CurrentJobId = "" QP_CurrentJobId = ""
QP_ExitCode = 0 QP_ExitCode = 0
QP_Stage = "session_startup" QP_Stage = "session_startup"
@@ -807,12 +809,18 @@ Function QPComponentIdentityKey(ByRef Comp)
If Number <> 0 Then Err.Raise vbObjectError + 872, _ If Number <> 0 Then Err.Raise vbObjectError + 872, _
"QuickPartReplace.Discovery", "component Refdes is unreadable; operation stopped before any replacement" "QuickPartReplace.Discovery", "component Refdes is unreadable; operation stopped before any replacement"
If Len(Trim(CStr(Uid))) > 0 Then If Len(Trim(CStr(Uid))) > 0 Then
QPComponentIdentityKey = CStr(Uid) QPComponentIdentityKey = Trim(CStr(Uid))
Exit Function
Else Else
QP_FallbackIdentityUsed = True QP_FallbackIdentityUsed = True
If Len(Trim(CStr(Refdes))) > 0 Then If Len(Trim(CStr(Refdes))) > 0 Then
QPComponentIdentityKey = "@REFDES|" & Trim(CStr(Refdes)) QPComponentIdentityKey = "@REFDES|" & Trim(CStr(Refdes))
QPLog QP_Root, "WARN", "component_uid_missing_using_refdes_fallback refdes=" & CStr(Refdes) If Not IsObject(QP_FallbackIdentityWarnings) Then _
Set QP_FallbackIdentityWarnings = CreateObject("Scripting.Dictionary")
If Not QP_FallbackIdentityWarnings.Exists(LCase(Trim(CStr(Refdes)))) Then
QP_FallbackIdentityWarnings.Add LCase(Trim(CStr(Refdes))), True
QPLog QP_Root, "WARN", "component_uid_missing_using_refdes_fallback refdes=" & CStr(Refdes)
End If
Else Else
Err.Raise vbObjectError + 872, "QuickPartReplace.Discovery", "component UID and Refdes are empty" Err.Raise vbObjectError + 872, "QuickPartReplace.Discovery", "component UID and Refdes are empty"
End If End If
@@ -1216,6 +1224,7 @@ Sub QPCaptureAndSelect(ByRef Command, ByVal SnapshotPath)
Dim Selectors, Selector, Uid, ValueAttr, ValueText, MatchedUids, UntouchedCount, NativeRead Dim Selectors, Selector, Uid, ValueAttr, ValueText, MatchedUids, UntouchedCount, NativeRead
QP_FallbackIdentityUsed = False QP_FallbackIdentityUsed = False
Set QP_FallbackIdentityWarnings = CreateObject("Scripting.Dictionary")
If StrComp(CStr(Command("old_part_number")), CStr(Command("new_part_number")), vbTextCompare) = 0 Then _ 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" Err.Raise vbObjectError + 829, "QuickPartReplace", "source and target must differ"
QPInvalidatePinIndex QPInvalidatePinIndex
@@ -101,6 +101,7 @@ class BatchCadRuntime:
self._project_attempts = {} self._project_attempts = {}
self._logging = None self._logging = None
self._active_evidence = None self._active_evidence = None
self._active_attempts = []
self._close_failure = None self._close_failure = None
self._close_failure_rebuild = False self._close_failure_rebuild = False
@@ -121,7 +122,10 @@ class BatchCadRuntime:
def __exit__(self, error_type, error, traceback): def __exit__(self, error_type, error, traceback):
if error is not None and self._active_evidence is not None: if error is not None and self._active_evidence is not None:
attempts = [item for values in self._project_attempts.values() for item in values] # Only the current generation can still own an in-flight CAD write.
# Earlier projects retain audit evidence but their closed checkpoint
# proves that they no longer need the live CAD/desktop wait.
attempts = list(self._active_attempts)
try: try:
self._retain_uncertain(self._active_evidence, None, attempts, error) self._retain_uncertain(self._active_evidence, None, attempts, error)
except WorkerMonitorError: except WorkerMonitorError:
@@ -254,6 +258,7 @@ class BatchCadRuntime:
'session_id': self.session_id, 'generation': self.generation, 'attempt_id': attempt_id, 'session_id': self.session_id, 'generation': self.generation, 'attempt_id': attempt_id,
'evidence_root': str(root), 'project_path': str(project), 'project_closed': True, 'evidence_root': str(root), 'project_path': str(project), 'project_closed': True,
'worker_closed': True, 'cad_pid': self.record['cad_pid'], 'cad_guid': self.record['cad_guid']}) 'worker_closed': True, 'cad_pid': self.record['cad_pid'], 'cad_guid': self.record['cad_guid']})
self._active_attempts = []
def run_worker(self, command, timeout, *, abort_event=None, cooperative_abort=False): def run_worker(self, command, timeout, *, abort_event=None, cooperative_abort=False):
from .discovery_cache import project_fingerprint from .discovery_cache import project_fingerprint
@@ -272,6 +277,7 @@ class BatchCadRuntime:
self._save() self._save()
generation = self.generation + (self.desktop is None) generation = self.generation + (self.desktop is None)
project, directory, expected = self._prepare_attempts(root, command, attempt_id, generation) project, directory, expected = self._prepare_attempts(root, command, attempt_id, generation)
self._active_attempts = list(expected)
self._ensure_desktop(abort_event) self._ensure_desktop(abort_event)
before = project_fingerprint(project, self.root) before = project_fingerprint(project, self.root)
status = internal_path(root / 'status.tsv') status = internal_path(root / 'status.tsv')
@@ -820,10 +820,10 @@ def run_native(snapshot, report):
refs = {record[2] for record in records} refs = {record[2] for record in records}
report['replacement_timeout'].update( report['replacement_timeout'].update(
component_count=len(current), component_count=len(current),
components=[dict(uid=str(c.UID), refdes=str(c.Refdes), components=[dict(uid=_component_uid(c), refdes=str(c.Refdes),
attributes={name: attribute_value(c, name) attributes={name: attribute_value(c, name)
for name in ('Part Number', 'Part Name', 'Part Label', 'Value')}) for name in ('Part Number', 'Part Name', 'Part Label', 'Value')})
for c in current if str(c.UID) in wanted or str(c.Refdes) in refs]) for c in current if _component_uid(c) in wanted or str(c.Refdes) in refs])
except Exception as error: except Exception as error:
report['replacement_timeout']['component_readback_error'] = str(error) report['replacement_timeout']['component_readback_error'] = str(error)
try: try:
@@ -9,8 +9,8 @@ from pathlib import Path
import queue import queue
import re import re
import subprocess import subprocess
import threading
import time import time
import threading
from uuid import uuid4 from uuid import uuid4
@@ -18,6 +18,9 @@ class WorkerMonitorError(subprocess.SubprocessError):
pass pass
_PROGRESS_FAILURE_LOGGED: dict[str, float] = {}
class ProgressWatch: class ProgressWatch:
def __init__(self, token: str, job_id: str, idle_timeout: float, started: float) -> None: def __init__(self, token: str, job_id: str, idle_timeout: float, started: float) -> None:
if idle_timeout <= 0: if idle_timeout <= 0:
@@ -134,7 +137,12 @@ def _publish_progress(path: Path, snapshot: dict) -> None:
except OSError as error: except OSError as error:
# Telemetry cannot interrupt a CAD write, but the lost state must remain diagnosable. # Telemetry cannot interrupt a CAD write, but the lost state must remain diagnosable.
import logging import logging
logging.getLogger(__name__).warning('worker_progress_publish_failed path=%s error=%s', path, error) now = time.monotonic()
key = str(path)
last = _PROGRESS_FAILURE_LOGGED.get(key, 0.0)
if now - last >= 15:
logging.getLogger(__name__).warning('worker_progress_publish_failed path=%s error=%s', path, error)
_PROGRESS_FAILURE_LOGGED[key] = now
def _decode(data: bytes) -> str: def _decode(data: bytes) -> str:
+18
View File
@@ -165,6 +165,24 @@ def test_two_projects_reuse_cad_and_produce_distinct_close_checkpoints(tmp_path,
assert Cad.created[0].closed and Desktop.created[0].released assert Cad.created[0].closed and Desktop.created[0].released
def test_completed_project_does_not_hold_resolution_wait_for_next_project_failure(tmp_path, monkeypatch):
import subprocess
command, _ = command_for(tmp_path)
next_command, _ = command_for(tmp_path, 'next')
runtime = worker_runtime(tmp_path, monkeypatch, lambda command, *a, **k:
subprocess.CompletedProcess(command, 0, '', ''))
with runtime:
runtime.run_worker(command, 5)
assert runtime._active_attempts == []
def fail_prepare(*args, **kwargs):
raise OSError('next project backup failed')
monkeypatch.setattr(runtime, '_prepare_attempts', fail_prepare)
with pytest.raises(OSError, match='next project backup failed'):
runtime.run_worker(next_command, 5)
assert not getattr(runtime.stop_event, 'waiting_for_resolution', False)
assert not (Path(command[3]) / 'quick-run' / 'uncertain.flag').exists()
@pytest.mark.parametrize('second_fails', [False, True]) @pytest.mark.parametrize('second_fails', [False, True])
def test_prewrite_failure_releases_old_desktop_and_retries_only_once(tmp_path, monkeypatch, second_fails): def test_prewrite_failure_releases_old_desktop_and_retries_only_once(tmp_path, monkeypatch, second_fails):
import subprocess import subprocess