fix(execution): track native read progress and retry transient library redraws

This commit is contained in:
阿白叔 committed 2026-10-19 13:45:39 +08:00
1 parent e74ec5bcbd
commit 911afdf1cc
7 files changed
+198 -8

No files matched your search

@@ -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)
+16 -4
View File
@@ -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