feat: isolate batch execution in owned supervisor with durable recovery protocol

This commit is contained in:
阿白叔 committed 2026-10-23 15:54:33 +08:00
1 parent 6d0b92c515
commit 1baf908ba4
23 files changed
+1208 -53

No files matched your search

@@ -48,6 +48,7 @@ def configure_application_identity(application: QApplication) -> None:
def _parse_arguments(argv: Sequence[str] | None) -> argparse.Namespace:
parser = argparse.ArgumentParser(prog="DxPartReplace")
parser.add_argument("--smoke-test", action="store_true", help=argparse.SUPPRESS)
parser.add_argument('--batch-worker', type=Path, help=argparse.SUPPRESS)
parser.add_argument("--data-root", type=Path, help=argparse.SUPPRESS)
parser.add_argument("--native-helper", action="store_true", help=argparse.SUPPRESS)
parser.add_argument("--snapshot", type=Path, help=argparse.SUPPRESS)
@@ -119,25 +120,24 @@ def _flush(context: LoggingContext) -> None:
def _smoke_batch_runtime(data_root: Path, context: LoggingContext) -> None:
"""Exercise process tracking inside the frozen supervisor before releasing."""
from dx_productivity.trial_task_center.batch_runtime import BatchCadRuntime
with BatchCadRuntime(data_root, 'packaged_runtime_smoke') as runtime:
runtime.bind_logs(context, ())
with runtime.native_scope(data_root / 'runtime-smoke') as lease:
command = str(Path(os.environ['SystemRoot']) / 'System32/cmd.exe')
process = lease.start_process((command, '/d', '/c', 'exit', '0'))
if not runtime.record['processes'][0]['creation_time']:
raise RuntimeError('Smoke process identity has no creation time')
if process.wait(timeout=15) != 0:
raise RuntimeError('Smoke worker did not exit successfully')
if runtime.record['state'] != 'released':
raise RuntimeError('Smoke resources were not released')
context.logger.info('packaged_runtime_smoke_passed batch_id=%s', runtime.session_id)
from dx_productivity.trial_task_center.batch_supervisor import run_supervised
with_store = TaskStore(data_root / 'task-center.db')
try:
service = TaskCenterService(with_store, context, recover_on_startup=False)
result = run_supervised(service, 'runtime_smoke', {})
if not result['process_identity_read']:
raise RuntimeError('Smoke worker identity was not checked')
finally:
with_store.close()
context.logger.info('packaged_runtime_smoke_passed supervisor_pid=%s', result['pid'])
def main(argv: Sequence[str] | None = None) -> int:
"""Run the Qt shell, returning a conventional process status code."""
arguments = _parse_arguments(argv)
if arguments.batch_worker is not None:
from dx_productivity.trial_task_center.batch_worker import run
return run(arguments.batch_worker)
if arguments.mark_batch_attempt:
from dx_productivity.trial_task_center.native_helper import run_attempt_marker
return run_attempt_marker(job_id=arguments.attempt_job, task_id=arguments.attempt_task,
@@ -171,6 +171,7 @@ def main(argv: Sequence[str] | None = None) -> int:
_smoke_batch_runtime(data_root, logging_context)
store = TaskStore(database_path)
service = TaskCenterService(store, logging_context)
service._supervised = True
qt_application = QApplication([sys.executable, *(argv or ())])
configure_application_identity(qt_application)
window = _load_window()(service)
@@ -0,0 +1,319 @@
"""GUI-side batch admission, process supervision and resource-only reconciliation."""
from __future__ import annotations
from contextlib import contextmanager
import json
import hashlib
import os
from pathlib import Path
import queue
import subprocess
import sys
import threading
import time
from uuid import uuid4
from .errors import TaskCenterError
from .path_access import canonical_path, internal_path
from .supervisor_protocol import VERSION, MessageGate, valid_journal, encode, decode, decode_error
_WORKER_ROOT = None
_LAUNCH_LOCK = threading.Lock()
_LIVE_SUPERVISORS = {}
_WRITE_OPERATIONS = frozenset({'execute_task_queue', 'execute_quick_run_queue', 'execute_quick_run', 'recover_quick_run'})
def _mark_interrupted(root, journal, reason):
from .batch_resources import write_record
journal.update(state='blocked', outcome='interrupted', error=str(reason))
if journal['operation'] in _WRITE_OPERATIONS:
# A missing final result is not proof of no mutation. Publish the same
# protection the existing recovery UI understands, without overwriting
# any earlier, more specific marker.
journal['business_uncertain'] = True
for task_id in journal['task_ids']:
allowed = {canonical_path(root), canonical_path(Path(root) / 'tasks' / task_id)}
actual = journal.get('uncertainty_roots', {}).get(task_id)
roots = {canonical_path(actual)} if actual and canonical_path(actual) in allowed else allowed
for evidence in roots:
marker = internal_path(evidence / 'quick-run/uncertain.flag')
marker.parent.mkdir(parents=True, exist_ok=True)
try:
with marker.open('x', encoding='utf-8') as stream:
stream.write('reason=supervisor_interrupted; batch=' + journal['batch_id'] + '; manual reconciliation required\n')
stream.flush()
os.fsync(stream.fileno())
except FileExistsError:
pass
write_record(Path(root) / 'batch-resources' / journal['batch_id'] / 'supervisor.json', journal)
def _worker_context(root):
global _WORKER_ROOT
_WORKER_ROOT = canonical_path(root)
def _file_lock(handle, acquire):
from .task_queue import _os_lock
_os_lock(handle, acquire)
@contextmanager
def supervisor_lease(root):
root = internal_path(root)
root.mkdir(parents=True, exist_ok=True)
if not _LAUNCH_LOCK.acquire(blocking=False):
raise TaskCenterError('supervisor_busy', '另一批操作正在运行,请先安全收尾。')
handle = None
acquired = False
try:
handle = (root / '.batch-supervisor.execution.lock').open('a+b')
if handle.seek(0, os.SEEK_END) == 0:
handle.write(b'\0')
handle.flush()
try:
_file_lock(handle, True)
acquired = True
except OSError as error:
raise TaskCenterError('supervisor_busy', '另一窗口的批次监督进程尚未结束。') from error
yield
finally:
if handle is not None:
if acquired:
_file_lock(handle, False)
handle.close()
_LAUNCH_LOCK.release()
def assert_supervisor_idle(root):
if _WORKER_ROOT == canonical_path(root):
return
with supervisor_lease(root):
pass
@contextmanager
def mutation_lease(root):
if _WORKER_ROOT == canonical_path(root):
yield
else:
with supervisor_lease(root):
yield
def pending_supervisors(root):
from .batch_resources import _process_gone
pending = []
for path in (internal_path(root) / 'batch-resources').glob('*/supervisor.json'):
try:
value = json.loads(path.read_text(encoding='utf-8'))
if not valid_journal(value, path.parent.name):
raise ValueError('invalid supervisor ownership record')
if value.get('state') == 'finished':
continue
identity = value.get('process') or value.get('parent_process')
if (value.get('state') in {'starting', 'running'} and identity and not _process_gone(identity)
and value.get('parent_process') and not _process_gone(value['parent_process'])):
continue
pending.append(dict(value, record_path=str(canonical_path(path)), state='blocked'))
except (OSError, ValueError, TypeError, KeyError) as error:
pending.append({'state': 'blocked', 'record_path': str(canonical_path(path)), 'error': str(error)})
return tuple(pending)
def reconcile_supervisors(root):
"""Recheck orphan ownership only; this never launches or replays a job."""
from .batch_resources import _process_gone, pending_resources, write_record
physical = pending_resources(root)
for record in pending_supervisors(root):
identity = record.get('process')
if not record.get('batch_id') or (identity and not _process_gone(identity)):
continue
if record.get('outcome') not in {'interrupted', 'completed_resources_pending'}:
_mark_interrupted(root, record, 'Supervisor ended without a reconciled final result')
if any(item.get('session_id') == record['batch_id'] or not item.get('session_id') for item in physical):
continue
path = Path(record.pop('record_path'))
outcome = 'completed' if record.get('outcome') == 'completed_resources_pending' else 'interrupted'
record.update(state='finished', reconciled=True, outcome=outcome, reconciled_at=time.time())
write_record(path, record)
return pending_supervisors(root)
def _command(request):
if bool(getattr(sys, 'frozen', False)):
return (sys.executable, '--batch-worker', str(request))
return (sys.executable, '-m', 'dx_productivity.trial_task_center.batch_worker', '--request', str(request))
def _environment():
environment = dict(os.environ)
if bool(getattr(sys, 'frozen', False)):
for key in ('PYTHONPATH', 'PYTHONHOME'):
environment.pop(key, None)
else:
environment['PYTHONPATH'] = str(Path(__file__).resolve().parents[2])
return environment
def _finish_response(root, journal, response, context):
"""A supervisor exit may release its last USER reference. Never repeat work."""
from .batch_resources import cleanup_pending_resources, write_record
from .supervisor_result import validated_outcome, resource_pending_error
result, error, primary = validated_outcome(journal['operation'], response)
pending = cleanup_pending_resources(root, logging_context=context)
related = tuple(item for item in pending if item.get('session_id') == journal['batch_id'] or not item.get('session_id'))
journal['state'] = 'blocked' if related else 'finished'
journal['outcome'] = ('completed_resources_pending' if related and response.get('business_succeeded')
else response.get('status', 'interrupted'))
journal['resource_recheck'] = {'pending': bool(related), 'checked_at': time.time()}
write_record(Path(root) / 'batch-resources' / journal['batch_id'] / 'supervisor.json', journal)
if related:
raise resource_pending_error(journal['operation'], result, error, primary)
if response.get('business_succeeded'):
if response.get('error'):
context.logger.info('supervisor_resource_recovery_passed batch_id=%s business_replayed=false', journal['batch_id'])
return result
if response.get('operation_error'):
if error is not None and hasattr(error, 'bom_report') and not hasattr(primary, 'bom_report'):
primary.bom_report = error.bom_report
raise primary
if response.get('error'):
raise error
raise TaskCenterError('supervisor_interrupted', '批次监督进程异常退出;未重放任务,请检查已有结果和保护记录。')
def run_supervised(service, operation, arguments, *, stop_event=None, on_progress=None, on_phase=None):
from .batch_resources import write_record, process_identity
from .isolated_desktop import _Win32Api
root = canonical_path(service._logging.root)
if stop_event is not None and stop_event.is_set():
raise TaskCenterError('operation_cancelled', '本批操作已取消,未启动监督进程。')
with supervisor_lease(root):
if operation == 'cleanup_batch_resources':
for key, (owned_api, owned_process) in tuple(_LIVE_SUPERVISORS.items()):
if key.parent.parent == root / 'batch-resources':
owned_process.close()
owned_api.close_pending()
_LIVE_SUPERVISORS.pop(key)
if operation != 'cleanup_batch_resources' and pending_supervisors(root):
raise TaskCenterError('batch_resources_pending', '上一监督进程尚未完成资源复核,请先重新清理资源。')
batch_id, attempt_id = uuid4().hex, uuid4().hex
directory = root / 'batch-resources' / batch_id
request = directory / 'request.json'
journal = {'version': VERSION, 'batch_id': batch_id, 'attempt_id': attempt_id,
'operation': operation, 'state': 'starting', 'started_at': time.time(),
'task_ids': list(arguments.get('task_ids', ())) or ([arguments['task_id']] if arguments.get('task_id') else []),
'process': None}
if any(not isinstance(value, str) or Path(value).name != value or value in {'.', '..'}
for value in journal['task_ids']):
raise TaskCenterError('target_identity', '监督进程任务编号无效。')
journal['uncertainty_roots'] = {task_id: str(canonical_path(
service._project_task_service(task_id)._quick_run_preparer.data_root))
for task_id in journal['task_ids'] if operation in _WRITE_OPERATIONS}
import win32api
parent = type('ParentIdentity', (), {'pid': os.getpid(), 'handle': win32api.GetCurrentProcess()})()
journal['parent_process'] = process_identity(parent)
write_record(request, {'version': VERSION, 'batch_id': batch_id, 'attempt_id': attempt_id,
'root': str(root), 'database': str(canonical_path(service._store.path)),
'operation': operation, 'arguments': encode(arguments), 'task_ids': journal['task_ids']})
journal['request_sha256'] = hashlib.sha256(internal_path(request).read_bytes()).hexdigest()
write_record(directory / 'supervisor.json', journal)
gate, messages = MessageGate(batch_id, attempt_id), queue.Queue()
api, process, reader = _Win32Api(), None, None
sent_cancel, last_heartbeat = False, time.monotonic()
transport_error = None
def receive():
try:
while line := process.stdout.readline(1024 * 1024):
try:
messages.put(json.loads(line))
except (ValueError, UnicodeError):
messages.put({'type': 'invalid'})
finally:
messages.put(None)
try:
# A normal input-desktop supervisor owns its private-desktop children.
# Only the supervisor, never the GUI, creates a private desktop.
process = api.create_process(_command(internal_path(request)), None, root,
_environment(), stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
journal.update(state='running', process=process_identity(process))
write_record(directory / 'supervisor.json', journal)
reader = threading.Thread(target=receive, daemon=True)
reader.start()
while process.poll() is None or not messages.empty():
if stop_event is not None and stop_event.is_set() and not sent_cancel:
write_record(directory / 'cancel.json', {'version': VERSION, 'batch_id': batch_id, 'attempt_id': attempt_id})
sent_cancel = True
try:
value = messages.get(timeout=.1)
except queue.Empty:
if time.monotonic() - last_heartbeat > 15:
service._logging.logger.warning('supervisor_heartbeat_delayed batch_id=%s; no automatic replay', batch_id)
last_heartbeat = time.monotonic()
continue
if value is None or not gate.accept(value):
continue
last_heartbeat = time.monotonic()
if value['type'] == 'progress' and on_progress is not None:
on_progress(value['payload'])
elif value['type'] == 'phase' and on_phase is not None:
payload = decode(value['payload'])
on_phase(*payload)
elif value['type'] == 'state':
state = decode(value['payload'])
service._task_queue_feedback = state['queue']
service._batch_feedback = state['batch']
if on_phase is not None and state['phase'] in {'recycling', 'closing'}:
from .bom_import_state import BomImportPhase
on_phase(BomImportPhase.RECOVERING if state['phase'] == 'recycling' else BomImportPhase.RELEASING,
'正在安全恢复读取会话…' if state['phase'] == 'recycling' else '正在释放后台资源…')
process.wait(timeout=15)
except Exception as error:
transport_error = error
finally:
service._task_queue_feedback = None
service._batch_feedback = None
try:
if process is not None:
process.close() # Waits, and confines termination to the owned Job.
api.close_pending()
except Exception as error:
if process is not None:
_LIVE_SUPERVISORS[directory / 'supervisor.json'] = (api, process)
transport_error = error if transport_error is None else TaskCenterError(
'batch_resources_pending', f'监督进程错误:{transport_error};收尾错误:{error}')
if reader is not None:
reader.join(3)
try:
try:
response = json.loads(internal_path(directory / 'result.json').read_text(encoding='utf-8'))
except FileNotFoundError:
saved = json.loads(internal_path(directory / 'business-result.json').read_text(encoding='utf-8'))
if (saved.get('version') != VERSION or saved.get('batch_id') != batch_id
or saved.get('attempt_id') != attempt_id or not saved['payload'].get('business_succeeded')):
raise ValueError('Untrusted saved business result')
response = dict(saved, type='result', sequence=gate.sequence + 1)
service._logging.logger.warning('supervisor_final_missing_saved_result_retained batch_id=%s', batch_id)
if (response.get('version') != VERSION or response.get('batch_id') != batch_id
or response.get('attempt_id') != attempt_id or response.get('type') != 'result'
or type(response.get('sequence')) is not int or response['sequence'] < gate.sequence
or type(response.get('generation')) is not int or response['generation'] < gate.generation):
raise ValueError('stale or invalid final supervisor result')
from .supervisor_result import validated_outcome, resource_pending_error
decoded_result, decoded_error, decoded_primary = validated_outcome(operation, response['payload'])
except (OSError, ValueError, KeyError, TypeError, AttributeError) as error:
_mark_interrupted(root, journal, error)
# Recheck physical resources even when final business results are
# missing; this never authorizes repeating the interrupted job.
from .batch_resources import cleanup_pending_resources
cleanup_pending_resources(root, logging_context=service._logging)
raise TaskCenterError('supervisor_interrupted', '批次监督进程未留下可信结果;保留保护记录,不自动重试。') from error
if transport_error is not None:
if response['payload']['business_succeeded']:
journal.update(state='blocked', outcome='completed_resources_pending', error=str(transport_error))
write_record(directory / 'supervisor.json', journal)
else:
_mark_interrupted(root, journal, transport_error)
raise resource_pending_error(operation, decoded_result, transport_error, decoded_primary)
return _finish_response(root, journal, response['payload'], service._logging)
@@ -0,0 +1,195 @@
"""One request, one resource-owning supervisor process, no Qt application."""
from __future__ import annotations
import argparse
import hashlib
import json
import os
from pathlib import Path
import sys
import threading
import time
import traceback
from uuid import UUID
from .path_access import internal_path, canonical_path
from .supervisor_protocol import VERSION, OPERATIONS, valid_journal, encode, decode, encode_error
def _output_stream():
if sys.stdout is not None:
return sys.stdout, False
# Windowed PyInstaller deliberately sets sys.stdout=None. The supervisor
# still has the explicit inherited pipe from STARTUPINFO; duplicate it so
# closing this Python stream cannot close an unrelated borrowed handle.
import msvcrt
import win32api
import win32con
source = win32api.GetStdHandle(win32con.STD_OUTPUT_HANDLE)
handle = win32api.DuplicateHandle(win32api.GetCurrentProcess(), source,
win32api.GetCurrentProcess(), 0, False, win32con.DUPLICATE_SAME_ACCESS)
descriptor = msvcrt.open_osfhandle(handle.Detach(), os.O_WRONLY | os.O_BINARY)
return os.fdopen(descriptor, 'w', encoding='utf-8', buffering=1), True
def _admit_request(directory, request, request_bytes):
from .batch_resources import _process_gone, process_identity
import win32api
deadline = time.monotonic() + 5
while True:
journal = json.loads(internal_path(directory / 'supervisor.json').read_text(encoding='utf-8'))
if (not valid_journal(journal, request['batch_id'])
or journal.get('attempt_id') != request['attempt_id']
or journal.get('state') not in {'starting', 'running'}
or journal.get('request_sha256') != hashlib.sha256(request_bytes).hexdigest()
or not journal.get('parent_process', {}).get('creation_time')
or _process_gone(journal['parent_process'])):
raise ValueError('Stale or unowned supervisor request')
if journal.get('process'):
break
if time.monotonic() >= deadline:
raise ValueError('Supervisor launch identity was not published')
time.sleep(.02)
own = process_identity(type('WorkerIdentity', (), {'pid': os.getpid(), 'handle': win32api.GetCurrentProcess()})())
if journal['process'] != own:
raise ValueError('Supervisor request belongs to another process')
# Atomic exclusive publication makes requests one-shot, including retained
# requests invoked manually or racing a delayed/duplicate launch.
with internal_path(directory / 'claim.json').open('x', encoding='utf-8') as stream:
json.dump({'version': VERSION, 'batch_id': request['batch_id'], 'attempt_id': request['attempt_id'],
'process': own}, stream)
stream.flush()
os.fsync(stream.fileno())
def run(request_path):
from .batch_resources import write_record
from .batch_runtime import BatchCadRuntime
from .batch_supervisor import _worker_context
from .logging_setup import configure_logging
from .service import TaskCenterService
from .store import TaskStore
output, owns_output = _output_stream()
request_path = canonical_path(request_path, strict=True)
request_bytes = internal_path(request_path).read_bytes()
request = json.loads(request_bytes)
batch_id, attempt_id = request['batch_id'], request['attempt_id']
if (request.get('version') != VERSION or UUID(batch_id).hex != batch_id or UUID(attempt_id).hex != attempt_id
or request['operation'] not in OPERATIONS):
raise ValueError('Invalid batch supervisor request')
root = canonical_path(request['root'])
directory = root / 'batch-resources' / batch_id
if request_path != directory / 'request.json':
raise ValueError('Supervisor request ownership path mismatch')
_admit_request(directory, request, request_bytes)
_worker_context(root)
stop, finished, output_lock = threading.Event(), threading.Event(), threading.Lock()
kind = {'inspect_bom_batch': 'bom_import', 'preview_bom_batch': 'bom_import',
'execute_task_queue': 'task_queue', 'execute_quick_run_queue': 'quick_run_queue'}.get(request['operation'], request['operation'])
runtime = BatchCadRuntime(root, kind, stop, session_id=batch_id)
sequence = 0
def emit(kind, payload=None, *, persist=False):
nonlocal sequence
with output_lock:
sequence += 1
envelope = {'version': VERSION, 'batch_id': batch_id, 'attempt_id': attempt_id,
'generation': max(1, runtime.generation), 'sequence': sequence,
'type': kind, 'payload': payload}
if persist:
write_record(directory / 'result.json', envelope)
try:
output.write(json.dumps(envelope, ensure_ascii=True, allow_nan=False) + '\n')
output.flush()
except (BrokenPipeError, OSError):
stop.set()
def monitor():
while not finished.is_set():
try:
cancel = internal_path(directory / 'cancel.json')
if cancel.is_file():
value = json.loads(cancel.read_text(encoding='utf-8'))
if value == {'version': VERSION, 'batch_id': batch_id, 'attempt_id': attempt_id}:
stop.set()
emit('heartbeat')
feedback = getattr(service, '_task_queue_feedback', None)
emit('state', encode({'phase': runtime.record['state'], 'queue': feedback,
'batch': service.batch_feedback()}))
except Exception:
stop.set() # Lost control evidence cannot authorize new work.
finished.wait(1)
context = configure_logging(root, log_path=directory / 'supervisor.log')
store = TaskStore(Path(request['database']))
service = TaskCenterService(store, context, recover_on_startup=False)
thread = threading.Thread(target=monitor, daemon=True)
thread.start()
response = {'business_succeeded': False, 'status': 'error'}
try:
arguments = decode(request['arguments'])
operation = request['operation']
def progress(message):
emit('progress', str(message))
def phase(value, message):
emit('phase', encode((value, str(message))))
if operation == 'cleanup_batch_resources':
result = service.cleanup_batch_resources()
response.update(status='ok', business_succeeded=True, result=encode(result))
else:
with runtime:
runtime.bind_logs(context, request['task_ids'])
try:
if operation == 'probe':
result = {'pid': os.getpid(), 'resource_state': 'not_acquired'}
elif operation == 'runtime_smoke':
with runtime.native_scope(directory / 'runtime-smoke') as lease:
child = lease.start_process((str(Path(os.environ['SystemRoot'])/'System32/cmd.exe'), '/d', '/c', 'exit', '0'))
if not runtime.record['processes'][0]['creation_time'] or child.wait(timeout=15):
raise RuntimeError('Supervisor process-identity smoke failed')
result = {'pid': os.getpid(), 'process_identity_read': True}
elif operation == 'execute_task_queue':
from .task_queue import execute_task_queue
result = execute_task_queue(service, **arguments, stop_event=stop, runtime=runtime)
elif operation in {'inspect_bom_batch', 'preview_bom_batch'}:
controls = {'stop_event': stop, 'on_progress': progress, 'runtime': runtime}
if operation == 'inspect_bom_batch':
controls['on_phase'] = phase
result = getattr(service, operation)(**arguments, **controls)
elif operation == 'collect_target_inventory':
result = service.collect_target_inventory(**arguments, stop_event=stop, on_progress=progress, runtime=runtime)
elif operation == 'execute_quick_run_queue':
result = service.execute_quick_run_queue(**arguments, stop_event=stop, runtime=runtime)
elif operation == 'target_cell_choices':
result = service.target_cell_choices(**arguments)
else:
result = getattr(service, operation)(**arguments, runtime=runtime)
runtime.result = result
response.update(status='ok', business_succeeded=True, result=encode(result))
write_record(directory / 'business-result.json', {'version': VERSION, 'batch_id': batch_id,
'attempt_id': attempt_id, 'generation': max(1, runtime.generation), 'payload': response})
if operation == 'inspect_bom_batch':
from .bom_import_state import BomImportPhase
phase(BomImportPhase.RELEASING, '本批位号核验结束,正在释放后台资源…')
except Exception as error:
response['operation_error'] = encode_error(error)
raise
except Exception as error:
context.report_exception('batch_supervisor', error)
response.update(status='error', error=encode_error(error))
finally:
finished.set()
thread.join(3)
store.close()
emit('result', response, persist=True)
if owns_output:
output.close()
return 0
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--request', required=True, type=Path)
args = parser.parse_args()
return run(args.request)
if __name__ == '__main__':
raise SystemExit(main())
@@ -17,6 +17,8 @@ class BomImportPhase(Enum):
VALIDATING = 'validating'
INVENTORY = 'inventory'
MATCHING = 'matching'
RECOVERING = 'recovering'
RELEASING = 'releasing'
CANCELLING = 'cancelling'
PREVIEW_READY = 'preview_ready'
REJECTED = 'rejected'
@@ -30,6 +32,11 @@ _NEXT = {
BomImportPhase.INVENTORY: {BomImportPhase.INVENTORY, BomImportPhase.MATCHING},
BomImportPhase.MATCHING: {BomImportPhase.MATCHING, BomImportPhase.INVENTORY},
}
_RECOVERY_PHASES = {BomImportPhase.RECOVERING, BomImportPhase.RELEASING}
for _phase in tuple(_NEXT):
_NEXT[_phase] |= _RECOVERY_PHASES
for _phase in _RECOVERY_PHASES:
_NEXT[_phase] = _RECOVERY_PHASES | {BomImportPhase.INVENTORY, BomImportPhase.MATCHING}
@dataclass(frozen=True)
@@ -130,6 +130,57 @@ class DiscoveryCache:
def invalidate(self, project: Path):
with self.lock:
self._entries.pop(_key(project), None)
self._disk_path(project).unlink(missing_ok=True)
def _disk_path(self, project):
from .path_access import internal_path
return internal_path(Path(self.data_root) / 'discovery-cache' /
(hashlib.sha256(_key(project).encode('utf-8')).hexdigest() + '.json'))
def _disk_entry(self, project, stamp):
import json
from uuid import uuid4
from .supervisor_protocol import decode
path = self._disk_path(project)
if stamp is None or not path.exists():
return None
try:
if path.stat().st_size > 32 * 1024 * 1024:
raise ValueError('inventory cache exceeds size limit')
record = json.loads(path.read_text(encoding='utf-8'))
payload = json.dumps(record['discovery'], ensure_ascii=True, sort_keys=True).encode('utf-8')
if record['version'] != 1 or record['payload_sha256'] != hashlib.sha256(payload).hexdigest():
raise ValueError('invalid discovery cache')
if record['project'] != _key(project) or record['fingerprint'] != hashlib.sha256(repr(stamp).encode()).hexdigest():
return None
discovery = decode(record['discovery'])
from .quick_run_protocol import ProjectDiscovery
if not isinstance(discovery, ProjectDiscovery):
raise ValueError('unexpected discovery cache type')
_discovery_identity(discovery)
return stamp, frozenset(record['parts']), record['collect_components'], discovery
except (OSError, ValueError, TypeError, KeyError):
try:
path.replace(path.with_name(path.name + '.bad-' + uuid4().hex))
except OSError:
pass # A bad cache is never authoritative, even if quarantine fails.
return None
def _save_disk(self, project, stamp, requested, components, discovery):
import json
from .batch_resources import write_record
from .supervisor_protocol import encode
try:
payload = encode(discovery)
write_record(self._disk_path(project), {'version': 1, 'project': _key(project),
'fingerprint': hashlib.sha256(repr(stamp).encode()).hexdigest(), 'parts': sorted(requested),
'collect_components': components, 'discovery': payload,
'payload_sha256': hashlib.sha256(json.dumps(payload, ensure_ascii=True, sort_keys=True).encode()).hexdigest()})
files = sorted(self._disk_path(project).parent.glob('*.json'), key=lambda path: path.stat().st_mtime_ns, reverse=True)
for stale in files[self.capacity:]:
stale.unlink(missing_ok=True)
except (OSError, ValueError, TypeError):
pass # Cache persistence is optional, unlike execution write-ahead proof.
def discover(self, project, parts, collect_components, loader, *, stop_event=None):
with self.lock:
@@ -140,7 +191,7 @@ class DiscoveryCache:
key = _key(project)
requested = frozenset(part.casefold() for part in parts)
before = fingerprint()
entry = self._entries.pop(key, None)
entry = self._entries.pop(key, None) or self._disk_entry(project, before)
if entry is not None:
stamp, covered, has_components, discovery = entry
if (before is not None and before == stamp and requested <= covered
@@ -197,6 +248,7 @@ class DiscoveryCache:
and (len(getattr(discovery, 'components', ())) + len(sheets)
+ sum(len(parts) for parts in matches.values())) <= 100000):
self._entries[key] = (after, requested, collect_components, deepcopy(discovery))
self._save_disk(project, after, requested, collect_components, discovery)
while len(self._entries) > self.capacity:
self._entries.popitem(last=False)
return discovery
@@ -12,6 +12,7 @@ from uuid import uuid4
from .cad_identity import CadBinding, current_desktop_name, verify_application, project_file_path
from .isolated_desktop import PrivateDesktop
from .worker_monitor import WorkerMonitorError
from .path_access import internal_path, canonical_path, retry_sharing_violation
class PrivateCadStartupError(WorkerMonitorError):
@@ -47,6 +48,7 @@ def is_identity_conflict(error):
def _helper_command(action, evidence, pid):
evidence = internal_path(evidence)
if getattr(sys, 'frozen', False):
return (sys.executable, '--private-cad-action', action, '--private-cad-evidence', str(evidence),
'--private-cad-pid', str(pid))
@@ -64,15 +66,7 @@ def _replace_record(temporary, target):
# Windows readers can temporarily deny delete access to the old JSON.
# Keep the complete old record until replacement succeeds, with a finite
# retry budget so persistent permissions failures still reach the caller.
deadline = time.monotonic() + 1.0
while True:
try:
temporary.replace(target)
return
except PermissionError:
if time.monotonic() >= deadline:
raise
time.sleep(0.02)
retry_sharing_violation(lambda: internal_path(temporary).replace(internal_path(target)), target=target)
def _designer_executable():
@@ -94,7 +88,7 @@ def _designer_executable():
class IsolatedCadSession:
"""The supervisor never attaches to COM on the user's input desktop."""
def __init__(self, root, *, abort_event=None, desktop=None):
self.root = Path(root).resolve()
self.root = canonical_path(root)
self.token = uuid4().hex
self.borrowed_desktop = desktop is not None
self.desktop = desktop if desktop is not None else PrivateDesktop('dx-' + self.token, enabled=True)
@@ -106,12 +100,12 @@ class IsolatedCadSession:
def _record(self, **values):
self.record.update(values)
self.root.mkdir(parents=True, exist_ok=True)
target = self.root / 'private-desktop.json'
internal_path(self.root).mkdir(parents=True, exist_ok=True)
target = internal_path(self.root / 'private-desktop.json')
temporary = target.with_suffix('.tmp')
temporary.write_text(json.dumps(self.record, ensure_ascii=False, indent=2), encoding='utf-8')
_replace_record(temporary, target)
history = self.root / 'private-desktop-sessions'
history = internal_path(self.root / 'private-desktop-sessions')
history.mkdir(exist_ok=True)
archived = history / (self.token + '.json')
pending = archived.with_suffix('.tmp')
@@ -144,7 +138,7 @@ class IsolatedCadSession:
finally:
probe.close()
try:
result = json.loads(bootstrap.read_text(encoding='utf-8'))
result = json.loads(internal_path(bootstrap).read_text(encoding='utf-8'))
binding = CadBinding(**result)
if (type(binding.pid) is not int or not isinstance(binding.guid, str) or not binding.guid
or (binding.pid, binding.desktop, binding.token) != (self.cad.pid, self.desktop.name, self.token)):
@@ -185,7 +179,7 @@ class IsolatedCadSession:
if self.binding is None or self.cad.poll() is not None:
raise WorkerMonitorError('owned CAD unavailable at project checkpoint')
evidence = Path(evidence)
evidence.parent.mkdir(parents=True, exist_ok=True)
internal_path(evidence.parent).mkdir(parents=True, exist_ok=True)
process = self.start_worker(_helper_command('checkpoint', evidence, self.cad.pid),
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
try:
@@ -195,7 +189,7 @@ class IsolatedCadSession:
raise failure_type('project close checkpoint failed: ' +
process.stderr.read().decode('utf-8', errors='replace'))
try:
result = json.loads(evidence.read_text(encoding='utf-8'))
result = json.loads(internal_path(evidence).read_text(encoding='utf-8'))
if (not isinstance(result, dict) or result.get('binding') != asdict(self.binding)
or result.get('project_path') != '' or result.get('project_closed') is not True):
raise ValueError('project close checkpoint identity mismatch')
@@ -294,7 +288,7 @@ def _run_native_action(action, evidence, expected_pid):
# COM startup can block inside a native call, so keep diagnostics outside
# the redirected pipes and retain them when the supervisor ends the child.
import faulthandler
with Path(str(evidence) + '.fault.txt').open('a', encoding='utf-8') as trace:
with internal_path(str(evidence) + '.fault.txt').open('a', encoding='utf-8') as trace:
faulthandler.dump_traceback_later(20, repeat=True, file=trace)
try:
return _native_action(action, evidence, expected_pid)
@@ -339,7 +333,7 @@ def _native_action(action, evidence, expected_pid):
verify_application(app, binding, require_view=False)
except ValueError as error:
raise CadIdentityConflict(str(error)) from error
Path(evidence).write_text(json.dumps(asdict(binding)), encoding='utf-8')
internal_path(evidence).write_text(json.dumps(asdict(binding)), encoding='utf-8')
elif action in {'quit', 'checkpoint'}:
try:
binding = CadBinding.from_environment()
@@ -75,24 +75,28 @@ class LoggingContext:
return reported
def configure_logging(root: Path) -> LoggingContext:
def configure_logging(root: Path, *, log_path: Path | None = None) -> LoggingContext:
"""Create storage directories and a UTF-8 rotating application log handler."""
storage_root = Path(root).resolve()
log_path = storage_root / "logs" / "application.log"
log_path.parent.mkdir(parents=True, exist_ok=True)
(storage_root / "tasks").mkdir(parents=True, exist_ok=True)
from .path_access import canonical_path, internal_path
storage_root = canonical_path(root)
separate_log = log_path is not None
log_path = canonical_path(log_path) if separate_log else storage_root / "logs" / "application.log"
internal_path(log_path.parent).mkdir(parents=True, exist_ok=True)
internal_path(storage_root / "tasks").mkdir(parents=True, exist_ok=True)
logger_name = "dx_productivity.trial_task_center." + hashlib.sha256(
str(storage_root.resolve()).encode("utf-8")
).hexdigest()[:16]
if separate_log:
logger_name += '.' + hashlib.sha256(str(log_path).encode('utf-8')).hexdigest()[:12]
logger = logging.getLogger(logger_name)
logger.setLevel(logging.DEBUG)
logger.propagate = False
if not any(
isinstance(handler, RotatingFileHandler) and Path(handler.baseFilename) == log_path
isinstance(handler, RotatingFileHandler) and canonical_path(handler.baseFilename) == log_path
for handler in logger.handlers
):
handler = RotatingFileHandler(
log_path,
internal_path(log_path),
maxBytes=_MAX_LOG_BYTES,
backupCount=_BACKUP_COUNT,
encoding="utf-8",
@@ -33,13 +33,36 @@ def internal_path(value):
return Path(windows_extended_path(value)) if os.name == 'nt' else Path(value)
def retry_sharing_violation(operation, *, sleep=time.sleep):
def _sharing_denial(error, target):
if getattr(error, 'winerror', None) in (32, 33):
return True
if os.name != 'nt' or getattr(error, 'winerror', None) != 5 or target is None:
return False
# MoveFileEx can report ACCESS_DENIED for a reader denying delete sharing.
# Confirm that specific condition, rather than retrying arbitrary ACL errors.
import ctypes
from ctypes import wintypes
kernel = ctypes.WinDLL('kernel32', use_last_error=True)
create = kernel.CreateFileW
create.argtypes = (wintypes.LPCWSTR, wintypes.DWORD, wintypes.DWORD, ctypes.c_void_p,
wintypes.DWORD, wintypes.DWORD, wintypes.HANDLE)
create.restype = wintypes.HANDLE
handle = create(str(internal_path(target)), 0x10000, 7, None, 3, 0, None)
if handle == ctypes.c_void_p(-1).value:
return ctypes.get_last_error() in (32, 33)
close = kernel.CloseHandle
close.argtypes = (wintypes.HANDLE,)
close(handle)
return False
def retry_sharing_violation(operation, *, target=None, sleep=time.sleep):
"""At most three attempts and 150ms delay; access denial is never replayed."""
for attempt in range(3):
try:
return operation()
except OSError as error:
if getattr(error, 'winerror', None) not in (32, 33) or attempt == 2:
if attempt == 2 or not _sharing_denial(error, target):
raise
sleep(.05 * (attempt + 1))
@@ -56,10 +56,13 @@ class TrialRunner:
logging_context: LoggingContext,
*,
probe_source_resolver: Callable[[TaskRecord, ProjectRecord], Path] | None = None,
recover_on_startup: bool = True,
) -> None:
self._store = store
self._logging = logging_context
self._probe_source_resolver = probe_source_resolver or self._default_probe_source
if not recover_on_startup:
return # Per-batch processes must not replay application-start recovery.
migration_recoveries = self._store.pending_migration_recoveries()
for recovery in migration_recoveries:
self._event_transition(
@@ -35,12 +35,26 @@ _QUICK_RUN_THREAD_LOCK = threading.Lock()
@contextmanager
def _quick_run_lease(root: Path):
from .batch_supervisor import mutation_lease
try:
with mutation_lease(root):
with _quick_run_lease_owned(root):
yield
except TaskCenterError as error:
if error.code == 'supervisor_busy':
raise TaskCenterError('quick_run_busy', '另一批操作正在执行,请先安全暂停。') from error
raise
@contextmanager
def _quick_run_lease_owned(root: Path):
if not _QUICK_RUN_THREAD_LOCK.acquire(blocking=False):
raise TaskCenterError("quick_run_busy", "another quick-run operation is already executing")
handle = None
locked = False
try:
lock_path = root / ".quick-run.execution.lock"
from .path_access import internal_path
lock_path = internal_path(root / ".quick-run.execution.lock")
lock_path.parent.mkdir(parents=True, exist_ok=True)
handle = lock_path.open("a+b")
if handle.seek(0, os.SEEK_END) == 0:
@@ -95,12 +109,26 @@ class TaskCenterService:
probe_source_resolver: Callable[[TaskRecord, ProjectRecord], Path] | None = None,
quick_run_preparer: QuickRunPreparer | None = None,
runner: TrialRunner | None = None,
supervised: bool = False,
recover_on_startup: bool = True,
) -> None:
self._store = store
self._logging = logging_context
self._path_opener = path_opener
self._clock = clock
self._runner = runner or TrialRunner(store, logging_context, probe_source_resolver=probe_source_resolver)
self._supervised = supervised
if runner is None and recover_on_startup:
from .batch_supervisor import assert_supervisor_idle, pending_supervisors
if pending_supervisors(logging_context.root):
recover_on_startup = False
try:
assert_supervisor_idle(logging_context.root)
except TaskCenterError as error:
if error.code != 'supervisor_busy':
raise
recover_on_startup = False
self._runner = runner or TrialRunner(store, logging_context, probe_source_resolver=probe_source_resolver,
**({'recover_on_startup': False} if not recover_on_startup else {}))
self._quick_run_preparer = quick_run_preparer or QuickRunPreparer(logging_context.root)
self._batch_feedback = None
self._project_facades: dict[str, TaskCenterService] = {}
@@ -143,6 +171,9 @@ class TaskCenterService:
lambda: export_template(self._store, task_id, path))
def preview_bom_batch(self, task_id: str, path: Path, *, stop_event=None, on_progress=None, runtime=None):
if runtime is None and self._supervised:
return self._supervise('preview_bom_batch', {'task_id': task_id, 'path': path},
stop_event=stop_event, on_progress=on_progress)
from .bom_batch import preview_batch
return self._idle_quick_run_operation('preview_bom_batch', task_id,
lambda: preview_batch(self, task_id, path, **control_options(stop_event, on_progress),
@@ -187,6 +218,7 @@ class TaskCenterService:
# the database. A facade shares the initialized runner instead.
child = TaskCenterService(self._store, self._logging, path_opener=self._path_opener,
clock=self._clock, quick_run_preparer=child_preparer, runner=self._runner)
child._supervised = self._supervised
self._project_facades[task_id] = child
return self._project_facades[task_id]
@@ -361,6 +393,8 @@ class TaskCenterService:
def target_cell_choices(self, task_id: str, new_part_number: str) -> tuple[str, ...]:
"""Read candidates for the captured batch; reject a changed project scope."""
if self._supervised:
return self._supervise('target_cell_choices', {'task_id': task_id, 'new_part_number': new_part_number})
from .cell_catalog import read_project_cell_choices
part_number = new_part_number.strip()
projects = self.target_cell_projects(task_id)
@@ -390,6 +424,9 @@ class TaskCenterService:
def collect_target_inventory(self, task_id: str, old_part_numbers: tuple[str, ...] | None = None,
*, stop_event=None, on_progress=None, runtime=None):
if runtime is None and self._supervised:
return self._supervise('collect_target_inventory', {'task_id': task_id, 'old_part_numbers': old_part_numbers},
stop_event=stop_event, on_progress=on_progress)
if runtime is None:
return self._owned_cad_operation('collect_inventory', lambda owned:
self.collect_target_inventory(task_id, old_part_numbers,
@@ -562,6 +599,8 @@ class TaskCenterService:
return self._operation("expected_probe_path", task_id, expected_path)
def prepare_quick_run(self, task_id: str, *, runtime=None) -> QuickRunResult:
if runtime is None and self._supervised:
return self._supervise('prepare_quick_run', {'task_id': task_id})
"""Create the legacy VBS handoff without starting a task-center trial."""
if runtime is None:
return self._owned_cad_operation('prepare_quick_run', lambda owned:
@@ -636,6 +675,8 @@ class TaskCenterService:
def execute_quick_run(self, task_id: str, *, expected_item: tuple[str, str, str, str] | None = None, runtime=None) -> QuickRunStepResult:
"""Execute one replacement rule through restoration and verification."""
if runtime is None and self._supervised:
return self._supervise('execute_quick_run', {'task_id': task_id, 'expected_item': expected_item})
if runtime is None:
return self._owned_cad_operation('quick_run_step', lambda owned:
self.execute_quick_run(task_id, expected_item=expected_item, runtime=owned), task_id=task_id)
@@ -679,6 +720,10 @@ class TaskCenterService:
reuse_project_session: bool = True,
runtime=None,
):
if runtime is None and self._supervised:
return self._supervise('execute_quick_run_queue', {'task_id': task_id, 'expected_item': expected_item,
'continue_after_backup_failure': continue_after_backup_failure,
'reuse_project_session': reuse_project_session}, stop_event=stop_event)
if runtime is None:
from .batch_runtime import BatchCadRuntime
with BatchCadRuntime(self._logging.root, 'quick_run_queue', stop_event) as owned_runtime:
@@ -735,6 +780,8 @@ class TaskCenterService:
def prepare_failed_quick_run(self, task_id: str, *, runtime=None) -> QuickRunProgress:
"""Reset only failed projects and discard the finished queue handoff."""
if runtime is None and self._supervised:
return self._supervise('prepare_failed_quick_run', {'task_id': task_id})
if runtime is None:
return self._owned_cad_operation('prepare_failed_quick_run', lambda owned:
self.prepare_failed_quick_run(task_id, runtime=owned), task_id=task_id)
@@ -816,10 +863,21 @@ class TaskCenterService:
def pending_batch_resources(self):
from .batch_runtime import pending_resources
return pending_resources(self._logging.root)
from .batch_supervisor import pending_supervisors
return (*pending_resources(self._logging.root), *pending_supervisors(self._logging.root))
def export_diagnostics(self, destination: Path) -> Path:
from .diagnostics_bundle import export_diagnostic_bundle
return self._operation('export_diagnostics', None,
lambda: export_diagnostic_bundle(self._logging.root, destination))
def cleanup_batch_resources(self):
"""Retry owned-resource release without opening or changing any project."""
if self._supervised:
result = self._supervise('cleanup_batch_resources', {})
from .batch_supervisor import reconcile_supervisors
reconcile_supervisors(self._logging.root)
return self.pending_batch_resources()
from .batch_runtime import cleanup_pending_resources
from .task_queue import assert_task_queue_idle
assert_task_queue_idle(self._logging.root)
@@ -828,6 +886,9 @@ class TaskCenterService:
lambda: cleanup_pending_resources(self._logging.root, logging_context=self._logging))
def inspect_bom_batch(self, task_id: str, path: Path, *, stop_event=None, on_progress=None, on_phase=None, runtime=None):
if runtime is None and self._supervised:
return self._supervise('inspect_bom_batch', {'task_id': task_id, 'path': path},
stop_event=stop_event, on_progress=on_progress, on_phase=on_phase)
from .bom_import_report import inspect_batch
return self._idle_quick_run_operation('inspect_bom_batch', task_id,
lambda: inspect_batch(self, task_id, path, on_phase=on_phase, runtime=runtime,
@@ -888,6 +949,8 @@ class TaskCenterService:
return self._quick_run_preparer.has_interrupted(task_id)
def recover_quick_run(self, task_id: str, *, confirmed: bool = False, runtime=None) -> QuickRunStepResult:
if runtime is None and self._supervised:
return self._supervise('recover_quick_run', {'task_id': task_id, 'confirmed': confirmed})
if runtime is None:
return self._owned_cad_operation('recover_quick_run', lambda owned:
self.recover_quick_run(task_id, confirmed=confirmed, runtime=owned), task_id=task_id)
@@ -1046,6 +1109,11 @@ class TaskCenterService:
self._logging.logger.info("operation_complete=%s task_id=%s at=%s", name, task_id or "", completed_timestamp)
return result
def _supervise(self, operation, arguments, **controls):
from .batch_supervisor import run_supervised
return self._operation(operation, arguments.get('task_id'),
lambda: run_supervised(self, operation, arguments, **controls))
def _idle_quick_run_operation(
self,
name: str,
@@ -1080,6 +1148,8 @@ class TaskCenterService:
self._execution_rules(task_id),
copy_part_number_to_value=task.copy_part_number_to_value,
)
if self._supervised:
return progress # Only the batch process persists live execution state.
by_path = {os.path.normcase(os.path.abspath(str(project.path))): project.project_id for project in projects}
project_by_id = {project.project_id: project for project in projects}
summary_by_id = {
@@ -125,11 +125,12 @@ class TaskStore:
def __init__(self, path: Path) -> None:
self.path = Path(path)
self.path.parent.mkdir(parents=True, exist_ok=True)
from .path_access import internal_path
internal_path(self.path.parent).mkdir(parents=True, exist_ok=True)
self._lock = threading.RLock()
self._transaction_depth = 0
self._savepoint_index = 0
self._connection = sqlite3.connect(self.path, isolation_level=None, check_same_thread=False)
self._connection = sqlite3.connect(internal_path(self.path), isolation_level=None, check_same_thread=False)
self._connection.row_factory = sqlite3.Row
with self._lock:
self._connection.execute("PRAGMA foreign_keys = ON")
@@ -0,0 +1,130 @@
"""Versioned, allowlisted JSON values exchanged with the batch supervisor."""
from __future__ import annotations
from dataclasses import fields, is_dataclass
from datetime import datetime
from enum import Enum
from functools import lru_cache
from pathlib import Path
import re
from .errors import TaskCenterError
VERSION = 1
OPERATIONS = frozenset({'probe', 'runtime_smoke', 'inspect_bom_batch', 'preview_bom_batch',
'collect_target_inventory', 'execute_task_queue', 'execute_quick_run_queue', 'execute_quick_run',
'prepare_quick_run', 'prepare_failed_quick_run', 'recover_quick_run', 'cleanup_batch_resources',
'target_cell_choices'})
def valid_journal(value, batch_id):
def identity(item):
return (isinstance(item, dict) and type(item.get('pid')) is int and item['pid'] > 0
and isinstance(item.get('creation_time'), str) and bool(item['creation_time']))
return (isinstance(value, dict) and value.get('version') == VERSION and value.get('batch_id') == batch_id
and isinstance(batch_id, str) and re.fullmatch('[0-9a-f]{32}', batch_id) is not None
and isinstance(value.get('attempt_id'), str) and re.fullmatch('[0-9a-f]{32}', value['attempt_id']) is not None
and value.get('operation') in OPERATIONS and value.get('state') in {'starting', 'running', 'blocked', 'finished'}
and isinstance(value.get('task_ids'), list) and all(isinstance(v, str) and v and Path(v).name == v
and v not in {'.', '..'} for v in value['task_ids'])
and identity(value.get('parent_process')) and (value.get('process') is None or identity(value['process']))
and isinstance(value.get('request_sha256'), str) and re.fullmatch('[0-9a-f]{64}', value['request_sha256']) is not None)
@lru_cache(maxsize=1)
def _types():
from . import models, target_plan, quick_run_protocol, bom_batch, bom_import_report, task_queue, bom_import_state, batch
modules = (models, target_plan, quick_run_protocol, bom_batch, bom_import_report, task_queue, bom_import_state, batch)
return {value.__module__ + '.' + value.__name__: value
for module in modules for value in vars(module).values()
if isinstance(value, type) and value.__module__ == module.__name__
and (is_dataclass(value) or issubclass(value, Enum))}
def encode(value):
if isinstance(value, Enum):
return {'type': 'enum', 'name': type(value).__module__ + '.' + type(value).__name__, 'value': value.value}
if value is None or type(value) in (str, int, float, bool):
return value
if isinstance(value, Path):
return {'type': 'path', 'value': str(value)}
if isinstance(value, datetime):
return {'type': 'datetime', 'value': value.isoformat()}
if type(value) in (tuple, list, frozenset):
return {'type': type(value).__name__, 'items': [encode(item) for item in value]}
if isinstance(value, dict):
return {'type': 'dict', 'items': [[encode(key), encode(item)] for key, item in value.items()]}
if is_dataclass(value):
name = type(value).__module__ + '.' + type(value).__name__
if name in _types():
return {'type': 'object', 'name': name,
'fields': {field.name: encode(getattr(value, field.name)) for field in fields(value)}}
raise ValueError('Unsupported supervisor value: ' + type(value).__name__)
def decode(value):
if value is None or type(value) in (str, int, float, bool):
return value
if not isinstance(value, dict):
raise ValueError('Invalid supervisor value')
kind = value.get('type')
if kind == 'path':
return Path(value['value'])
if kind == 'datetime':
return datetime.fromisoformat(value['value'])
if kind in ('tuple', 'list', 'frozenset'):
return {'tuple': tuple, 'list': list, 'frozenset': frozenset}[kind](decode(v) for v in value['items'])
if kind == 'dict':
return {decode(k): decode(v) for k, v in value['items']}
cls = _types().get(value.get('name'))
if cls is None:
raise ValueError('Unknown supervisor type')
if kind == 'enum' and issubclass(cls, Enum):
return cls(value['value'])
if kind == 'object' and is_dataclass(cls):
if set(value['fields']) != {f.name for f in fields(cls)}:
raise ValueError('Supervisor record fields do not match schema')
return cls(**{key: decode(v) for key, v in value['fields'].items()})
raise ValueError('Invalid supervisor type')
def encode_error(error, *, depth=0):
result = {'code': getattr(error, 'code', 'supervisor_operation'),
'message': getattr(error, 'message', str(error)),
'error_id': getattr(error, 'error_id', None)}
for key in ('bom_report', 'completed_result'):
if getattr(error, key, None) is not None:
result[key] = encode(getattr(error, key))
if depth < 3:
for key in ('primary_error', 'cleanup_error'):
other = getattr(error, key, None)
if other is not None and other is not error:
result[key] = encode_error(other, depth=depth + 1)
return result
def decode_error(value):
error = TaskCenterError(value['code'], value['message'], error_id=value.get('error_id'))
for key in ('bom_report', 'completed_result'):
if key in value:
setattr(error, key, decode(value[key]))
for key in ('primary_error', 'cleanup_error'):
if key in value:
setattr(error, key, decode_error(value[key]))
return error
class MessageGate:
def __init__(self, batch_id, attempt_id):
self.batch_id, self.attempt_id = batch_id, attempt_id
self.sequence, self.generation = 0, 1
def accept(self, value):
if (not isinstance(value, dict) or value.get('version') != VERSION
or value.get('batch_id') != self.batch_id or value.get('attempt_id') != self.attempt_id
or type(value.get('sequence')) is not int or value['sequence'] <= self.sequence
or type(value.get('generation')) is not int or value['generation'] < self.generation
or value.get('type') not in {'progress', 'phase', 'heartbeat', 'result', 'state'}):
return False
self.sequence, self.generation = value['sequence'], value['generation']
return True
@@ -0,0 +1,50 @@
"""Validate business evidence before changing any supervisor safety gate."""
from .supervisor_protocol import decode, decode_error
def validated_outcome(operation, body):
from .batch import BatchRunResult
from .bom_import_report import BomImportReport
from .bom_batch import BomBatchPreview
from .quick_run_protocol import QuickRunResult, QuickRunStepResult, QuickRunProgress
from .target_plan import TargetPlanRow
from .task_queue import TaskQueueResult
if (not isinstance(body, dict) or type(body.get('business_succeeded')) is not bool
or body.get('status') not in {'ok', 'error'}):
raise ValueError('Invalid supervisor business outcome')
result = decode(body['result']) if body['business_succeeded'] else None
expected = {'inspect_bom_batch': BomImportReport, 'preview_bom_batch': BomBatchPreview,
'execute_task_queue': TaskQueueResult, 'execute_quick_run_queue': BatchRunResult,
'execute_quick_run': QuickRunStepResult, 'recover_quick_run': QuickRunStepResult,
'prepare_quick_run': QuickRunResult, 'prepare_failed_quick_run': QuickRunProgress,
'collect_target_inventory': tuple, 'target_cell_choices': tuple,
'cleanup_batch_resources': tuple, 'probe': dict, 'runtime_smoke': dict}
if body['business_succeeded'] and not isinstance(result, expected[operation]):
raise ValueError('Supervisor result type does not match requested operation')
if body['business_succeeded'] and operation == 'collect_target_inventory' and not all(isinstance(v, TargetPlanRow) for v in result):
raise ValueError('Invalid inventory plan result')
errors = []
for name in ('error', 'operation_error'):
value = body.get(name)
if value is not None and (not isinstance(value, dict) or not isinstance(value.get('code'), str)
or not isinstance(value.get('message'), str)):
raise ValueError('Invalid supervisor failure')
errors.append(decode_error(value) if value is not None else None)
if not body['business_succeeded'] and not any(errors):
raise ValueError('Failed supervisor outcome has no failure evidence')
return result, *errors
def resource_pending_error(operation, result, error, primary_error=None):
from dataclasses import replace
from .batch_resources import BatchResourceCleanupError
from .bom_import_report import BomImportReport
if isinstance(result, BomImportReport):
result = replace(result, preview=None)
failure = BatchResourceCleanupError('后台资源仍待清理;报告和已保存核验结果保留。' + (str(error) if error else ''),
completed_result=result, primary_error=primary_error, cleanup_error=error)
if isinstance(result, BomImportReport):
failure.bom_report = result
elif getattr(error, 'bom_report', None) is not None:
failure.bom_report = replace(error.bom_report, preview=None)
return failure
@@ -47,6 +47,8 @@ def _os_lock(handle, acquire):
def _lock_file(root: Path):
from .path_access import internal_path
root = internal_path(root)
root.mkdir(parents=True, exist_ok=True)
handle = (root / '.task-queue.execution.lock').open('a+b')
if handle.seek(0, os.SEEK_END) == 0:
@@ -57,6 +59,8 @@ def _lock_file(root: Path):
def assert_task_queue_idle(root: Path) -> None:
"""Reject external mutations while a queue owns CAD; its runner may call services."""
from .batch_supervisor import assert_supervisor_idle
assert_supervisor_idle(root)
if _QUEUE_OWNER == get_ident():
return
if _QUEUE_LOCK.locked():
@@ -122,6 +126,8 @@ def _save(path: Path, state: dict) -> None:
def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
queue_id: str | None = None, runtime=None) -> TaskQueueResult:
"""Execute the frozen order; uncertain state stops before the next project."""
if runtime is None and getattr(service, '_supervised', False):
return service._supervise('execute_task_queue', {'task_ids': task_ids, 'queue_id': queue_id}, stop_event=stop_event)
if runtime is None:
from .batch_runtime import BatchCadRuntime
with BatchCadRuntime(service._logging.root, 'task_queue', stop_event) as owned_runtime:
@@ -4,7 +4,7 @@ from threading import Event
from shiboken6 import isValid
import time
from PySide6.QtCore import QElapsedTimer, QSettings, QSignalBlocker, QThreadPool, QTimer, Qt
from PySide6.QtWidgets import (QApplication, QCheckBox, QDialog, QHBoxLayout, QMainWindow, QMessageBox,
from PySide6.QtWidgets import (QApplication, QCheckBox, QDialog, QFileDialog, QHBoxLayout, QMainWindow, QMessageBox,
QPushButton, QLabel, QSplitter, QTabWidget, QVBoxLayout, QWidget)
from ..errors import TaskCenterError
from ..models import TaskStatus
@@ -12,7 +12,7 @@ from ..version import VERSION
from .dialogs import _TaskDialog, _MappingDialog
from .execution_state import execution_state
from .mapping_table import MappingTable
from .messages import ERROR_TEXT, _format_live_log_line
from .messages import ERROR_TEXT, _format_live_log_line, format_operation_error
from .project_plan import DirectoryTaskDialog, ProjectPlanPanel
from .project_summary import ProjectSummary
from .run_panel import RunPanel
@@ -91,6 +91,7 @@ class TrialTaskCenterWindow(QMainWindow):
self.run_panel.retry_button.clicked.connect(self._retry_failed)
self.run_panel.recover_button.clicked.connect(self._recover_quick_run)
self.run_panel.cleanup_resources_button.clicked.connect(self._cleanup_batch_resources)
self.run_panel.diagnostics_button.clicked.connect(self._export_diagnostics)
self.run_panel.new_round_button.clicked.connect(self._start_new_round)
self.run_panel.history_button.clicked.connect(self._open_round_history)
self.run_panel.copy_value_check.toggled.connect(self._value_option_changed)
@@ -114,6 +115,8 @@ class TrialTaskCenterWindow(QMainWindow):
widget.restoreState(saved)
self._refresh_task_list()
self._update_gates()
if getattr(service, '_supervised', False):
QTimer.singleShot(0, self._startup_resource_recheck)
@property
def _loading(self):
@@ -620,6 +623,25 @@ class TrialTaskCenterWindow(QMainWindow):
self._run_async(self.service.cleanup_batch_resources, done,
self.run_panel.cleanup_resources_button)
def _startup_resource_recheck(self):
if self._closed:
return
if self._workers or self._loading:
QTimer.singleShot(250, self._startup_resource_recheck)
return
if self.service.pending_batch_resources():
self._update_gates()
self._cleanup_batch_resources() # Resource-only; never resumes a queue.
def _export_diagnostics(self):
from pathlib import Path
name = 'DxPartReplace-诊断-' + time.strftime('%Y%m%d-%H%M%S') + '.zip'
value, _ = QFileDialog.getSaveFileName(self, '导出脱敏诊断包', name, 'ZIP 文件 (*.zip)')
if value:
self._run_async(lambda: self.service.export_diagnostics(Path(value)),
lambda path: self._set_operator_message(f'脱敏诊断包已导出:{path}', 'success'),
self.run_panel.diagnostics_button)
def _retry_failed(self):
if self.run_panel.retry_button.isEnabled():
task_id = self._task_id
@@ -812,7 +834,7 @@ class TrialTaskCenterWindow(QMainWindow):
def _show_error(self, error, *, owner_task_id=None, **_unused):
stable = error if isinstance(error, TaskCenterError) else self.service.report_ui_error(error)
message = f'{ERROR_TEXT.get(stable.code, "操作未完成")}\n{stable.message}\n错误编号:{stable.error_id}'
message = format_operation_error(stable)
if owner_task_id:
name = next((t.name for t in self._tasks if t.task_id == owner_task_id), owner_task_id)
message = f'任务「{name}」:{message}'
@@ -4,7 +4,9 @@ import json
import re
ERROR_TEXT = {
"batch_resources_pending": "已核验的替换结果已保留。后台资源尚未释放,请使用“重新清理资源”后再开始下一批。",
"batch_resources_pending": "后台资源尚未确认释放,请使用“重新清理资源”后再开始下一批。",
"supervisor_busy": "另一批操作正在执行,请先安全收尾。",
"supervisor_interrupted": "批次监督连接异常,保护记录已保留,没有自动重放替换。",
"inventory_session": "原生读取会话异常,安全重试未完成,已停止本批处理。请查看诊断记录并排除原因后重试。",
"task_required": "请先选择任务。",
"directory_required": "请先选择工程目录。",
@@ -50,6 +52,28 @@ ERROR_TEXT = {
"task_name": "任务名称为空或已经存在。",
}
def format_operation_error(error):
title = ERROR_TEXT.get(error.code, '操作未完成')
report = getattr(error, 'bom_report', None)
if report is not None:
title = 'BOM 导入未完成,校验报告已保留。' + title
result = getattr(error, 'completed_result', None)
if (getattr(result, 'state', None) == 'saved_ok'
or getattr(getattr(result, 'progress', None), 'saved_items', 0)
or any(getattr(entry, 'state', None) == 'completed' for entry in getattr(result, 'entries', ()))):
title += ' 已保存核验的结果保留,不会重新替换。'
lines = [title]
for label, name, limit in (('首次错误', 'primary_error', 180), ('收尾错误', 'cleanup_error', 140)):
failure = getattr(error, name, None)
if failure is not None:
text = getattr(failure, 'message', str(failure)).replace('\n', ' ')
lines.append(f'{label}:{text[:limit]}' + ('…' if len(text) > limit else ''))
if len(lines) == 1:
lines.append(error.message[:260])
lines.append('错误编号:' + error.error_id)
return '\n'.join(lines)
DIALOG_ERROR_TEXT = {
"duplicate_source": "该旧料号已经存在,请修改现有规则或输入其他旧料号。",
"mapping_chain": "目标料号同时是另一条规则的旧料号,请拆分任务后再执行。",
@@ -27,6 +27,8 @@ class RunPanel(QWidget):
self.recover_button = QPushButton('核验并恢复', objectName='recoverQuickRunButton')
self.cleanup_resources_button = QPushButton('重新清理资源', objectName='cleanupBatchResources')
self.cleanup_resources_button.setToolTip('只释放本程序拥有的后台资源,不执行工程替换。')
self.diagnostics_button = QPushButton('导出诊断包', objectName='exportDiagnosticBundle')
self.diagnostics_button.setToolTip('导出脱敏日志与资源记录,不包含工程、中心库、BOM 或任务数据库。')
self.new_round_button = QPushButton('开始新一轮', objectName='startNewRoundButton')
self.history_button = QPushButton('查看轮次证据', objectName='roundHistoryButton')
self.copy_value_check = QCheckBox('Value 策略:替换后将 Part Label 写入 Value(逐行自定义优先)', objectName='copyPartNumberToValue')
@@ -39,7 +41,7 @@ class RunPanel(QWidget):
self.log_dialog = None
self.toggle_log_button.toggled.connect(self._toggle_log)
buttons = QHBoxLayout()
for button in (self.quick_run_button, self.retry_button, self.recover_button, self.cleanup_resources_button,
for button in (self.quick_run_button, self.retry_button, self.recover_button, self.cleanup_resources_button, self.diagnostics_button,
self.new_round_button, self.history_button, self.stop_queue_button):
buttons.addWidget(button)
buttons.addStretch()
@@ -208,6 +208,10 @@ def test_runtime_smoke_tracks_real_process_and_releases_on_failure(tmp_path, mon
else:
_smoke_batch_runtime(tmp_path, configure_logging(tmp_path))
paths = list((tmp_path / 'batch-resources').glob('*/session.json'))
if missing_dependency:
# The GUI now verifies supervisor identity before launching anything.
assert not paths
return
assert len(paths) == 1
record = json.loads(paths[0].read_text(encoding='utf-8'))
assert record['state'] == 'released' and record['cad_pid'] is None
+129
View File
@@ -0,0 +1,129 @@
from pathlib import Path
import os
import json
import subprocess
import pytest
def test_supervisor_runs_in_other_process_and_releases_gate(tmp_path):
from dx_productivity.trial_task_center.batch_supervisor import run_supervised, assert_supervisor_idle
from dx_productivity.trial_task_center.logging_setup import configure_logging
from dx_productivity.trial_task_center.store import TaskStore
from dx_productivity.trial_task_center.service import TaskCenterService
store = TaskStore(tmp_path/'task-center.db')
try:
service = TaskCenterService(store, configure_logging(tmp_path))
result = run_supervised(service, 'probe', {})
assert result['pid'] != os.getpid()
assert result['resource_state'] == 'not_acquired'
assert_supervisor_idle(tmp_path)
finally:
store.close()
def test_mutation_guard_refuses_owned_launch_gate(tmp_path):
from dx_productivity.trial_task_center.batch_supervisor import supervisor_lease, assert_supervisor_idle
from dx_productivity.trial_task_center.errors import TaskCenterError
with supervisor_lease(tmp_path):
with pytest.raises(TaskCenterError, match='supervisor_busy'):
assert_supervisor_idle(tmp_path)
def test_child_error_returns_original_code_without_acquiring_desktop(tmp_path):
from dx_productivity.trial_task_center.batch_supervisor import run_supervised
from dx_productivity.trial_task_center.logging_setup import configure_logging
from dx_productivity.trial_task_center.store import TaskStore
from dx_productivity.trial_task_center.service import TaskCenterService
from dx_productivity.trial_task_center.errors import TaskCenterError
store = TaskStore(tmp_path/'task-center.db')
try:
service = TaskCenterService(store, configure_logging(tmp_path))
with pytest.raises(TaskCenterError) as caught:
run_supervised(service, 'inspect_bom_batch', {'task_id':'missing','path':tmp_path/'absent.xlsx'})
assert caught.value.code != 'supervisor_protocol'
assert not list((tmp_path/'batch-resources').glob('*/session.json'))
finally:
store.close()
def test_completed_worker_request_cannot_be_replayed(tmp_path):
from dx_productivity.trial_task_center.batch_supervisor import run_supervised, _command, _environment
from dx_productivity.trial_task_center.logging_setup import configure_logging
from dx_productivity.trial_task_center.store import TaskStore
from dx_productivity.trial_task_center.service import TaskCenterService
store = TaskStore(tmp_path/'task-center.db')
try:
service = TaskCenterService(store, configure_logging(tmp_path))
run_supervised(service, 'probe', {})
request = next((tmp_path/'batch-resources').glob('*/request.json'))
claim = request.with_name('claim.json').read_bytes()
result = request.with_name('result.json').read_bytes()
duplicate = subprocess.run(_command(request), env=_environment(), capture_output=True, timeout=30,
creationflags=subprocess.CREATE_NO_WINDOW)
assert duplicate.returncode != 0
assert request.with_name('claim.json').read_bytes() == claim
assert request.with_name('result.json').read_bytes() == result
finally:
store.close()
def test_missing_write_result_preserves_protection_marker(tmp_path):
from dx_productivity.trial_task_center.batch_supervisor import _mark_interrupted
journal = {'version': 1, 'batch_id': 'a'*32, 'attempt_id':'b'*32,
'operation':'execute_task_queue', 'task_ids':['task'], 'state':'running'}
_mark_interrupted(tmp_path, journal, 'worker exited unexpectedly')
marker = tmp_path/'tasks/task/quick-run/uncertain.flag'
assert marker.exists()
marker.write_text('original stronger reason')
_mark_interrupted(tmp_path, journal, 'another cleanup failure')
assert marker.read_text() == 'original stronger reason'
def test_cancelled_request_does_not_launch_supervisor(tmp_path):
from threading import Event
from types import SimpleNamespace
from dx_productivity.trial_task_center.batch_supervisor import run_supervised
from dx_productivity.trial_task_center.errors import TaskCenterError
stop = Event(); stop.set()
with pytest.raises(TaskCenterError, match='operation_cancelled'):
run_supervised(SimpleNamespace(_logging=SimpleNamespace(root=tmp_path)), 'probe', {}, stop_event=stop)
assert not (tmp_path/'batch-resources').exists()
def test_parent_job_cleanup_failure_preserves_result_and_can_retry_resources_only(tmp_path, monkeypatch):
from dx_productivity.trial_task_center.batch_supervisor import run_supervised
from dx_productivity.trial_task_center.isolated_desktop import _Win32Api
from dx_productivity.trial_task_center.logging_setup import configure_logging
from dx_productivity.trial_task_center.store import TaskStore
from dx_productivity.trial_task_center.service import TaskCenterService
from dx_productivity.trial_task_center.errors import TaskCenterError
original = _Win32Api.create_process
injected = []
def create(api, *args, **kwargs):
process = original(api, *args, **kwargs)
if not injected:
injected.append(process)
close = process.close
attempts = []
def interrupted_close():
if not attempts:
attempts.append(1)
raise OSError('injected parent Job close failure')
close()
process.close = interrupted_close
return process
monkeypatch.setattr(_Win32Api, 'create_process', create)
store = TaskStore(tmp_path/'task-center.db')
try:
service = TaskCenterService(store, configure_logging(tmp_path), supervised=True)
with pytest.raises(TaskCenterError) as caught:
run_supervised(service, 'probe', {})
assert caught.value.code == 'batch_resources_pending'
assert caught.value.completed_result['pid'] != os.getpid()
saved = next((tmp_path/'batch-resources').glob('*/business-result.json'))
before = saved.read_bytes()
assert service.cleanup_batch_resources() == ()
assert saved.read_bytes() == before
assert not service.pending_batch_resources()
finally:
store.close()
@@ -0,0 +1,41 @@
import json
from pathlib import Path
import pytest
def test_new_process_cache_instance_reuses_only_verified_identity(tmp_path):
from dx_productivity.trial_task_center.discovery_cache import DiscoveryCache
from dx_productivity.trial_task_center.quick_run_protocol import ProjectDiscovery
project = tmp_path/'project/demo.prj'
project.parent.mkdir()
project.write_text('project')
root = tmp_path/'data'
discovery = ProjectDiscovery((('main','1'),), {('main','1'):frozenset({'OLD'})})
calls = []
def loader():
calls.append(1)
return discovery
assert DiscoveryCache(root).discover(project, ('OLD',), False, loader) == discovery
assert DiscoveryCache(root).discover(project, ('OLD',), False, loader) == discovery
assert len(calls) == 1
project.write_text('changed')
DiscoveryCache(root).discover(project, ('OLD',), False, loader)
assert len(calls) == 2
def test_corrupted_disk_cache_is_quarantined_and_read_once(tmp_path):
from dx_productivity.trial_task_center.discovery_cache import DiscoveryCache
from dx_productivity.trial_task_center.quick_run_protocol import ProjectDiscovery
project = tmp_path/'p/demo.prj';project.parent.mkdir();project.write_text('project')
root=tmp_path/'data'
discovery=ProjectDiscovery((('main','1'),),{('main','1'):frozenset({'OLD'})})
DiscoveryCache(root).discover(project,('OLD',),False,lambda:discovery)
paths=list((root/'discovery-cache').glob('*.json'))
assert len(paths)==1
paths[0].write_text('{broken')
calls=[]
def loader():
calls.append(1);return discovery
assert DiscoveryCache(root).discover(project,('OLD',),False,loader)==discovery
assert calls==[1]
assert list((root/'discovery-cache').glob('*.bad-*'))
+2 -1
View File
@@ -12,7 +12,8 @@ def test_project_access_resolves_each_distinct_input_once_per_preparation(tmp_pa
(tmp_path/'command.tsv').write_text('project_path\n'+(str(project)+'\n')*1000,encoding='utf8')
original=Path.resolve;calls=[]
def resolve(path,*args,**kwargs):
if path==project:calls.append(path)
from dx_productivity.trial_task_center.path_access import strip_extended_prefix
if Path(strip_extended_prefix(path))==project:calls.append(path)
return original(path,*args,**kwargs)
monkeypatch.setattr(Path,'resolve',resolve)
legacy_paths._prepare_project_access(tmp_path)
+54
View File
@@ -0,0 +1,54 @@
import json
from pathlib import Path
import pytest
def test_wire_roundtrip_preserves_bom_preview_and_identity(tmp_path):
from dx_productivity.trial_task_center.supervisor_protocol import encode, decode
from dx_productivity.trial_task_center.bom_import_report import BomImportReport, BomRowResult
from dx_productivity.trial_task_center.bom_batch import BomBatchPreview, BomProjectPreview
from dx_productivity.trial_task_center.target_plan import ComponentTarget, TargetPlanRow
target = ComponentTarget(tmp_path/'中文.prj', 'Main', '1', 'uid', 'R1', 'OLD', '1K')
row = TargetPlanRow(target, True, 'NEW')
preview = BomBatchPreview('task', (('task', str(target.project_path)),),
(BomProjectPreview('task', target.project_path, (), (target,), (row,)),))
report = BomImportReport((BomRowResult(2, str(target.project_path), '中文', 'passed'),), (), preview)
assert decode(json.loads(json.dumps(encode(report)))) == report
def test_protocol_rejects_unknown_types_and_late_results():
from dx_productivity.trial_task_center.supervisor_protocol import decode, MessageGate
with pytest.raises(ValueError):
decode({'type': 'object', 'name': 'os.system', 'fields': {}})
gate = MessageGate('batch', 'attempt')
current = dict(version=1, batch_id='batch', attempt_id='attempt', generation=1, sequence=1, type='heartbeat', payload=None)
assert gate.accept(current)
assert not gate.accept(current)
assert not gate.accept(dict(current, sequence=2, attempt_id='old'))
assert not gate.accept(dict(current, sequence=2, generation=0))
assert gate.accept(dict(current, sequence=2, generation=2))
assert not gate.accept(dict(current, sequence=3, generation=1))
def test_wire_error_retains_bom_report_and_primary_cleanup():
from dx_productivity.trial_task_center.supervisor_protocol import encode_error, decode_error
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.bom_import_report import BomImportReport
error = TaskCenterError('batch_resources_pending', '收尾失败', error_id='support-id')
error.primary_error = TaskCenterError('path_access', '目录创建失败')
error.cleanup_error = TaskCenterError('private_desktop_cleanup', '桌面残留')
error.bom_report = BomImportReport((), (), errors=('原始问题',))
actual = decode_error(json.loads(json.dumps(encode_error(error))))
assert actual.error_id == 'support-id'
assert actual.primary_error.code == 'path_access'
assert actual.cleanup_error.code == 'private_desktop_cleanup'
assert actual.bom_report.errors == ('原始问题',)
def test_single_task_batch_result_wire_roundtrip():
from dx_productivity.trial_task_center.supervisor_protocol import encode, decode
from dx_productivity.trial_task_center.batch import BatchRunResult
from dx_productivity.trial_task_center.quick_run_protocol import QuickRunProgress
progress = QuickRunProgress(1,1,None,None,None,(),True,saved_items=1)
actual = BatchRunResult(progress,False,item_messages=('saved',))
assert decode(encode(actual)) == actual
+23
View File
@@ -0,0 +1,23 @@
import pytest
@pytest.mark.parametrize('body', [None, {}, {'status':'ok','business_succeeded':'yes','result':'bad'},
{'status':'ok','business_succeeded':True,'result':'wrong type'}])
def test_invalid_result_cannot_finish_resource_gate(tmp_path, body):
from dx_productivity.trial_task_center.batch_supervisor import _finish_response
from dx_productivity.trial_task_center.logging_setup import configure_logging
journal={'operation':'probe','batch_id':'a'*32,'state':'blocked'}
with pytest.raises((ValueError, KeyError, TypeError)):
_finish_response(tmp_path,journal,body,configure_logging(tmp_path))
assert journal['state']=='blocked'
assert not (tmp_path/'batch-resources').exists()
def test_pending_cleanup_cannot_expose_bom_preview():
from dx_productivity.trial_task_center.bom_import_report import BomImportReport
from dx_productivity.trial_task_center.bom_batch import BomBatchPreview
from dx_productivity.trial_task_center.supervisor_result import resource_pending_error
report=BomImportReport((),(),BomBatchPreview('task',(),()))
error=resource_pending_error('inspect_bom_batch',report,OSError('held desktop'))
assert error.completed_result.preview is None
assert error.bom_report.preview is None