fix: close batch execution and recovery lifecycle

This commit is contained in:
阿白叔 committed 2026-11-17 16:56:29 +08:00
1 parent b19afc6a53
commit d9cf6a07e9
91 files changed
+5779 -454

No files matched your search

+16 -5
View File
@@ -27,6 +27,16 @@ from dx_productivity.trial_task_center.task_queue import execute_task_queue
from dx_productivity.trial_task_center.ui.messages import _format_task_log_lines
class SimulatedReleasedRuntime:
"""The injected executor starts no owned process; admission proof is explicit."""
def __init__(self, root):
self.root, self.stop_event, self.cad, self.desktop = root, None, None, None
def bind_logs(self, *args):
pass
def release_failed_project(self, error, evidence_root):
return True
def run_scenario(output: Path, *, projects=3, sheets=2, rules=2, behavior='success') -> dict:
output = Path(output).resolve()
output.mkdir(parents=True, exist_ok=False)
@@ -126,17 +136,18 @@ def run_scenario(output: Path, *, projects=3, sheets=2, rules=2, behavior='succe
preview = measured('import_bom', lambda: service.preview_bom_plan(task.task_id, bom))
measured('save_plan', lambda: service.replace_target_plan(task.task_id, preview))
ids = tuple(task.task_id for task in tasks)
result = measured('queue_wall', lambda: execute_task_queue(service, ids, stop_event=stop))
simulated_runtime = SimulatedReleasedRuntime(service._logging.root)
result = measured('queue_wall', lambda: execute_task_queue(service, ids, stop_event=stop, runtime=simulated_runtime))
if behavior == 'pause_resume':
assert result.paused and len(calls) == 2
stop.clear()
result = measured('queue_resume_wall', lambda: execute_task_queue(service, ids, stop_event=stop, queue_id=result.queue_id))
result = measured('queue_resume_wall', lambda: execute_task_queue(service, ids, stop_event=stop, queue_id=result.queue_id, runtime=simulated_runtime))
expected_steps = projects * sheets * rules * 2
expected_calls = 1 if behavior == 'uncertain_stop' else expected_steps
expected_calls = 1 + (projects - 1) * sheets * rules * 2 if behavior == 'uncertain_stop' else expected_steps
assert len(calls) == expected_calls
if behavior == 'uncertain_stop':
assert result.paused and result.entries[0].state == 'blocked'
assert all(entry.state == 'pending' for entry in result.entries[1:])
assert not result.paused and result.entries[0].state == 'blocked'
assert all(entry.state == 'completed' for entry in result.entries[1:])
else:
assert not result.paused
assert [entry.state for entry in result.entries] == ['failed' if behavior == 'failure_continue' and i == 0 else 'completed' for i in range(projects)]
+72 -18
View File
@@ -14,11 +14,14 @@ from uuid import uuid4
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'src'))
from dx_productivity.trial_task_center.batch_resources import (
BatchResourceCleanupError, cleanup_pending_resources, pending_resources,
BatchResourceCleanupError, cleanup_pending_resources, pending_resources, blocking_resources,
process_identity, write_record,
)
from dx_productivity.trial_task_center.batch_runtime import BatchCadRuntime
from dx_productivity.trial_task_center.batch_worker import _wait_for_owned_writes
from dx_productivity.trial_task_center.cad_identity import current_desktop_name
from dx_productivity.trial_task_center.isolated_desktop import _Win32Api
from dx_productivity.trial_task_center.stop_control import StopControl
HOLDER = '''import json,os,sys,win32service
@@ -65,30 +68,81 @@ def probe(output):
handshake = json.loads(holder.stdout.readline())
assert handshake['pid'] == holder.pid and handshake['state'] == 'holding'
report['holder_fixture'] = handshake
try:
runtime.close()
raise AssertionError('cleanup incorrectly succeeded with external holder')
except BatchResourceCleanupError as failure:
assert failure.completed_result == original_result
report['events'].append({'phase': 'initial_cleanup', 'blocked': True,
'error': str(failure), 'holder_still_running': holder.poll() is None})
runtime.close()
report['events'].append({'phase': 'initial_cleanup', 'blocked': False,
'state': runtime.record['state'], 'holder_still_running': holder.poll() is None})
assert holder.poll() is None
blocked = pending_resources(root)
assert len(blocked) == 1 and blocked[0]['state'] == 'blocked'
assert len(blocked) == 1 and blocked[0]['state'] == 'isolated' and not blocking_resources(root)
assert blocked[0]['blocking'] is False and blocked[0]['release_results']['desktop_released'] is False
assert blocked[0]['cleanup']['desktop_confirmation']['remaining_windows'] == []
assert blocked[0]['cleanup']['desktop_handle_closed']
report['blocked_resource_record'] = blocked[0]
candidate = BatchCadRuntime(root, 'must_be_blocked', cad_factory=forbidden_cad)
report['isolated_resource_record'] = blocked[0]
# A synthetic persistent claim with an actual live owned helper proves
# that neither the isolated label nor a forged exit flag opens the gate.
active = subprocess.Popen((sys.executable, '-c', 'import sys;sys.stdin.readline()'),
stdin=subprocess.PIPE, creationflags=subprocess.CREATE_NO_WINDOW)
try:
candidate.__enter__()
raise AssertionError('new batch bypassed pending resource guard')
except BatchResourceCleanupError as failure:
report['events'].append({'phase': 'new_batch', 'blocked': True, 'error': str(failure)})
assert candidate.generation == 0 and candidate.desktop is None
active_identity = process_identity(active)
active_root = output / 'active-writer-data'
active_session = uuid4().hex
active_path = active_root / 'batch-resources' / active_session / 'session.json'
active_record = dict(blocked[0], session_id=active_session,
writer_identities=[active_identity], processes=[active_identity])
active_record.pop('record_path', None)
active_record['isolation_proof'] = dict(active_record['isolation_proof'],
session_id=active_session, processes=[active_identity])
write_record(active_path, active_record)
assert blocking_resources(active_root)
assert cleanup_pending_resources(active_root) and blocking_resources(active_root)
assert active.poll() is None
report['active_writer_gate'] = {'process': active_identity, 'blocked': True,
'record_fixture': 'synthetic isolated claim; real owned helper remains alive'}
finally:
active.stdin.write(b'release\n')
active.stdin.flush()
active.wait(timeout=5)
active.stdin.close()
assert not blocking_resources(active_root) # Exact recorded process has now exited.
candidate = BatchCadRuntime(root, 'fresh_batch', cad_factory=forbidden_cad)
with candidate:
fresh = candidate._ensure_desktop()
assert fresh.name != desktop.name
report['fresh_desktop'] = fresh.name
report['events'].append({'phase': 'new_batch', 'blocked': False, 'fresh_desktop_created': True})
restart_code = '''import json,sys
from pathlib import Path
sys.path.insert(0,sys.argv[2])
from dx_productivity.trial_task_center.batch_resources import cleanup_pending_resources,blocking_resources
from dx_productivity.trial_task_center.batch_runtime import BatchCadRuntime
root=Path(sys.argv[1])
rows=cleanup_pending_resources(root)
assert rows and all(row['state']=='isolated' and row['blocking'] is False for row in rows)
assert not blocking_resources(root)
with BatchCadRuntime(root,'restart_admission') as runtime:
desktop=runtime._ensure_desktop()
assert desktop.name != rows[0]['desktop']
print(json.dumps({'restart_isolation_validated':True,'fresh_desktop':desktop.name}))
'''
restarted = subprocess.run((sys.executable, '-c', restart_code, str(root),
str(Path(__file__).resolve().parents[1] / 'src')), capture_output=True, text=True,
encoding='utf-8', timeout=30, creationflags=subprocess.CREATE_NO_WINDOW)
assert restarted.returncode == 0, restarted.stderr
report['restart'] = json.loads(restarted.stdout.strip())
cleanup_error = _wait_for_owned_writes(runtime, StopControl())
assert cleanup_error is None
assert runtime.owned_processes_exited() and holder.poll() is None
assert runtime.record['state'] == 'isolated' and result_path.read_bytes() == original_bytes
report['events'].append({'phase': 'worker_exit_resource_recheck',
'error_returned': False, 'owned_writers_exited': True,
'holder_still_running': True, 'resource_state': runtime.record['state']})
pending = cleanup_pending_resources(root)
assert pending and pending[0]['state'] == 'blocked' and holder.poll() is None
assert pending and pending[0]['state'] == 'isolated' and holder.poll() is None
assert not blocking_resources(root)
close_history = runtime.record['cleanup']['desktop_handle_history']
assert len([event for event in close_history if event['operation'] == 'close']) == 1
report['events'].append({'phase': 'resource_only_retry_while_held',
'blocked': True, 'holder_still_running': True})
'blocked': False, 'holder_still_running': True, 'owned_desktop_handle_closed_once': True})
assert result_path.read_bytes() == original_bytes
holder.stdin.write('release\n')
holder.stdin.flush()