perf(execution): use native-host full snapshots for owned batches

This commit is contained in:
阿白叔 committed 2026-10-19 11:07:13 +08:00
1 parent 2f6060dfe3
commit 81f34683ea
9 files changed
+261 -14

No files matched your search

+1 -1
View File
@@ -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',
+119
View File
@@ -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)]
+46
View File
@@ -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'