fix: recover uncertain native failures and reopen long project paths safely

This commit is contained in:
阿白叔 committed 2026-10-15 17:49:10 +08:00
1 parent 7f0ec29d31
commit d832a1c736
15 files changed
+355 -36

No files matched your search

+19
View File
@@ -60,6 +60,25 @@ def run_queue(service, task, stop=None):
return service.execute_quick_run_queue(task.task_id, expected_item=expected, stop_event=stop or Event())
def test_native_mutation_failure_stops_before_next_batch_step(tmp_path):
service, task, calls = setup_queue(tmp_path, ('batch_failed', 'saved_ok'))
original_worker = service._quick_run_preparer._process_runner
def failed_after_mutation(command, timeout):
root = Path(command[3])
job = command[-1]
with (root / 'status.tsv').open('a', encoding='utf-8') as stream:
stream.write(f'{job}\tawaiting_native_replace\t\tsnapshot captured\n')
(root / f'snapshot-{job}.tsv.native.json').write_text(
json.dumps({'ok': False, 'stage': 'pin_promotion_started'}), encoding='utf-8')
return original_worker(command, timeout)
service._quick_run_preparer._process_runner = failed_after_mutation
with pytest.raises(TaskCenterError) as raised:
run_queue(service, task)
assert raised.value.code == 'quick_run_uncertain'
assert len(calls) == 1
assert (tmp_path / 'data/quick-run/uncertain.flag').exists()
@pytest.mark.parametrize('states', [('no_match',) * 20, ('no_match', 'saved_ok', 'no_match', 'saved_ok')])
def test_queue_continues_after_misses_and_successes(tmp_path, states):
service, task, calls = setup_queue(tmp_path, states)
@@ -0,0 +1,132 @@
import json
from pathlib import Path
import pytest
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.logging_setup import configure_logging
from dx_productivity.trial_task_center.service import TaskCenterService
from dx_productivity.trial_task_center.store import TaskStore
@pytest.fixture
def failed_native(tmp_path):
store = TaskStore(tmp_path / 'tasks.db')
service = TaskCenterService(store, configure_logging(tmp_path / 'data'))
path = tmp_path / 'board.prj'
path.touch()
task = store.create_task('native failed')
project = store.sync_projects(task.task_id, tmp_path, (path,))[0]
project = store.set_project_selected(project.project_id, True)
store.bind_project_task(task.task_id, project.project_id, 'batch', 0)
service.add_rule(task.task_id, 'OLD', 'NEW')
facade = service.for_project_task(task.task_id)
handoff = facade._quick_run_preparer.prepare(task.task_id, (project,), store.list_rules(task.task_id))
job = handoff.command_path.read_text(encoding='utf-8').splitlines()[1].split('\t')[1]
handoff.status_path.write_text('job_id\tstate\tcode\tmessage\n'
f'{job}\tawaiting_native_replace\t\tprepared\n'
f'{job}\tbatch_failed\t-2147220665\tfailed project closed without saving; native rollback not executed\n', encoding='utf-8')
root = handoff.command_path.parent
snapshot = root / f'snapshot-{job}.tsv'
snapshot.write_text('original snapshot evidence')
report = Path(str(snapshot) + '.native.json')
report.write_text(json.dumps({'ok': False, 'stage': 'pin_promotion_started', 'replaced_uids': ['uid']}))
service.quick_run_progress(task.task_id)
yield service, store, task.task_id, handoff, report
store.close()
def test_failed_after_native_mutation_is_interrupted_and_retry_does_not_archive(failed_native):
service, store, task_id, handoff, report = failed_native
context = service.task_context(task_id)
assert context.interrupted and service.has_interrupted_quick_run(task_id)
originals = {p: p.read_bytes() for p in (handoff.command_path, handoff.status_path, report)}
with pytest.raises(TaskCenterError) as error:
service.prepare_failed_quick_run(task_id)
assert error.value.code == 'quick_run_uncertain'
assert all(path.read_bytes() == contents for path, contents in originals.items())
assert not (handoff.command_path.parent.parent / 'quick-run-history').exists()
def test_verified_rollback_resolves_failed_native_uncertainty(failed_native):
service, _, task_id, _, report = failed_native
Path(str(report)[:-len('.json')] + '.rolled-back').write_text('native replacement rollback verified')
assert not service.task_context(task_id).interrupted
@pytest.mark.parametrize('contents', [None, '{truncated'])
def test_native_awaiting_then_failed_without_readable_report_stays_uncertain(failed_native, contents):
service, _, task_id, _, report = failed_native
if contents is None:
report.unlink()
else:
report.write_text(contents)
assert service.has_interrupted_quick_run(task_id)
def test_preflight_native_failure_does_not_claim_mutation(failed_native):
service, _, task_id, _, report = failed_native
report.write_text(json.dumps({'ok': False, 'stage': 'preflight', 'error': 'library target absent'}))
assert not service.has_interrupted_quick_run(task_id)
def test_recovery_selects_failed_job_with_native_mutation_evidence(failed_native):
from dx_productivity.trial_task_center import quick_run, recovery
_, _, _, handoff, _ = failed_native
commands = quick_run._read_commands(handoff.command_path)
statuses = quick_run._read_status_details(handoff.status_path)
assert recovery._recovery_command(commands, statuses, root=handoff.command_path.parent) == commands[0]
def test_native_failure_status_reaches_bound_recovery_validation(failed_native, monkeypatch):
from dx_productivity.trial_task_center import recovery
from dx_productivity.trial_task_center.models import ProjectStatus
service, store, task_id, _, _ = failed_native
project = store.list_projects(task_id)[0]
assert project.status is ProjectStatus.FAILED
def validate(*args, **kwargs):
raise TaskCenterError('bound_recovery_reached', 'validate immutable native evidence')
monkeypatch.setattr(recovery, 'recover', validate)
with pytest.raises(TaskCenterError) as error:
service.recover_quick_run(task_id, confirmed=True)
assert error.value.code == 'bound_recovery_reached'
@pytest.mark.parametrize('code', ['recovery_verified', 'recovery_saved_verified'])
def test_verified_recovery_synchronizes_previously_failed_project(failed_native, code):
from dx_productivity.trial_task_center.models import ProjectStatus, TaskStatus
service, store, task_id, handoff, _ = failed_native
job = handoff.command_path.read_text(encoding='utf-8').splitlines()[1].split('\t')[1]
with handoff.status_path.open('a', encoding='utf-8') as stream:
stream.write(f'{job}\trestored_ok\t{code}\tsaved and verified\n')
service.quick_run_progress(task_id)
assert store.list_projects(task_id)[0].status is ProjectStatus.COMPLETED
assert store.get_task(task_id).status is TaskStatus.COMPLETED
def test_manual_failure_cannot_be_completed_by_native_progress(failed_native):
from dx_productivity.trial_task_center.models import ProjectStatus
service, store, task_id, handoff, _ = failed_native
project = store.list_projects(task_id)[0]
store.set_project_status(project.project_id, ProjectStatus.FAILED, summary='manual failure')
job = handoff.command_path.read_text(encoding='utf-8').splitlines()[1].split('\t')[1]
with handoff.status_path.open('a', encoding='utf-8') as stream:
stream.write(f'{job}\trestored_ok\trecovery_verified\tverified\n')
with pytest.raises(TaskCenterError, match='quick_run_project_state'):
service.quick_run_progress(task_id)
def test_uncertain_batch_failed_blocks_next_project_in_task_queue(failed_native, tmp_path):
from threading import Event
from dx_productivity.trial_task_center.task_queue import execute_task_queue
service, store, task_id, _, _ = failed_native
other = store.create_task('next must not run')
path = tmp_path / 'next.prj'
path.touch()
project = store.sync_projects(other.task_id, tmp_path, (path,))[0]
store.set_project_selected(project.project_id, True)
store.bind_project_task(other.task_id, project.project_id, 'batch', 1)
result = execute_task_queue(service, (task_id, other.task_id), stop_event=Event())
assert result.paused
assert [entry.state for entry in result.entries] == ['blocked', 'pending']
assert not (service.for_project_task(other.task_id)._quick_run_preparer.data_root / 'quick-run').exists()
+24
View File
@@ -0,0 +1,24 @@
from threading import Timer
import pytest
@pytest.mark.parametrize('kind', ['native_report', 'queue_command'])
def test_native_report_waits_for_reader_to_release_windows_replace_lock(tmp_path, kind):
import win32file
import win32con
from dx_productivity.trial_task_center.native_helper import atomic_text
from dx_productivity.trial_task_center.quick_run import _write_atomic_queue_text
report = tmp_path / 'native.json'
report.write_text('old complete report')
held = win32file.CreateFile(str(report), win32con.GENERIC_READ,
win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE, None, win32con.OPEN_EXISTING, 0, None)
timer = Timer(.2, held.Close)
timer.start()
try:
if kind == 'native_report':
atomic_text(report, 'new complete report')
else:
_write_atomic_queue_text(report, 'new complete report', 'quick_run_command', 'publish failed')
finally:
timer.join()
assert report.read_text() == 'new complete report'
+34
View File
@@ -61,6 +61,40 @@ def test_native_context_accepts_same_project_via_junction_and_rejects_foreign(tm
assert not pool.close()
def test_vbs_reopen_resolves_canonical_long_project_before_fso_check(tmp_path, monkeypatch):
project = long_project(tmp_path)
root = tmp_path / 'worker'
root.mkdir()
(root / 'command.tsv').write_text(f'project_path\n{project}\n', encoding='utf-8')
pool = legacy_paths._AliasPool()
monkeypatch.setattr(legacy_paths, '_aliases', pool)
monkeypatch.setattr(legacy_paths, '_short_path', lambda _: None)
source = (Path(__file__).resolve().parents[2] / 'integration/dxdesigner795/QuickPartReplace.vbs').read_text(encoding='utf-8-sig')
def function(name):
return re.search(rf'(?ms)^Function {name}\(.*?^End Function', source).group()
try:
legacy_paths.worker_paths(root / 'worker.vbs', root)
access = (root / 'project-access.tsv').read_text(encoding='utf-8').splitlines()[1].split('\t')[1]
# Execute the production reopen boundary against real legacy FSO,
# stopping before CAD calls; no imitation of path resolution here.
boundary = re.search(r'(?ms)^Sub QPEnsureProject\(.*?(?= QP_Stage = "check_project")', source).group()
script = tmp_path / 'reopen-check.vbs'
script.write_text('Dim QP_Fso, QP_Root, QP_ProjectAccess, QP_AccessProject, App\n'
'Set QP_Fso=CreateObject("Scripting.FileSystemObject")\n'
'QP_Root=WScript.Arguments(0)\nSet App=Nothing\n'
'QPEnsureProject App, WScript.Arguments(1)\n'
+ boundary + 'WScript.Echo TargetPath\nEnd Sub\n'
+ function('QPProjectAccessPath') + '\n'
+ re.search(r'(?ms)^Sub QPEnsureProjectAccess\(\).*?^End Sub', source).group() + '\n'
+ function('QPReadUtf8'), encoding='utf-8')
result = subprocess.run((r'C:\Windows\SysWOW64\cscript.exe', '//nologo', str(script), str(root), str(project)),
capture_output=True, text=True)
assert result.returncode == 0, result.stdout + result.stderr
assert Path(result.stdout.strip()) == Path(access)
finally:
assert not pool.close()
def test_redirected_project_entry_is_rejected_before_native_launch(tmp_path, monkeypatch):
import _winapi
from dx_productivity.trial_task_center import quick_run
+8 -2
View File
@@ -62,7 +62,8 @@ def test_recovery_selects_saved_unverified_job_before_next_pending_job():
assert _recovery_command(commands, statuses) == commands[0]
def test_recovered_unverified_job_no_longer_blocks_queue(tmp_path):
@pytest.mark.parametrize('code', ['recovery_verified', 'recovery_saved_verified'])
def test_recovered_unverified_job_no_longer_blocks_queue(tmp_path, code):
script = tmp_path / 'QuickPartReplace.vbs'
script.write_text("' fixture\n", encoding='ascii')
preparer = QuickRunPreparer(tmp_path / 'data', script_source=script)
@@ -74,9 +75,14 @@ def test_recovered_unverified_job_no_longer_blocks_queue(tmp_path):
(root / 'status.tsv').write_text(
'job_id\tstate\tcode\tmessage\n'
'a\tbatch_saved_unverified\t\treadback failed\n'
'a\trestored_ok\t\trecovered\n', encoding='utf-8')
f'a\trestored_ok\t{code}\trecovered\n', encoding='utf-8')
assert preparer.has_interrupted('t') is False
from dx_productivity.trial_task_center.quick_run import _progress_from_queue
project = type('Project', (), {'path': Path('board.prj')})()
progress = _progress_from_queue((project,), _read_commands(root / 'command.tsv'),
(('a', 'restored_ok', code, 'recovered'),), None)
assert progress.saved_items == 1
def test_native_context_rejects_missing_or_changed_target_without_no_match():