From 0714c7753f612638b0aa9c5ee4ca3947af3dbcda 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: Mon, 19 Oct 2026 09:41:41 +0800 Subject: [PATCH] perf(execution): consolidate full checks at commit boundaries --- .../dxdesigner795/QuickPartReplace.vbs | 106 ++++++++++++++---- .../trial_task_center/recovery.py | 2 +- tests/integration/test_quick_value_modes.py | 98 ++++++++++++++++ tests/v1_1/test_accuracy_vbs_guards.py | 59 +++++++++- 4 files changed, 241 insertions(+), 24 deletions(-) diff --git a/integration/dxdesigner795/QuickPartReplace.vbs b/integration/dxdesigner795/QuickPartReplace.vbs index 0ee1a28..d3e0a3f 100644 --- a/integration/dxdesigner795/QuickPartReplace.vbs +++ b/integration/dxdesigner795/QuickPartReplace.vbs @@ -1036,8 +1036,13 @@ Function QPNativeReportShowsMutation(ByVal ReportPath) End Function Sub QPRequireSnapshotContext(ByVal SnapshotPath) - Dim Records, Meta + Dim Records Set Records = QPReadSnapshot(SnapshotPath) + QPRequireRecordsContext Records +End Sub + +Sub QPRequireRecordsContext(ByRef Records) + Dim Meta Set Meta = Records.Item("meta") If QPCanonicalPath(CStr(Meta("project_path"))) <> QPCanonicalPath(QPProjectPath()) Or _ CStr(Meta("sheet_name")) <> QPSheetIdentity() Then _ @@ -1186,17 +1191,49 @@ Sub QPCaptureAndSelect(ByRef Command, ByVal SnapshotPath) End Sub Function QPUntouchedComponent(ByRef Comp) - QPUntouchedComponent = "U" & vbTab & QPEncode(CStr(Comp.UID)) & vbTab & _ - QPEncode(CStr(Comp.Refdes)) & vbTab & QPEncode(QPEffectiveComponentAttribute(Comp, "Part Number")) & vbTab & _ - QPEncode(QPEffectiveComponentAttribute(Comp, "Value")) & vbTab & _ - QPEncode(QPEffectiveComponentAttribute(Comp, "Part Name")) & vbTab & _ - QPEncode(QPEffectiveComponentAttribute(Comp, "Part Label")) & vbCrLf - QPUntouchedComponent = QPUntouchedComponent & "G" & vbTab & QPEncode(CStr(Comp.UID)) & _ - vbTab & QPEncode(QPUntouchedFullState(Comp)) & vbCrLf + Dim State, Identity, Fields + State = QPUntouchedFullState(Comp) + Identity = QPUntouchedIdentity(State) + Fields = Split(Identity, vbTab) + QPUntouchedComponent = Identity & vbCrLf & "G" & vbTab & Fields(1) & _ + vbTab & QPEncode(State) & vbCrLf +End Function + +Function QPUntouchedIdentity(ByVal State) + Dim Values, Seen, Line, Fields, Header, Name, Value + Set Values = CreateObject("Scripting.Dictionary") + Set Seen = CreateObject("Scripting.Dictionary") + Values.CompareMode = vbTextCompare + Seen.CompareMode = vbTextCompare + For Each Name In Array("Part Number", "Value", "Part Name", "Part Label") + Values.Add Name, "" + Next + Header = "" + For Each Line In Split(State, vbCrLf) + If Len(Line) > 0 Then + Fields = Split(Line, vbTab) + If Fields(0) = "C" Then + Header = "U" & vbTab & Fields(1) & vbTab & Fields(2) + ElseIf Fields(0) = "A" Then + Name = QPDecode(Fields(2)) + If Values.Exists(Name) Then + If Seen.Exists(Name) Then Err.Raise vbObjectError + 874, _ + "QuickPartReplace.Target", "duplicate unselected identity attribute" + Seen.Add Name, True + Value = Fields(4) + If Len(Value) = 0 Then Value = Fields(3) + Values(Name) = Value + End If + End If + End If + Next + QPUntouchedIdentity = Header & vbTab & Values("Part Number") & vbTab & _ + Values("Value") & vbTab & Values("Part Name") & vbTab & Values("Part Label") End Function Function QPUntouchedFullState(ByRef Comp) - Dim Point, Pins, Connections, Attr, AttributeText, Result + Dim Point, Pins, Connections, Attr, AttributeText, Result, Uid + Uid = CStr(Comp.UID) Set Point = Comp.GetLocation() Set Pins = QPComponentPins(Comp) If Pins.Count = 0 Then @@ -1204,15 +1241,15 @@ Function QPUntouchedFullState(ByRef Comp) ' still propagate. Selected replacement symbols continue to require pins. Connections = "NO_PINS" Else - Connections = QPConnectionSignature(Comp) + Connections = QPConnectionSignatureFromPins(Comp, Pins) End If - Result = "C" & vbTab & QPEncode(CStr(Comp.UID)) & vbTab & QPEncode(CStr(Comp.Refdes)) & _ + Result = "C" & vbTab & QPEncode(Uid) & vbTab & QPEncode(CStr(Comp.Refdes)) & _ vbTab & QPEncode(CStr(Point.X)) & vbTab & QPEncode(CStr(Point.Y)) & _ vbTab & QPEncode(CStr(Comp.Orientation)) & vbTab & QPEncode(CStr(Comp.Scale)) & _ vbTab & QPEncode(Connections) & vbCrLf AttributeText = "" For Each Attr In Comp.Attributes - AttributeText = AttributeText & QPSnapshotAttribute(CStr(Comp.UID), Attr) + AttributeText = AttributeText & QPSnapshotAttribute(Uid, Attr) Next QPUntouchedFullState = Result & QPSortSnapshotLines(AttributeText) End Function @@ -1359,7 +1396,7 @@ Function QPSortSnapshotLines(ByVal Text) End Function Function QPSnapshotAttribute(ByVal ComponentUid, ByRef Attr) - Dim Instance + Dim Instance, Point, ErrorNumber, ErrorDescription Dim LocationX Dim LocationY Dim Color @@ -1369,8 +1406,16 @@ Function QPSnapshotAttribute(ByVal ComponentUid, ByRef Attr) Dim Visible Instance = Attr.InstanceValue - LocationX = QPOptionalAttributeField(Attr, "location_x") - LocationY = QPOptionalAttributeField(Attr, "location_y") + On Error Resume Next + Set Point = Attr.GetLocation() + LocationX = CStr(Point.X) + LocationY = CStr(Point.Y) + ErrorNumber = Err.Number + ErrorDescription = Err.Description + Err.Clear + On Error GoTo 0 + If ErrorNumber <> 0 Then Err.Raise ErrorNumber, "QuickPartReplace.Snapshot", _ + "Cannot capture " & CStr(Attr.Name) & ".location: " & ErrorDescription Color = QPOptionalAttributeField(Attr, "color") Font = QPOptionalAttributeField(Attr, "font") Size = QPOptionalAttributeField(Attr, "size") @@ -1435,7 +1480,10 @@ Sub QPRestoreAfterOperatorReplace(ByRef Command, ByVal SnapshotPath) QPProgress "restore_preflight", 0, 0 Set Records = QPReadSnapshot(SnapshotPath) QPRequireCommandSnapshot Command, SnapshotPath - QPVerifyUntouched Records + ' 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 Set Meta = Records.Item("meta") If QPCanonicalPath(CStr(Meta("project_path"))) <> QPCanonicalPath(QPProjectPath()) Or _ CStr(Meta("sheet_name")) <> QPSheetIdentity() Then _ @@ -1544,7 +1592,7 @@ Sub QPRestorePlans(ByRef Command, ByRef Records, ByRef Plans) QPProgress "restore_attributes", Index + 1, Plans.Count Next QPVerifyRestoredPlans Command, Records, Plans, ValueStates - QPVerifyUntouched Records + If Not QP_BatchMode Then QPVerifyUntouched Records End Sub Sub QPVerifyRestoredPlans(ByRef Command, ByRef Records, ByRef Plans, ByRef ValueStates) @@ -1657,7 +1705,19 @@ Sub QPRecoverSavedJob(ByRef Command, ByVal SnapshotPath) Err.Clear On Error GoTo 0 If ErrorNumber = 0 Then - QPWriteStatus QP_Root, QP_CurrentJobId, "restored_ok", "recovery_verified", "Saved replacement already passes all restoration checks; no CAD writes." + If QP_BatchMode Then + If QP_SessionMode Then Err.Raise vbObjectError + 865, _ + "QuickPartReplace.Recovery", "read-only recovery cannot reuse a project session" + ' A fresh owned recovery session has already verified the disk state. + ' Closing without saving avoids a second save/reopen cycle for no writes. + QPRequireCommandSnapshot Command, SnapshotPath + QPCloseBatchProject CStr(Command("project_path")), False + QP_BatchMode = False + QPWriteStatus QP_Root, QP_CurrentJobId, "restored_ok", "recovery_saved_verified", _ + "Saved replacement verified from disk and owned project closed without additional saving." + Else + QPWriteStatus QP_Root, QP_CurrentJobId, "restored_ok", "recovery_verified", "Saved replacement already passes all restoration checks; no CAD writes." + End If Else If ErrorNumber <> vbObjectError + 833 And ErrorNumber <> vbObjectError + 834 And _ ErrorNumber <> vbObjectError + 837 And ErrorNumber <> vbObjectError + 840 And _ @@ -2054,7 +2114,7 @@ Sub QPRequireCommandSnapshot(ByRef Command, ByVal SnapshotPath) Dim Records, Meta Set Records = QPReadSnapshot(SnapshotPath) Set Meta = Records.Item("meta") - QPRequireSnapshotContext SnapshotPath + QPRequireRecordsContext Records If CStr(Meta("old_part_number")) <> CStr(Command("old_part_number")) Or _ CStr(Meta("new_part_number")) <> CStr(Command("new_part_number")) Then _ Err.Raise vbObjectError + 830, "QuickPartReplace", "snapshot rule mismatch" @@ -2398,6 +2458,11 @@ End Function Function QPConnectionSignature(ByRef Comp) Dim Pins + Set Pins = QPComponentPins(Comp) + QPConnectionSignature = QPConnectionSignatureFromPins(Comp, Pins) +End Function + +Function QPConnectionSignatureFromPins(ByRef Comp, ByRef Pins) Dim PinIndexKey Dim PinReadCount Dim CmpPin @@ -2418,7 +2483,6 @@ Function QPConnectionSignature(ByRef Comp) Set Signatures = CreateObject("Scripting.Dictionary") QP_Stage = "query_pins" - Set Pins = QPComponentPins(Comp) PinReadCount = 0 For Each PinIndexKey In Pins.Keys Set CmpPin = Pins.Item(CStr(PinIndexKey)) @@ -2487,7 +2551,7 @@ Function QPConnectionSignature(ByRef Comp) For Index = 0 To UBound(Keys) Result = Result & Signatures.Item(CStr(Keys(Index))) & vbLf Next - QPConnectionSignature = Result + QPConnectionSignatureFromPins = Result End Function Sub QPAddSortedSignature(ByRef Signatures, ByVal PinKey, ByVal PinValue) diff --git a/src/dx_productivity/trial_task_center/recovery.py b/src/dx_productivity/trial_task_center/recovery.py index 7f38420..0fdc98d 100644 --- a/src/dx_productivity/trial_task_center/recovery.py +++ b/src/dx_productivity/trial_task_center/recovery.py @@ -240,7 +240,7 @@ def recover(preparer, task_id, projects, rules, *, copy_part_number_to_value=Fal progress = preparer.progress(task_id, projects, rules, copy_part_number_to_value=copy_part_number_to_value) message = ('磁盘工程与替换前快照一致,只读核验工程已关闭,已准备新的执行编号;尚未再次替换,请确认后执行。' if state == 'retry_ready' else - '已核验并恢复本项任务记录,属性已保存并重开回读,工程已关闭;没有重复执行原生替换。' + '已从磁盘核验本项结果并恢复任务记录,工程已关闭;没有重复执行原生替换。' if after[0][2] == 'recovery_saved_verified' else '已核验并恢复本项任务记录;没有重复执行原生替换。若补做了属性恢复,请保存当前工程。') return QuickRunStepResult(root / 'QuickPartReplace.vbs', root / 'command.tsv', root / 'status.tsv', diff --git a/tests/integration/test_quick_value_modes.py b/tests/integration/test_quick_value_modes.py index b1000c1..b230cd1 100644 --- a/tests/integration/test_quick_value_modes.py +++ b/tests/integration/test_quick_value_modes.py @@ -1,5 +1,6 @@ import ast from pathlib import Path +import re import subprocess import pytest @@ -229,6 +230,103 @@ Require QP_App.TransactionCount=0,"identity failure must precede CAD writes" ''', after=change) +def _batch_readback_fixture(routines, *, fault=''): + # Exercise real restore/finish/guards, replacing only the external open and + # command transport with an in-memory CAD-shaped application. + routines = re.sub(r'(?ms)^Function QPReadCommand\([^\n]*\n.*?^End Function', '''Function QPReadCommand(ByVal Path) + Set QPReadCommand=Command +End Function''', routines) + routines = re.sub(r'(?ms)^Sub QPEnsureProject\([^\n]*\n.*?^End Sub', '''Sub QPEnsureProject(ByRef App, ByVal TargetPath) + App.ProjectPath=TargetPath + App.CloseCount=0 + QP_OwnedProject=True + QP_OwnedProjectPath=TargetPath + ''' + ('Set Attr=Other.FindAttribute("Value"): Attr.Value="DRIFT"' if fault == 'after_reopen' else '') + ''' +End Sub''', routines) + injection = 'FullChecks=FullChecks+1\n' + if fault == 'before_save': + injection += 'If FullChecks=1 Then Other.FindAttribute("Value").Value="DRIFT"\n' + return routines.replace('Sub QPVerifyUntouched(ByRef Records)\n', + 'Sub QPVerifyUntouched(ByRef Records)\n' + injection) + + +@pytest.mark.parametrize('fault', ['', 'before_save', 'after_reopen']) +def test_owned_batch_checks_full_state_at_save_and_disk_boundaries(tmp_path, fault): + run_vbs(tmp_path, 'part_number', ''' +Dim FullChecks +FullChecks=0 +Command.Add "project_path",QPProjectPath() +QP_BatchMode=True: QP_SessionMode=True +QP_SessionToken=String(32,"b") +QP_OwnedProject=True: QP_OwnedProjectPath=QPProjectPath() +QPRestoreAfterOperatorReplace Command,SnapshotPath +Require FullChecks=0,"full scans repeated before the commit boundary" +On Error Resume Next +QPFinishBatchItem +Failure=Err.Number +Err.Clear +On Error GoTo 0 +''' + (''' +Require Failure=0,"valid batch failed" +Require FullChecks=2,"expected one full check before save and one after reopen" +Require QP_App.SaveCalled,"valid batch did not save" +Require InStr(QPReadUtf8(QP_Fso.BuildPath(QP_Root,"project-session-result.tsv")),"saved_ok")>0,"no verified result" +''' if not fault else ''' +Require Failure<>0,"unselected drift passed the commit guard" +Require Not QP_Fso.FileExists(QP_Fso.BuildPath(QP_Root,"project-session-result.tsv")),"failure published a completion" +Require QP_App.SaveCalled=''' + ('True' if fault == 'after_reopen' else 'False') + ''',"wrong save boundary" +Require QP_BatchSaveCommitted=''' + ('True' if fault == 'after_reopen' else 'False') + ''',"saved uncertainty marker is wrong" +'''), after=''' +Dim Other +Set Other=New ValueComponent +Other.UID="unselected": Other.Refdes="R2": Other.Orientation=0: Other.Scale=1 +Set Ignored=AddValueAttr(Other,"Value","SAFE") +QP_App.Components.Add Other,True +QPWriteUtf8 SnapshotPath,QPReadUtf8(SnapshotPath) & QPUntouchedComponent(Other) +''', routines_transform=lambda routines: _batch_readback_fixture(routines, fault=fault)) + + +@pytest.mark.parametrize('refuse_close', [False, True]) +def test_verified_disk_recovery_closes_without_saving_or_reopening(tmp_path, refuse_close): + run_vbs(tmp_path, 'part_number', ''' +Command.Add "recovery_part_name","NEW_NAME" +Command.Add "recovery_part_label","NEW_LABEL" +Command.Add "project_path",QPProjectPath() +QPRestoreAfterOperatorReplace Command,SnapshotPath +QPWriteUtf8 QP_Fso.BuildPath(QP_Root,"status.tsv"),"job_id" & vbTab & "state" & vbTab & "code" & vbTab & "message" & vbCrLf +QP_BatchMode=True +QP_OwnedProject=True: QP_OwnedProjectPath=QPProjectPath() +QP_App.RefuseClose=''' + ('True' if refuse_close else 'False') + ''' +On Error Resume Next +QPRecoverSavedJob Command,SnapshotPath +Failure=Err.Number +Err.Clear +On Error GoTo 0 +Require Not QP_App.SaveCalled,"read-only disk recovery saved again" +''' + (''' +Require Failure<>0,"unconfirmed recovery close was accepted" +Require InStr(QPReadUtf8(QP_Fso.BuildPath(QP_Root,"status.tsv")),"recovery_saved_verified")=0,"failure published proof" +''' if refuse_close else ''' +Require Failure=0,"valid disk recovery failed" +Require Not QP_BatchMode,"read-only recovery will trigger a duplicate finish/save" +Require QP_App.CloseCount=1 And Len(QP_App.ProjectPath)=0,"verified recovery did not close" +Require Not QP_OwnedProject,"closed recovery retains stale ownership" +Require InStr(QPReadUtf8(QP_Fso.BuildPath(QP_Root,"status.tsv")),"recovery_saved_verified")>0,"missing disk proof" +''')) + + +def test_command_snapshot_validation_reads_the_file_once(tmp_path): + def count_reads(routines): + return routines.replace('Function QPReadSnapshot(ByVal Path)\n', + 'Function QPReadSnapshot(ByVal Path)\n SnapshotReads=SnapshotReads+1\n') + run_vbs(tmp_path, 'part_number', ''' +Dim SnapshotReads +SnapshotReads=0 +QPRequireCommandSnapshot Command,SnapshotPath +Require SnapshotReads=1,"same boundary parsed its snapshot twice" +''', routines_transform=count_reads) + + @pytest.mark.parametrize('mode', ['preserve', 'part_label', 'part_number']) def test_recovery_repairs_attributes_without_native_replace(tmp_path, mode): run_vbs(tmp_path, mode, ''' diff --git a/tests/v1_1/test_accuracy_vbs_guards.py b/tests/v1_1/test_accuracy_vbs_guards.py index 6098616..979db04 100644 --- a/tests/v1_1/test_accuracy_vbs_guards.py +++ b/tests/v1_1/test_accuracy_vbs_guards.py @@ -310,11 +310,66 @@ Const VDM_COMPPIN = 4096 Const VD_ALL = 0 ''' -UNTOUCHED_ROUTINES = ['QPUntouchedComponent', '?QPUntouchedFullState', 'QPVerifyUntouched', +UNTOUCHED_ROUTINES = ['QPUntouchedComponent', '?QPUntouchedFullState', '?QPUntouchedIdentity', 'QPVerifyUntouched', 'QPReadSnapshot', 'QPWriteUtf8', 'QPReadUtf8', 'QPEncode', 'QPDecode', 'QPFindCurrentAttribute', 'QPEffectiveAttributeValue', 'QPEffectiveComponentAttribute', 'QPSnapshotAttribute', 'QPOptionalAttributeField', 'QPSortSnapshotLines', - 'QPConnectionSignature', 'QPComponentPins', 'QPInvalidatePinIndex', 'QPAddSortedSignature'] + 'QPConnectionSignature', '?QPConnectionSignatureFromPins', 'QPComponentPins', 'QPInvalidatePinIndex', 'QPAddSortedSignature'] + + +def test_snapshot_attribute_reads_its_location_once(tmp_path): + fake = FULL_FAKE.replace('Function GetLocation()\n Dim Point:', + 'Function GetLocation()\n LocationReads=LocationReads+1\n Dim Point:', 1) + output = run_vbs(tmp_path, ['QPSnapshotAttribute', 'QPOptionalAttributeField', 'QPEncode'], ''' +Dim Attr, Text, LocationReads +LocationReads=0 +Set Attr=New FullAttribute +Text=QPSnapshotAttribute("u1",Attr) +WScript.Echo LocationReads +WScript.Echo Replace(Text,vbCrLf,"") +''', LOG_STUB + fake) + assert output.splitlines() == ['1', 'A\tu1\tValue\tSAME\tSAME\t0\t0\t1\t2\t3\t0\t1'] + + +def test_unselected_identity_comes_from_the_same_complete_attribute_read(tmp_path): + output = run_vbs(tmp_path, UNTOUCHED_ROUTINES, ''' +Dim Comp, Attr, Text, Lines, Names, Values, Item +Set QP_App=New FakeApp +Set Comp=New FullComponent +Comp.UID="u2": Comp.Refdes="R2": Comp.RaiseOnFind=True +Names=Array("Part Number","Value","Part Name","Part Label") +Values=Array("00123","BASE","NAME","LABEL") +For Item=0 To 3 + Set Attr=New FullAttribute + Attr.Name=Names(Item): Attr.Value=Values(Item): Attr.InstanceValue="" + If Item=1 Then Attr.InstanceValue="OVERRIDE" + Comp.Attributes.Add Attr,True +Next +Text=QPUntouchedComponent(Comp) +Lines=Split(Text,vbCrLf) +WScript.Echo Lines(0) +''', LOG_STUB + FULL_FAKE) + assert output == 'U\tu2\tR2\t00123\tOVERRIDE\tNAME\tLABEL' + + +def test_unselected_pin_snapshot_reuses_the_queried_pin_collection(tmp_path): + fake = FULL_FAKE.replace('Function QPSheetIdentity()\n', + 'Function QPSheetIdentity()\n ContextReads=ContextReads+1\n') + output = run_vbs(tmp_path, UNTOUCHED_ROUTINES, ''' +Dim Comp, Pin, Net, Conn, Text, ContextReads +ContextReads=0 +Set QP_App=New FakeApp +Set Comp=New FullComponent: Comp.UID="u2": Comp.Refdes="R2" +Set Net=New FakeNet: Net.UID="net1": Net.LogicalNetName="GND" +Set Conn=New FakeConnection: Set Conn.Net=Net +Set Pin=New FakePin: Set Pin.Component=Comp: Set Pin.Connection=Conn: Pin.Number="1" +Pin.X=0: Pin.Y=0 +QP_App.ActiveView.Pins.Add Pin,True +Text=QPUntouchedFullState(Comp) +WScript.Echo ContextReads +WScript.Echo CStr(CBool(InStr(Text,"net1|GND")>0)) +''', LOG_STUB + fake) + assert output.splitlines() == ['2', 'True'] @pytest.mark.parametrize(('mutation', 'expected'), [