From 81f34683ea24e089cda2245b0175fc5c7d357549 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 11:07:13 +0800 Subject: [PATCH] perf(execution): use native-host full snapshots for owned batches --- .../dxdesigner795/NativeSnapshotReader.vbs | 31 +++++ .../dxdesigner795/QuickPartReplace.vbs | 48 +++++-- packaging/DxPartReplace.spec | 4 + .../trial_task_center/quick_run.py | 7 +- .../trial_task_center/recovery.py | 3 +- .../trial_task_center/worker_runtime.py | 15 +++ tests/v1_1/test_accuracy_vbs_guards.py | 2 +- tests/v1_1/test_native_snapshot_reader.py | 119 ++++++++++++++++++ tests/v1_1/test_native_worker_runtime.py | 46 +++++++ 9 files changed, 261 insertions(+), 14 deletions(-) create mode 100644 src/dx_productivity/trial_task_center/worker_runtime.py create mode 100644 tests/v1_1/test_native_worker_runtime.py diff --git a/integration/dxdesigner795/NativeSnapshotReader.vbs b/integration/dxdesigner795/NativeSnapshotReader.vbs index ffb9754..d2c856c 100644 --- a/integration/dxdesigner795/NativeSnapshotReader.vbs +++ b/integration/dxdesigner795/NativeSnapshotReader.vbs @@ -46,6 +46,37 @@ Function QPNativeCommandPathSupported(ByVal Path) QPNativeCommandPathSupported = (Len(Path) > 0) End Function +Function QPTryNativeVerifyUntouched(ByRef Records) + Dim Selected, Record, Index, Actual + QPTryNativeVerifyUntouched = False + QPRequireRecordsContext Records + Set Selected = CreateObject("Scripting.Dictionary") + For Index = 0 To Records("components").Count - 1 + Set Record = Records("components").Item(CStr(Index)) + Selected.Add CStr(Record("uid")), True + Next + Set Actual = QPNativeReadUntouched(Selected) + If Actual Is Nothing Then Exit Function + QPRequireRecordsContext Records + QPCompareNativeUntouched Records, Actual + QPTryNativeVerifyUntouched = True +End Function + +Sub QPCompareNativeUntouched(ByRef Records, ByRef Actual) + Dim Baseline, FullBaseline, Rows, Uid, Expected + Set Baseline = Records("untouched") + Set FullBaseline = Records("untouched_full") + Set Rows = Actual("rows") + If Actual("total") <> Baseline.Count + Records("components").Count Or Rows.Count <> Baseline.Count Then _ + QPNativeReadInvalid "component count changed outside selected targets" + For Each Uid In Baseline.Keys + If Not Rows.Exists(Uid) Or Not FullBaseline.Exists(Uid) Then QPNativeReadInvalid "unselected component missing" + Expected = CStr(Baseline(Uid)) & vbCrLf & "G" & vbTab & QPEncode(Uid) & vbTab & _ + QPEncode(CStr(FullBaseline(Uid))) & vbCrLf + If Rows(Uid) <> Expected Then QPNativeReadInvalid "unselected component changed" + Next +End Sub + Function QPParseNativeSnapshot(ByVal Text, ByVal Token, ByVal Project, ByVal Sheet, ByRef SelectedUids) Dim Lines, Fields, Last, Index, Uid, Identity, State, Pair, Rows, Result, Total Set Rows = CreateObject("Scripting.Dictionary") diff --git a/integration/dxdesigner795/QuickPartReplace.vbs b/integration/dxdesigner795/QuickPartReplace.vbs index 1f1757a..ff12829 100644 --- a/integration/dxdesigner795/QuickPartReplace.vbs +++ b/integration/dxdesigner795/QuickPartReplace.vbs @@ -1114,7 +1114,7 @@ Sub QPCaptureAndSelect(ByRef Command, ByVal SnapshotPath) Dim PartNumber Dim Snapshot Dim Index - Dim Selectors, Selector, Uid, ValueAttr, ValueText, MatchedUids, UntouchedCount + Dim Selectors, Selector, Uid, ValueAttr, ValueText, MatchedUids, UntouchedCount, NativeRead 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" @@ -1188,15 +1188,26 @@ Sub QPCaptureAndSelect(ByRef Command, ByVal SnapshotPath) Set Comp = Matches.Item(CStr(Index)) MatchedUids.Add CStr(Comp.UID), True Next + Set NativeRead = Nothing + If QPUseNativeSnapshot() Then + QPRequireProject Command + Set NativeRead = QPNativeReadUntouched(MatchedUids) + End If UntouchedCount = 0 - For Each Comp In Components - If Not MatchedUids.Exists(CStr(Comp.UID)) 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 + If NativeRead Is Nothing Then + For Each Comp In Components + If Not MatchedUids.Exists(CStr(Comp.UID)) 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 + If NativeRead("total") <> Components.Count Then _ + Err.Raise vbObjectError + 875, "QuickPartReplace.NativeRead", "component count changed during capture" + Snapshot = Snapshot & CStr(NativeRead("text")) + End If QPWriteUtf8 SnapshotPath, Snapshot For Each Comp In Components @@ -1212,6 +1223,22 @@ Sub QPCaptureAndSelect(ByRef Command, ByVal SnapshotPath) QPLog QP_Root, "INFO", "awaiting_native_replace count=" & Matches.Count End Sub +Function QPUseNativeSnapshot() + Dim Reader, Number + QPUseNativeSnapshot = False + If Not QP_BatchMode Or Not QP_OwnedProject Then Exit Function + If Len(CStr(CreateObject("WScript.Shell").Environment("PROCESS")("DXPART_DESKTOP"))) = 0 Then Exit Function + On Error Resume Next + Set Reader = GetRef("QPNativeReadUntouched") + Number = Err.Number + Err.Clear + On Error GoTo 0 + If Number <> 0 Then Exit Function + If QPCanonicalPath(QP_OwnedProjectPath) <> QPProjectPath() Then _ + Err.Raise vbObjectError + 875, "QuickPartReplace.NativeRead", "native reader does not own the active project" + QPUseNativeSnapshot = True +End Function + Function QPUntouchedComponent(ByRef Comp) Dim State, Identity, Fields State = QPUntouchedFullState(Comp) @@ -1294,6 +1321,9 @@ Sub QPVerifyUntouched(ByRef Records) ' Read new component/pin proxies after each native mutation, restore or reopen. QPInvalidatePinIndex QPInvalidateComponentIndex + If QPUseNativeSnapshot() Then + If QPTryNativeVerifyUntouched(Records) Then Exit Sub + End If Set Components = QP_App.ActiveView.Query(VDM_COMP, VD_ALL) Matched = 0 Total = 0 diff --git a/packaging/DxPartReplace.spec b/packaging/DxPartReplace.spec index 1d155af..2467616 100644 --- a/packaging/DxPartReplace.spec +++ b/packaging/DxPartReplace.spec @@ -21,6 +21,10 @@ legacy_runtime_datas = [ str(project_root / "integration" / "dxdesigner795" / "QuickPartReplace.vbs"), "legacy-runtime/dxdesigner795", ), + ( + str(project_root / "integration" / "dxdesigner795" / "NativeSnapshotReader.vbs"), + "legacy-runtime/dxdesigner795", + ), ] a = Analysis( diff --git a/src/dx_productivity/trial_task_center/quick_run.py b/src/dx_productivity/trial_task_center/quick_run.py index b140599..195fd18 100644 --- a/src/dx_productivity/trial_task_center/quick_run.py +++ b/src/dx_productivity/trial_task_center/quick_run.py @@ -21,6 +21,7 @@ from uuid import uuid4 from .errors import TaskCenterError from .models import ProjectRecord, ProjectStatus, RuleRecord from .retention import maintain_quick_run_storage, rotate_text_log +from .worker_runtime import copy_worker_script DONE_STATES = frozenset({"restored_ok", "saved_ok", "no_match"}) @@ -119,7 +120,7 @@ class QuickRunPreparer: log_path = root / "quick-part-replace.log" root.mkdir(parents=True, exist_ok=True) _assert_no_pending_status(status_path, log_path) - shutil.copyfile(source, script_path) + copy_worker_script(source, script_path) if sheet_targets is not None: manifest_path = root / "sheets.tsv" manifest_path.write_text(_sheet_manifest_text(selected_projects, sheet_targets), encoding="utf-8", newline="") @@ -254,7 +255,7 @@ class QuickRunPreparer: ) source = self._required_script_source() if source.resolve() != handoff.script_path.resolve(): - shutil.copyfile(source, handoff.script_path) + copy_worker_script(source, handoff.script_path) commands = _read_commands(handoff.command_path) command_options = _read_command_options(handoff.command_path) statuses = _read_status_details(handoff.status_path) @@ -373,7 +374,7 @@ class QuickRunPreparer: else: source = self._required_script_source() if source.resolve() != handoff.script_path.resolve(): - shutil.copyfile(source, handoff.script_path) + copy_worker_script(source, handoff.script_path) commands = _read_commands(handoff.command_path) before = _read_status_details(handoff.status_path) selected_command = _next_unfinished_command(commands, before) diff --git a/src/dx_productivity/trial_task_center/recovery.py b/src/dx_productivity/trial_task_center/recovery.py index 0fdc98d..82d72bb 100644 --- a/src/dx_productivity/trial_task_center/recovery.py +++ b/src/dx_productivity/trial_task_center/recovery.py @@ -176,7 +176,8 @@ def recover(preparer, task_id, projects, rules, *, copy_part_number_to_value=Fal if _recovery_hashes(audit / 'evidence-before') != evidence_before or _recovery_hashes(root) != evidence_before: raise TaskCenterError('quick_run_recovery', '备份期间执行证据变化,已停止。') script = worker / 'QuickPartReplace.vbs' - shutil.copyfile(preparer._required_script_source(), script) + from .worker_runtime import copy_worker_script + copy_worker_script(preparer._required_script_source(), script) shutil.copyfile(snapshot, worker / snapshot.name) (worker / 'recovery.request').write_text(job_id, encoding='ascii') option_fields = (selected_mode, selected_custom_value, '1' if selected_sync_nc else '0', selected_base_mode) diff --git a/src/dx_productivity/trial_task_center/worker_runtime.py b/src/dx_productivity/trial_task_center/worker_runtime.py new file mode 100644 index 0000000..bccd3ae --- /dev/null +++ b/src/dx_productivity/trial_task_center/worker_runtime.py @@ -0,0 +1,15 @@ +"""Compose the worker with its optional read-only native snapshot adapter.""" +from pathlib import Path +import shutil + + +def copy_worker_script(source: Path, destination: Path) -> None: + source, destination = Path(source), Path(destination) + if source.resolve() == destination.resolve(): + return + shutil.copyfile(source, destination) + adapter = source.with_name('NativeSnapshotReader.vbs') + if adapter.is_file(): + with destination.open('ab') as output: + output.write(b'\r\n') + output.write(adapter.read_bytes()) diff --git a/tests/v1_1/test_accuracy_vbs_guards.py b/tests/v1_1/test_accuracy_vbs_guards.py index b9b9ba6..a824f02 100644 --- a/tests/v1_1/test_accuracy_vbs_guards.py +++ b/tests/v1_1/test_accuracy_vbs_guards.py @@ -310,7 +310,7 @@ Const VDM_COMPPIN = 4096 Const VD_ALL = 0 ''' -UNTOUCHED_ROUTINES = ['QPUntouchedComponent', '?QPUntouchedFullState', '?QPUntouchedIdentity', 'QPVerifyUntouched', +UNTOUCHED_ROUTINES = ['QPUntouchedComponent', '?QPUntouchedFullState', '?QPUntouchedIdentity', 'QPVerifyUntouched', '?QPUseNativeSnapshot', 'QPReadSnapshot', 'QPWriteUtf8', 'QPReadUtf8', 'QPEncode', 'QPDecode', 'QPFindCurrentAttribute', 'QPEffectiveAttributeValue', 'QPEffectiveComponentAttribute', 'QPSnapshotAttribute', 'QPOptionalAttributeField', 'QPSortSnapshotLines', diff --git a/tests/v1_1/test_native_snapshot_reader.py b/tests/v1_1/test_native_snapshot_reader.py index 013b6fc..de8fd64 100644 --- a/tests/v1_1/test_native_snapshot_reader.py +++ b/tests/v1_1/test_native_snapshot_reader.py @@ -85,6 +85,36 @@ End If assert output.splitlines() == expected +@pytest.mark.parametrize('mutation', ['', 'geometry', 'unselected_uid', 'missing_unselected']) +def test_native_comparison_keeps_complete_unselected_baseline(tmp_path, mutation): + text = FRAME + if mutation == 'geometry': + text = text.replace('R2%00090%00090', 'R2%000920%00090') + elif mutation == 'unselected_uid': + text = text.replace('u2', 'u3') + elif mutation == 'missing_unselected': + text = 'NR1\tnonce\tc:\\board.prj\tMAIN:1\r\nEND\tnonce\t1\r\n' + path = tmp_path/'actual.tsv' + path.write_bytes(text.encode('ascii')) + state = tmp_path/'state.tsv' + state.write_bytes(b'C\tu2\tR2\t0\t0\t0\t1\tNO_PINS\r\n') + output = run(tmp_path, ''' +Dim Selected,Actual,Records,Components,Identities,FullStates,Failure +Set Selected=CreateObject("Scripting.Dictionary"):Selected.Add "u1",True +Set Actual=QPParseNativeSnapshot(QPReadUtf8(''' + quote(path) + '''),"nonce","c:\\board.prj","MAIN:1",Selected) +Set Components=CreateObject("Scripting.Dictionary"):Components.Add "0","selected" +Set Identities=CreateObject("Scripting.Dictionary"):Identities.Add "u2","U" & vbTab & "u2" & vbTab & "R2" & vbTab & vbTab & vbTab & vbTab +Set FullStates=CreateObject("Scripting.Dictionary"):FullStates.Add "u2",QPReadUtf8(''' + quote(state) + ''') +Set Records=CreateObject("Scripting.Dictionary") +Records.Add "components",Components:Records.Add "untouched",Identities:Records.Add "untouched_full",FullStates +On Error Resume Next +QPCompareNativeUntouched Records,Actual +Failure=Err.Number +WScript.Echo CStr(Failure<>0) +''') + assert output == ('True' if mutation else 'False') + + NATIVE_FAKES = guards.FULL_FAKE[guards.FULL_FAKE.index('Class FakePoint'):guards.FULL_FAKE.index('Function QPProjectPath()')] + ''' Class OwnedNativeApp Public ActiveView @@ -164,3 +194,92 @@ QPWriteUtf8 ''' + quote(generated) + ''',Text assert 'QuickPartReplace.SafeStop' in actual else: assert actual == FRAME + + +def run_composed_fixture(tmp_path, body, *, native_app=NATIVE_FAKES, with_adapter=True, routines_transform=None): + source = MAIN.read_text(encoding='ascii') + if with_adapter: + source += '\n' + ADAPTER.read_text(encoding='ascii') + declarations = source[:source.index('On Error Resume Next\nQPBootstrapSession')] + names = re.findall(r'(?mi)^(?:Function|Sub) (\w+)\(', source) + routines = '\n'.join(re.search(rf'(?mi)^(Function|Sub) {name}\([^\n]*\n[\s\S]*?^End \1\s*$', source)[0] for name in names) + if routines_transform: + routines = routines_transform(routines) + script = tmp_path/'client.vbs' + script.write_text(declarations + '\nQP_Root=' + quote(tmp_path) + '\nSet QP_App=MakeNativeFake()\n' + body + '\n' + routines + '\n' + native_app, encoding='ascii') + result = subprocess.run(['cscript.exe', '//nologo', str(script)], capture_output=True, text=True, timeout=15) + assert result.returncode == 0, result.stdout + result.stderr + return [line for line in result.stdout.splitlines() if not line.startswith('DX_PROGRESS\t')] + + +@pytest.mark.parametrize('fault', ['', 'unsupported_path', 'command_failed', 'missing_result', 'stale_result', 'read_error']) +def test_native_reader_requires_proof_after_dispatch_without_silent_fallback(tmp_path, fault): + execute = ''' + Function ExecuteCommand(ByVal Command) + Dim File,Token,Path,Text + NativeDispatchCalls=NativeDispatchCalls+1 + ExecuteCommand=(NativeFault<>"command_failed") + If NativeFault="command_failed" Or NativeFault="missing_result" Then Exit Function + For Each File In QP_Fso.GetFolder(QP_Root).Files + If Left(File.Name,12)="native-read-" And QP_Fso.GetExtensionName(File.Name)="vbs" Then + Token=Mid(File.Name,13,Len(File.Name)-16) + Path=Left(File.Path,Len(File.Path)-4) & ".tsv" + End If + Next + Text=Replace(QPReadUtf8(''' + quote(tmp_path/'literal.tsv') + '''),"nonce",Token) + If NativeFault="stale_result" Then Text=Replace(Text,Token,"old-token") + If NativeFault="read_error" Then Text="ERROR" & vbTab & Token & vbTab & "1234" & vbTab & "FakeCOM" & vbTab & "read denied" & vbCrLf + QPWriteUtf8 Path,Text + End Function +''' + native_app = NATIVE_FAKES.replace(' Function Guid()\n', execute + ' Function Guid()\n', 1) + (tmp_path/'literal.tsv').write_bytes(FRAME.encode('ascii')) + output = run_composed_fixture(tmp_path, ''' +Dim Selected,Actual,Failure,NativeDispatchCalls,NativeFault +NativeDispatchCalls=0:NativeFault="''' + fault + '''" +QP_AttemptToken=String(32,"a") +Set Selected=CreateObject("Scripting.Dictionary"):Selected.Add "u1",True +On Error Resume Next +Set Actual=QPNativeReadUntouched(Selected) +Failure=Err.Number +Err.Clear +On Error GoTo 0 +WScript.Echo NativeDispatchCalls +WScript.Echo CStr(Failure<>0) +If NativeFault="read_error" Then WScript.Echo CStr(Failure=1234) +If NativeFault="" Then WScript.Echo Actual("total") +If NativeFault="unsupported_path" Then WScript.Echo CStr(Actual Is Nothing) +''', native_app=native_app, routines_transform=(lambda code: re.sub( + r'(?ms)^Function QPNativeCommandPathSupported\([^\n]*\n.*?^End Function', + 'Function QPNativeCommandPathSupported(ByVal Path)\n QPNativeCommandPathSupported=False\nEnd Function', code) + ) if fault == 'unsupported_path' else None) + expected = ['0', 'False', 'True'] if fault == 'unsupported_path' else ['1', 'True' if fault else 'False'] + if fault == 'read_error': + expected.append('True') + if not fault: + expected.append('2') + assert output == expected + + +@pytest.mark.parametrize(('batch', 'owned', 'desktop', 'adapter', 'wrong_owner', 'enabled', 'failed'), [ + (False, True, True, True, False, False, False), + (True, False, True, True, False, False, False), + (True, True, False, True, False, False, False), + (True, True, True, False, False, False, False), + (True, True, True, True, False, True, False), + (True, True, True, True, True, False, True), +]) +def test_native_reader_gate_requires_owned_private_batch( + tmp_path, batch, owned, desktop, adapter, wrong_owner, enabled, failed): + output = run_composed_fixture(tmp_path, ''' +Dim Enabled,Failure +QP_BatchMode=''' + str(batch) + ''':QP_OwnedProject=''' + str(owned) + ''' +QP_OwnedProjectPath="c:\\''' + ('other' if wrong_owner else 'board') + '''.prj" +CreateObject("WScript.Shell").Environment("PROCESS")("DXPART_DESKTOP")="''' + ('dx-test' if desktop else '') + '''" +On Error Resume Next +Enabled=QPUseNativeSnapshot() +Failure=Err.Number +WScript.Echo CStr(CBool(Enabled)) +WScript.Echo CStr(Failure<>0) +''', with_adapter=adapter) + assert output == [str(enabled), str(failed)] diff --git a/tests/v1_1/test_native_worker_runtime.py b/tests/v1_1/test_native_worker_runtime.py new file mode 100644 index 0000000..7d8c165 --- /dev/null +++ b/tests/v1_1/test_native_worker_runtime.py @@ -0,0 +1,46 @@ +"""Compose the default native adapter while preserving custom worker scripts.""" +import importlib +from pathlib import Path + +import pytest + + +ROOT = Path(__file__).resolve().parents[2] + + +@pytest.mark.parametrize('with_adapter', [False, True]) +def test_runtime_composition_preserves_source_and_adds_only_its_sibling(tmp_path, with_adapter): + module = ROOT / 'src/dx_productivity/trial_task_center/worker_runtime.py' + assert module.is_file(), 'worker runtime composer is missing' + copy_worker = importlib.import_module('dx_productivity.trial_task_center.worker_runtime').copy_worker_script + source = tmp_path/'source/QuickPartReplace.vbs' + source.parent.mkdir() + source.write_bytes(b"' custom worker\r\n") + if with_adapter: + source.with_name('NativeSnapshotReader.vbs').write_bytes(b"' native adapter\r\n") + target = tmp_path/'worker.vbs' + copy_worker(source, target) + assert source.read_bytes() == b"' custom worker\r\n" + expected = b"' custom worker\r\n" + (b"\r\n' native adapter\r\n" if with_adapter else b'') + assert target.read_bytes() == expected + copy_worker(source, target) + assert target.read_bytes() == expected + + +def test_default_composed_worker_compiles_without_starting_cad(tmp_path): + module = ROOT / 'src/dx_productivity/trial_task_center/worker_runtime.py' + assert module.is_file(), 'worker runtime composer is missing' + import re + import subprocess + copy_worker = importlib.import_module('dx_productivity.trial_task_center.worker_runtime').copy_worker_script + target = tmp_path/'worker.vbs' + copy_worker(ROOT/'integration/dxdesigner795/QuickPartReplace.vbs', target) + source = target.read_text(encoding='ascii') + declarations = source[:source.index('On Error Resume Next\nQPBootstrapSession')] + names = re.findall(r'(?mi)^(?:Function|Sub) (\w+)\(', source) + assert 'QPNativeReadUntouched' in names + code = '\n'.join(re.search(rf'(?mi)^(Function|Sub) {name}\([^\n]*\n[\s\S]*?^End \1\s*$', source)[0] for name in names) + target.write_text(declarations + '\n' + code + '\nWScript.Echo "PARSED"\n', encoding='ascii') + result = subprocess.run(['cscript.exe', '//nologo', str(target)], capture_output=True, text=True, timeout=15) + assert result.returncode == 0, result.stdout + result.stderr + assert result.stdout.strip() == 'PARSED'