fix(execution): track native read progress and retry transient library redraws
This commit is contained in:
1 parent
e74ec5bcbd
commit
911afdf1cc
7 files changed
+198
-8
No files matched your search
@@ -172,18 +172,25 @@ Sub QPNativeRequireContext(ByVal Project, ByVal Sheet, ByVal Guid)
|
||||
End Sub
|
||||
|
||||
Function QPBuildNativeSnapshotScript(ByVal Source, ByRef SelectedUids, ByVal Token, ByVal Project, ByVal Sheet, ByVal Guid, ByVal ResultPath, ByVal StopToken, ByVal Safe)
|
||||
Dim Header, Body, Names, Name, Uid, Pattern, Matches
|
||||
Dim Header, Body, Names, Name, Uid, Pattern, Matches, MonitorJob
|
||||
Header = Left(Source, InStr(Source, "Set QP_Fso =") - 1)
|
||||
Set Pattern = CreateObject("VBScript.RegExp")
|
||||
Pattern.Global = True
|
||||
Pattern.MultiLine = True
|
||||
Pattern.Pattern = "^Const (VDM_COMP|VDM_COMPPIN|VD_ALL) = [^\r\n]*\r?\n"
|
||||
Header = Pattern.Replace(Header, "")
|
||||
MonitorJob = QP_ExpectedJobId
|
||||
If QP_SessionMode Then MonitorJob = QP_MonitorJobId
|
||||
Body = Header & vbCrLf & "Dim QP_NR_Selected, QP_NR_Text, QP_NR_Code, QP_NR_Source, QP_NR_Description, QP_NR_Safe" & vbCrLf & _
|
||||
"Dim QP_NR_MonitorJob, QP_NR_CurrentJob, QP_NR_ParentSequence, QP_NR_Sequence, QP_NR_LastProgress" & vbCrLf & _
|
||||
"Set QP_Fso=CreateObject(""Scripting.FileSystemObject"")" & vbCrLf & _
|
||||
"QP_Root=" & QPNativeExpression(QP_Root) & vbCrLf & _
|
||||
"QP_AttemptToken=" & QPNativeExpression(StopToken) & vbCrLf & _
|
||||
"QP_NR_Safe=" & CStr(CBool(Safe)) & vbCrLf & _
|
||||
"QP_NR_MonitorJob=" & QPNativeExpression(MonitorJob) & vbCrLf & _
|
||||
"QP_NR_CurrentJob=" & QPNativeExpression(QP_ExpectedJobId) & vbCrLf & _
|
||||
"QP_NR_ParentSequence=" & CStr(CLng(QP_ProgressSequence) + 1) & vbCrLf & _
|
||||
"QP_NR_Sequence=0:QP_NR_LastProgress=-1" & vbCrLf & _
|
||||
"Set QP_NR_Selected=CreateObject(""Scripting.Dictionary"")" & vbCrLf
|
||||
For Each Uid In SelectedUids.Keys
|
||||
Body = Body & "QP_NR_Selected.Add " & QPNativeExpression(Uid) & ",True" & vbCrLf
|
||||
@@ -207,12 +214,26 @@ Function QPBuildNativeSnapshotScript(ByVal Source, ByRef SelectedUids, ByVal Tok
|
||||
Next
|
||||
Body = Body & vbCrLf & "Sub QPLog(ByVal Root,ByVal Level,ByVal Message)" & vbCrLf & "End Sub" & vbCrLf & _
|
||||
"Sub QPProgress(ByVal Stage,ByVal Done,ByVal Total)" & vbCrLf & _
|
||||
" Dim StopPath" & vbCrLf & _
|
||||
" Dim StopPath,Elapsed,CurrentTime,ProgressPath,Stream,SafeFlag" & vbCrLf & _
|
||||
" If QP_NR_Safe And Len(QP_AttemptToken)>0 Then" & vbCrLf & _
|
||||
" StopPath=QP_Fso.BuildPath(QP_Root,""monitor-"" & QP_AttemptToken & "".stop"")" & vbCrLf & _
|
||||
" If QP_Fso.FileExists(StopPath) Then" & vbCrLf & _
|
||||
" If Trim(QPReadUtf8(StopPath))=QP_AttemptToken Then Err.Raise vbObjectError+860,""QuickPartReplace.SafeStop"",""native read stopped at safe boundary""" & vbCrLf & _
|
||||
" End If" & vbCrLf & " End If" & vbCrLf & "End Sub" & vbCrLf
|
||||
" End If" & vbCrLf & " End If" & vbCrLf & _
|
||||
" If Len(QP_AttemptToken)=0 Then Exit Sub" & vbCrLf & _
|
||||
" CurrentTime=Timer:Elapsed=CurrentTime-QP_NR_LastProgress" & vbCrLf & _
|
||||
" If Elapsed<0 Then Elapsed=Elapsed+86400" & vbCrLf & _
|
||||
" If QP_NR_LastProgress>=0 And Elapsed<1 And Not (Total>0 And Done=Total) Then Exit Sub" & vbCrLf & _
|
||||
" SafeFlag=0:If QP_NR_Safe Then SafeFlag=1" & vbCrLf & _
|
||||
" QP_NR_Sequence=QP_NR_Sequence+1" & vbCrLf & _
|
||||
" ProgressPath=QP_Fso.BuildPath(QP_Root,""monitor-"" & QP_AttemptToken & "".native-progress"")" & vbCrLf & _
|
||||
" On Error Resume Next" & vbCrLf & _
|
||||
" Set Stream=QP_Fso.CreateTextFile(ProgressPath,True,False)" & vbCrLf & _
|
||||
" Stream.WriteLine ""DX_NATIVE_PROGRESS"" & vbTab & QP_AttemptToken & vbTab & QP_NR_MonitorJob & vbTab & _" & vbCrLf & _
|
||||
" CStr(QP_NR_ParentSequence) & vbTab & QP_NR_CurrentJob & vbTab & CStr(QP_NR_Sequence) & vbTab & _" & vbCrLf & _
|
||||
" CStr(Done) & vbTab & CStr(Total) & vbTab & CStr(SafeFlag)" & vbCrLf & _
|
||||
" Stream.Close:Err.Clear" & vbCrLf & " On Error GoTo 0" & vbCrLf & _
|
||||
" QP_NR_LastProgress=CurrentTime" & vbCrLf & "End Sub" & vbCrLf
|
||||
QPBuildNativeSnapshotScript = Body
|
||||
End Function
|
||||
|
||||
|
||||
@@ -132,7 +132,17 @@ def wait_for_library_rows(callback, target, timeout=30, stable_for=0.45, poll_in
|
||||
stable_since = None
|
||||
latest = []
|
||||
while time.monotonic() < deadline:
|
||||
latest = callback()
|
||||
try:
|
||||
latest = callback()
|
||||
except KeyError as error:
|
||||
# During DxDataBook redraw, pywinauto can see a destroyed row
|
||||
# whose UIA control_type is None. Reacquire the read-only list;
|
||||
# never carry its earlier stability interval across that gap.
|
||||
if error.args != (None,):
|
||||
raise
|
||||
previous = stable_since = None
|
||||
time.sleep(poll_interval)
|
||||
continue
|
||||
signature = tuple(tuple(str(value) for value in columns) for _, columns in latest)
|
||||
now = time.monotonic()
|
||||
if signature != previous:
|
||||
|
||||
@@ -8,6 +8,7 @@ STAGES = {
|
||||
'find_components': '定位目标位号', 'index_pins': '建立引脚索引',
|
||||
'snapshot_attributes': '记录原始属性', 'capture': '采集替换前快照',
|
||||
'capture_untouched': '记录未选中器件状态', 'verify_untouched': '核验未选中器件',
|
||||
'native_snapshot_read': '采集并核验器件完整状态',
|
||||
'before_native': '准备原生替换', 'native_replace': '执行原生替换',
|
||||
'restore_preflight': '检查属性恢复条件',
|
||||
'before_restore_transaction': '准备恢复属性',
|
||||
|
||||
@@ -28,6 +28,8 @@ class ProgressWatch:
|
||||
self.idle_timeout = idle_timeout
|
||||
self.last_progress = started
|
||||
self.sequence = 0
|
||||
self.native_sequence = 0
|
||||
self.native_progress_frames = 0
|
||||
self.stop_requested = False
|
||||
self.stage = 'starting'
|
||||
self.done = 0
|
||||
@@ -55,16 +57,45 @@ class ProgressWatch:
|
||||
if current_job != self.current_job_id:
|
||||
self.current_job_id = current_job
|
||||
self.stage_seconds = {}
|
||||
self.native_progress_frames = 0
|
||||
self.started = self.stage_started = now
|
||||
self.stage = fields[4]
|
||||
if fields[4] != self.stage:
|
||||
self.stage_seconds[self.stage] = self.stage_seconds.get(self.stage, 0.0) + max(0.0, now - self.stage_started)
|
||||
self.stage_started = now
|
||||
self.sequence = sequence
|
||||
self.native_sequence = 0
|
||||
self.last_progress = now
|
||||
self.stage, self.done, self.total, self.safe_stop = fields[4], done, total, bool(safe)
|
||||
return True
|
||||
|
||||
def accept_native(self, line: bytes, now: float) -> bool:
|
||||
"""Accept only the sidecar of the currently authorized blocking read.
|
||||
|
||||
The parent stdout sequence identifies one native call. A sidecar can
|
||||
update liveness and counts; it cannot advance stdout or grant safety.
|
||||
"""
|
||||
if self.stage != 'native_snapshot_read' or not line.endswith(b'\n'):
|
||||
return False
|
||||
try:
|
||||
fields = line.decode('ascii').strip().split('\t')
|
||||
if len(fields) != 9 or fields[:3] != ['DX_NATIVE_PROGRESS', self.token, self.job_id]:
|
||||
return False
|
||||
if int(fields[3]) != self.sequence or fields[4] != self.current_job_id:
|
||||
return False
|
||||
sequence, done, total, safe = map(int, fields[5:])
|
||||
if not self.native_sequence < sequence <= 2**31 - 1:
|
||||
return False
|
||||
if done < 0 or total < 0 or (total and done > total) or safe != int(self.safe_stop):
|
||||
return False
|
||||
except (ValueError, UnicodeError):
|
||||
return False
|
||||
self.native_sequence = sequence
|
||||
self.native_progress_frames += 1
|
||||
self.last_progress = now
|
||||
self.done, self.total = done, total
|
||||
return True
|
||||
|
||||
def action(self, now: float) -> str | None:
|
||||
idle = now - self.last_progress
|
||||
if not self.stop_requested and idle >= self.idle_timeout:
|
||||
@@ -80,6 +111,7 @@ class ProgressWatch:
|
||||
stages[self.stage] = stages.get(self.stage, 0.0) + max(0.0, now - self.stage_started)
|
||||
return {name: getattr(self, name) for name in ('token', 'sequence', 'stage', 'done', 'total', 'safe_stop', 'stop_requested')} | {
|
||||
'job_id': self.current_job_id,
|
||||
'native_progress_frames': self.native_progress_frames,
|
||||
'elapsed_seconds': max(0.0, now - self.started), 'stage_seconds': stages}
|
||||
|
||||
|
||||
@@ -165,6 +197,7 @@ def run_monitored_process(command: tuple[str, ...], idle_timeout: float, *, abor
|
||||
ready = root / f'monitor-{token}.ready'
|
||||
stop = root / f'monitor-{token}.stop'
|
||||
progress_path = root / 'worker-progress.json'
|
||||
native_progress_path = root / f'monitor-{token}.native-progress'
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
watch = ProgressWatch(token, job_id, idle_timeout, time.monotonic())
|
||||
owned = _OwnedWorkers(token, {command[0], command[4]})
|
||||
@@ -227,6 +260,15 @@ def run_monitored_process(command: tuple[str, ...], idle_timeout: float, *, abor
|
||||
receive(*messages.get_nowait())
|
||||
except queue.Empty:
|
||||
pass
|
||||
if watch.stage == 'native_snapshot_read':
|
||||
line = b''
|
||||
try:
|
||||
with native_progress_path.open('rb') as native:
|
||||
line = native.read(2048)
|
||||
except OSError:
|
||||
pass # Missing/temporarily locked telemetry cannot prove progress.
|
||||
if watch.accept_native(line, time.monotonic()):
|
||||
_publish_progress(progress_path, watch.snapshot())
|
||||
if process.poll() is not None:
|
||||
break
|
||||
action = watch.action(time.monotonic())
|
||||
|
||||
@@ -56,6 +56,59 @@ def test_replayed_sequence_does_not_extend_deadline():
|
||||
assert watch.action(160) == 'request_stop'
|
||||
|
||||
|
||||
def native_frame(sequence=1, *, parent=1, current='job', safe=1):
|
||||
return f'DX_NATIVE_PROGRESS\ttoken\tjob\t{parent}\t{current}\t{sequence}\t1\t57\t{safe}\r\n'.encode()
|
||||
|
||||
|
||||
def test_native_progress_extends_only_its_live_read_without_changing_stdout_sequence():
|
||||
watch = worker_monitor.ProgressWatch('token', 'job', 150, 0)
|
||||
assert watch.accept(frame(1, stage='native_snapshot_read'), 1)
|
||||
for n, now in enumerate((100, 200, 300), 1):
|
||||
assert watch.accept_native(native_frame(n), now)
|
||||
assert watch.action(now) is None
|
||||
assert watch.sequence == 1
|
||||
assert watch.snapshot(now=301)['done'] == 1
|
||||
assert watch.accept(frame(2, stage='verify'), 302)
|
||||
assert not watch.accept_native(native_frame(4), 450)
|
||||
assert watch.action(452) == 'request_stop'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('invalid', [
|
||||
native_frame().replace(b'token', b'old'), native_frame(parent=0),
|
||||
native_frame().replace(b'\tjob\t1\t', b'\tforeign\t1\t', 1),
|
||||
native_frame(current='other'), native_frame(safe=0), native_frame(sequence=0),
|
||||
native_frame().replace(b'\t1\t57\t', b'\t58\t57\t'),
|
||||
native_frame().replace(b'DX_NATIVE_PROGRESS', b'DX_PROGRESS'), native_frame()[:-2],
|
||||
b'partial',
|
||||
])
|
||||
def test_stale_or_partial_native_progress_cannot_hide_a_stalled_read(invalid):
|
||||
watch = worker_monitor.ProgressWatch('token', 'job', 150, 0)
|
||||
assert watch.accept(frame(1, stage='native_snapshot_read'), 1)
|
||||
assert not watch.accept_native(invalid, 150)
|
||||
assert watch.action(151) == 'request_stop'
|
||||
|
||||
|
||||
def test_native_progress_replay_cannot_extend_deadline_or_make_mutation_safe():
|
||||
watch = worker_monitor.ProgressWatch('token', 'job', 150, 0)
|
||||
assert watch.accept(frame(1, stage='native_snapshot_read', safe=0), 1)
|
||||
assert watch.accept_native(native_frame(safe=0), 10)
|
||||
assert not watch.accept_native(native_frame(safe=0), 155)
|
||||
assert not watch.accept_native(native_frame(sequence=2, safe=1), 155)
|
||||
assert not watch.safe_stop
|
||||
assert watch.action(160) == 'request_stop'
|
||||
|
||||
|
||||
def test_native_progress_is_reset_and_rebound_for_each_session_job():
|
||||
watch = worker_monitor.ProgressWatch('token', 'job', 150, 0)
|
||||
assert watch.accept(frame(1, stage='native_snapshot_read'), 1)
|
||||
assert watch.accept_native(native_frame(), 2)
|
||||
assert watch.accept(b'DX_PROGRESS\ttoken\tjob\t2\tnative_snapshot_read\t0\t57\t1\tsecond\n', 3)
|
||||
assert watch.native_progress_frames == 0
|
||||
assert not watch.accept_native(native_frame(sequence=2), 4)
|
||||
assert watch.accept_native(native_frame(parent=2, current='second'), 5)
|
||||
assert watch.native_progress_frames == 1 and watch.sequence == 2
|
||||
|
||||
|
||||
def toy_worker(tmp_path: Path, body: str):
|
||||
script = tmp_path / 'toy.py'
|
||||
script.write_text('''
|
||||
@@ -88,6 +141,24 @@ print('DONE',flush=True)
|
||||
assert not progress['stop_requested']
|
||||
|
||||
|
||||
def test_native_sidecar_progress_outlives_idle_timeout_without_stdout_heartbeats(tmp_path):
|
||||
command = toy_worker(tmp_path, '''
|
||||
print(f'DX_PROGRESS\\t{token}\\t{job}\\t1\\tnative_snapshot_read\\t0\\t57\\t1',flush=True)
|
||||
for n in range(1, 7):
|
||||
(root/f'monitor-{token}.native-progress').write_text(
|
||||
f'DX_NATIVE_PROGRESS\\t{token}\\t{job}\\t1\\t{job}\\t{n}\\t{n}\\t57\\t1\\r\\n',encoding='ascii')
|
||||
time.sleep(.35)
|
||||
print('NATIVE_READ_FINISHED',flush=True)
|
||||
''')
|
||||
result = worker_monitor.run_monitored_process(command, 1.0)
|
||||
assert result.returncode == 0
|
||||
assert 'NATIVE_READ_FINISHED' in result.stdout
|
||||
progress = json.loads((tmp_path / 'worker-progress.json').read_text())
|
||||
assert not progress['stop_requested']
|
||||
assert progress['done'] == 6 and progress['sequence'] == 1
|
||||
assert 0 < progress.get('native_progress_frames', 0) <= 6
|
||||
|
||||
|
||||
def test_idle_worker_can_acknowledge_cooperative_stop(tmp_path):
|
||||
command = toy_worker(tmp_path, '''
|
||||
while not stop.exists(): time.sleep(0.01)
|
||||
|
||||
@@ -162,7 +162,7 @@ End Function
|
||||
'''
|
||||
|
||||
|
||||
@pytest.mark.parametrize('fault', ['', 'foreign_guid', 'cancel', 'missing_target'])
|
||||
@pytest.mark.parametrize('fault', ['', 'foreign_guid', 'cancel', 'missing_target', 'progress_locked', 'session', 'cancel_unsafe'])
|
||||
def test_generated_native_script_collects_complete_readonly_frame(tmp_path, fault):
|
||||
source = tmp_path / 'combined.vbs'
|
||||
assert ADAPTER.is_file(), 'native snapshot adapter is missing'
|
||||
@@ -170,13 +170,17 @@ def test_generated_native_script_collects_complete_readonly_frame(tmp_path, faul
|
||||
generated, result = tmp_path/'generated.vbs', tmp_path/'result.tsv'
|
||||
selected = 'missing' if fault == 'missing_target' else 'u1'
|
||||
guid = 'FOREIGN' if fault == 'foreign_guid' else 'OWNED'
|
||||
if fault == 'cancel':
|
||||
if fault in {'cancel', 'cancel_unsafe'}:
|
||||
(tmp_path/'monitor-stop-token.stop').write_text('stop-token', encoding='ascii')
|
||||
if fault == 'progress_locked':
|
||||
(tmp_path/'monitor-stop-token.native-progress').mkdir()
|
||||
run(tmp_path, '''
|
||||
Dim QP_Root,Selected,Text
|
||||
QP_Root=''' + quote(tmp_path) + '''
|
||||
QP_ExpectedJobId="job":QP_ProgressSequence=8
|
||||
QP_SessionMode=''' + str(fault == 'session') + ''':QP_MonitorJobId="initial-job"
|
||||
Set Selected=CreateObject("Scripting.Dictionary"): Selected.Add "''' + selected + '''",True
|
||||
Text=QPBuildNativeSnapshotScript(QPReadUtf8(''' + quote(source) + '''),Selected,"nonce","c:\\board.prj","MAIN:1","''' + guid + '''",''' + quote(result) + ''',"stop-token",True)
|
||||
Text=QPBuildNativeSnapshotScript(QPReadUtf8(''' + quote(source) + '''),Selected,"nonce","c:\\board.prj","MAIN:1","''' + guid + '''",''' + quote(result) + ''',"stop-token",''' + str(fault != 'cancel_unsafe') + ''')
|
||||
QPWriteUtf8 ''' + quote(generated) + ''',Text
|
||||
''')
|
||||
text = generated.read_text(encoding='utf-8-sig')
|
||||
@@ -187,13 +191,21 @@ QPWriteUtf8 ''' + quote(generated) + ''',Text
|
||||
completed = subprocess.run(['cscript.exe', '//nologo', str(generated)], capture_output=True, text=True, timeout=15)
|
||||
assert completed.returncode == 0, completed.stdout + completed.stderr
|
||||
actual = result.read_bytes().decode('utf-8-sig')
|
||||
if fault:
|
||||
if fault in {'foreign_guid', 'cancel', 'missing_target'}:
|
||||
assert actual.startswith('ERROR\tnonce\t')
|
||||
assert 'END\t' not in actual
|
||||
if fault == 'cancel':
|
||||
assert 'QuickPartReplace.SafeStop' in actual
|
||||
else:
|
||||
assert actual == FRAME
|
||||
if fault == 'progress_locked':
|
||||
return # Telemetry failure cannot invalidate a complete read proof.
|
||||
progress = tmp_path/'monitor-stop-token.native-progress'
|
||||
assert progress.exists(), 'native host did not publish its bounded progress'
|
||||
fields = progress.read_text(encoding='ascii').strip().split('\t')
|
||||
assert fields[:5] == ['DX_NATIVE_PROGRESS', 'stop-token',
|
||||
'initial-job' if fault == 'session' else 'job', '9', 'job']
|
||||
assert int(fields[5]) > 0 and fields[6:] == ['2', '2', '0' if fault == 'cancel_unsafe' else '1']
|
||||
|
||||
|
||||
def run_composed_fixture(tmp_path, body, *, native_app=NATIVE_FAKES, with_adapter=True, routines_transform=None):
|
||||
|
||||
@@ -37,3 +37,36 @@ def test_unready_target_times_out_without_becoming_a_valid_selection(monkeypatch
|
||||
with pytest.raises(TimeoutError, match='Native target'):
|
||||
native.wait_for_native_target(lambda: state, 'NEW', 'lib:RES', 1,
|
||||
timeout=.5, stable_for=.2, poll_interval=.1)
|
||||
|
||||
|
||||
def test_library_redraw_restarts_stability_before_accepting_target(monkeypatch):
|
||||
now = clock(monkeypatch)
|
||||
rows = [('row', ['RESISTOR', 'NEW', 'lib:RES'])]
|
||||
attempts = [0]
|
||||
def read():
|
||||
attempts[0] += 1
|
||||
if attempts[0] == 2:
|
||||
raise KeyError(None) # pywinauto wrapper sees a destroyed UIA row.
|
||||
return rows
|
||||
assert native.wait_for_library_rows(read, 'NEW', timeout=1,
|
||||
stable_for=.2, poll_interval=.1) == rows
|
||||
assert now[0] >= .4
|
||||
|
||||
|
||||
def test_persistent_destroyed_library_rows_time_out_before_selection(monkeypatch):
|
||||
clock(monkeypatch)
|
||||
def read():
|
||||
raise KeyError(None)
|
||||
with pytest.raises(TimeoutError, match='DxDataBook'):
|
||||
native.wait_for_library_rows(read, 'NEW', timeout=.5,
|
||||
stable_for=.2, poll_interval=.1)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('error', [KeyError('Part Number'), RuntimeError('wrong window')])
|
||||
def test_other_library_read_errors_are_not_silently_retried(monkeypatch, error):
|
||||
now = clock(monkeypatch)
|
||||
def read():
|
||||
raise error
|
||||
with pytest.raises(type(error)) as raised:
|
||||
native.wait_for_library_rows(read, 'NEW', timeout=.5, poll_interval=.1)
|
||||
assert raised.value is error and now[0] == 0
|
||||
Reference in new issue
Block a user