diff --git a/src/dx_productivity/trial_task_center/batch.py b/src/dx_productivity/trial_task_center/batch.py index 6f5de9d..1401f7a 100644 --- a/src/dx_productivity/trial_task_center/batch.py +++ b/src/dx_productivity/trial_task_center/batch.py @@ -1,15 +1,11 @@ """Serial, confirmed queue execution with safe between-item pausing.""" from dataclasses import dataclass -from concurrent.futures import Future, ThreadPoolExecutor -import hashlib import json -import os from pathlib import Path import shutil from threading import Event import time -from uuid import uuid4 from .errors import TaskCenterError from .logging_setup import append_task_event @@ -17,7 +13,6 @@ from .models import TaskStatus from .quick_run import ( BATCH_FAILED_STATE, BATCH_SAVED_UNVERIFIED_STATE, - TERMINAL_STATES, QuickRunProgress, QuickRunStepResult, _path_key, @@ -26,10 +21,12 @@ from .quick_run import ( from .retention import maintain_quick_run_storage from .schematic_backup import create_schematic_backup from .execution_metrics import measure_phase - - -_BACKUP_STATE_NAME = 'batch-backups.json' -_BACKUP_DIRECTORY_NAME = 'batch-backups' +# Keep legacy helper imports patchable for queue integrations. +from .batch_backup import ( + BatchBackupCoordinator, + _BACKUP_STATE_NAME, _BACKUP_DIRECTORY_NAME, + _backup_key, _read_backup_state, _write_backup_state, _reusable_backup, +) @dataclass(frozen=True) @@ -50,7 +47,7 @@ def execute_batch( continue_after_backup_failure: bool = False, ) -> BatchRunResult: preparer = service._quick_run_preparer - retention = maintain_quick_run_storage(preparer._data_root) + retention = maintain_quick_run_storage(preparer.data_root) if retention.removed_entries or retention.skipped_entries: service._logging.logger.info( 'quick_run_retention removed=%s removed_bytes=%s skipped=%s', @@ -68,7 +65,7 @@ def execute_batch( return BatchRunResult(progress, False) if expected_item is None or actual != expected_item: raise TaskCenterError('quick_run_selection_changed', '队列起点或 Value 选项发生变化,请重新确认。') - if (preparer._data_root / 'quick-run/uncertain.flag').exists(): + if (preparer.data_root / 'quick-run/uncertain.flag').exists(): raise TaskCenterError('quick_run_uncertain', '队列存在待核验步骤,不能绕过保护开始批量执行。') if task.status is TaskStatus.PAUSED and not stop_event.is_set(): service._store.set_task_status(task_id, TaskStatus.RUNNING, summary='automatic queue resumed after confirmation') @@ -82,115 +79,12 @@ def execute_batch( metric['completed_units'] = len(session.commands) initial_progress = progress progress = session.progress - backup_root = session.handoff.command_path.parent - backup_state_path = backup_root / _BACKUP_STATE_NAME - backup_state = _read_backup_state(backup_state_path, task_id) - backed_up_roots = { - root_key - for root_key, entry in backup_state.items() - if entry.get('status') == 'backed_up' and _reusable_backup(backup_root, root_key, entry) - } - unbacked_project_paths: list[Path] = [ - Path(str(entry['project_path'])) - for entry in backup_state.values() - if entry.get('status') == 'unbacked' and entry.get('project_path') - ] + backups = BatchBackupCoordinator(service, task_id, session, projects, + continue_after_failure=continue_after_backup_failure, + backup=_backup_project_root, write_state=_write_backup_state) last_result = None item_messages: list[str] = [] - project_root_keys = {_path_key(project.path): _path_key(project.path.resolve(strict=False).parent) - for project in projects} project_ids = {_path_key(project.path): project.project_id for project in projects} - backup_search_exhausted = False - - def backup_destination(root_key: str) -> Path: - return backup_root / _BACKUP_DIRECTORY_NAME / f'project-{_backup_key(root_key)}' - - def perform_backup(project_path: Path, destination: Path) -> None: - with measure_phase(service._logging, task_id, 'backup_project', project_path=str(project_path)) as metric: - _backup_project_root(preparer._data_root, project_path, destination) - metric['completed_units'] = 1 - - def record_backup_failure(project_path: Path, root_key: str, destination: Path, error: TaskCenterError) -> None: - backup_state[root_key] = { - 'status': 'unbacked', - 'project_path': str(project_path), - 'destination': str(destination.relative_to(backup_root)), - 'error_id': error.error_id, - 'error': error.message, - } - _write_backup_state(backup_state_path, task_id, backup_state) - if not continue_after_backup_failure: - raise error - if project_path not in unbacked_project_paths: - unbacked_project_paths.append(project_path) - service._batch_feedback = (task_id, progress, f'备份失败已按确认跳过:{project_path.name}') - append_task_event( - service._logging, - level='WARNING', - task_id=task_id, - operation='quick_run_backup_override', - message='操作员明确确认在原理图精简备份失败后继续当前队列。', - error_id=error.error_id, - details={ - 'state': 'continued_without_backup', - 'project_path': str(project_path), - 'backup_error': error.message, - 'rollback_available': False, - }, - ) - - def record_backup_success(project_path: Path, root_key: str, destination: Path) -> None: - backup_state[root_key] = { - 'status': 'backed_up', - 'project_path': str(project_path), - 'destination': str(destination.relative_to(backup_root)), - } - _write_backup_state(backup_state_path, task_id, backup_state) - backed_up_roots.add(root_key) - - def backup_project(project_path: Path) -> None: - root_key = project_root_keys[_path_key(project_path)] - if root_key in backed_up_roots: - return - previous = backup_state.get(root_key) - if previous is not None and previous.get('status') == 'unbacked': - if not continue_after_backup_failure: - raise TaskCenterError( - 'quick_run_backup', - f"工程此前备份失败,尚未建立可用回滚副本:{project_path};请排除原因后重试,或明确确认忽略备份失败。", - error_id=str(previous.get('error_id') or '') or None, - ) - if project_path not in unbacked_project_paths: - unbacked_project_paths.append(project_path) - backed_up_roots.add(root_key) - return - service._batch_feedback = (task_id, progress, f'正在备份 {project_path.name}') - destination = backup_destination(root_key) - try: - perform_backup(project_path, destination) - except TaskCenterError as error: - if error.code != 'quick_run_backup': - raise - record_backup_failure(project_path, root_key, destination, error) - else: - record_backup_success(project_path, root_key, destination) - backed_up_roots.add(root_key) - - def next_backup_candidate(start_index: int, active_root_key: str) -> tuple[Path, str] | None: - nonlocal backup_search_exhausted - if backup_search_exhausted: - return None - for command in session.commands[start_index:]: - state = session.latest.get(command[1]) - if state is not None and state[0] in TERMINAL_STATES: - continue - project_path = Path(command[2]) - root_key = project_root_keys[_path_key(project_path)] - if root_key == active_root_key or root_key in backed_up_roots or root_key in backup_state: - continue - return project_path, root_key - backup_search_exhausted = True - return None if session.progress.completed_items > initial_progress.completed_items: discovered_no_match = session.progress.completed_items - initial_progress.completed_items @@ -218,54 +112,23 @@ def execute_batch( ) else: progress = session.progress - prefetched_backup: tuple[Path, str, Path, Future[None]] | None = None - - def commit_prefetched_backup() -> None: - nonlocal prefetched_backup - if prefetched_backup is None: - return - project_path, root_key, destination, future = prefetched_backup - try: - future.result() - except TaskCenterError as error: - if error.code != 'quick_run_backup': - raise - record_backup_failure(project_path, root_key, destination, error) - else: - record_backup_success(project_path, root_key, destination) - prefetched_backup = None - - with ThreadPoolExecutor(max_workers=1, thread_name_prefix='dxpart-backup') as backup_executor: + with backups: while not progress.queue_complete: if stop_event.is_set(): - commit_prefetched_backup() + backups.commit_prefetched(progress) return BatchRunResult( - progress, True, last_result, tuple(item_messages), tuple(unbacked_project_paths) + progress, True, last_result, tuple(item_messages), tuple(backups.unbacked_project_paths) ) current = progress.next_project_path if current is None: raise TaskCenterError('quick_run_queue_progress', '队列未结束但找不到下一项,已停止。') current_key = _path_key(current) - root_key = project_root_keys[current_key] - if root_key not in backed_up_roots: - if prefetched_backup is not None and prefetched_backup[1] == root_key: - service._batch_feedback = (task_id, progress, f'正在确认预备份 {current.name}') - commit_prefetched_backup() - else: - service._batch_feedback = (task_id, progress, f'正在备份 {current.name}') - backup_project(current) - if prefetched_backup is None: - next_backup = next_backup_candidate(session.next_index + 1, root_key) - if next_backup is not None: - project_path, next_root_key = next_backup - destination = backup_destination(next_root_key) - future = backup_executor.submit(perform_backup, project_path, destination) - prefetched_backup = (project_path, next_root_key, destination, future) + backups.prepare(current, progress) service._batch_feedback = (task_id, progress, f'正在处理 {current.name}') if stop_event.is_set(): - commit_prefetched_backup() + backups.commit_prefetched(progress) return BatchRunResult( - progress, True, last_result, tuple(item_messages), tuple(unbacked_project_paths) + progress, True, last_result, tuple(item_messages), tuple(backups.unbacked_project_paths) ) expected = (str(current), progress.next_old_part_number, progress.next_new_part_number, mode) sheet = f'{progress.next_schematic_name}:{progress.next_sheet_number}' if progress.next_schematic_name else '当前图页' @@ -309,7 +172,7 @@ def execute_batch( else: updated = candidate if updated.completed_items <= progress.completed_items or updated.total_items != progress.total_items: - _write_uncertain_flag(preparer._data_root / 'quick-run/uncertain.flag', 'batch_progress_mismatch') + _write_uncertain_flag(preparer.data_root / 'quick-run/uncertain.flag', 'batch_progress_mismatch') raise TaskCenterError('quick_run_queue_progress', '执行器返回后队列进度异常,已停止,避免重复执行。') # Keep every verified step: one project can contain many sheets and rules. project_id = project_ids.get(current_key) @@ -331,11 +194,11 @@ def execute_batch( task_id, last_result.state, updated.completed_items, updated.total_items) progress = updated if last_result.state == BATCH_SAVED_UNVERIFIED_STATE: - _write_uncertain_flag(preparer._data_root / 'quick-run/uncertain.flag', + _write_uncertain_flag(preparer.data_root / 'quick-run/uncertain.flag', 'saved_readback_unverified') service._batch_feedback = (task_id, progress, '保存后回读未通过,队列已停止,请核验工程。') return BatchRunResult(progress, True, last_result, tuple(item_messages), - tuple(unbacked_project_paths)) + tuple(backups.unbacked_project_paths)) feedback = '未命中已跳过,继续下一项' if last_result.state == 'no_match' else ( '失败已记录,继续下一项' if last_result.state == BATCH_FAILED_STATE @@ -343,67 +206,10 @@ def execute_batch( ) service._batch_feedback = (task_id, progress, feedback) return BatchRunResult( - progress, False, last_result, tuple(item_messages), tuple(unbacked_project_paths) + progress, False, last_result, tuple(item_messages), tuple(backups.unbacked_project_paths) ) -def _backup_key(root_key: str) -> str: - return hashlib.sha256(root_key.encode('utf-8')).hexdigest()[:16] - - -def _read_backup_state(path: Path, task_id: str) -> dict[str, dict[str, object]]: - if not path.is_file(): - return {} - try: - payload = json.loads(path.read_text(encoding='utf-8')) - if not isinstance(payload, dict) or payload.get('format_version') != 1 or payload.get('task_id') != task_id: - raise ValueError('backup state does not belong to the current queue') - projects = payload.get('projects') - if not isinstance(projects, dict): - raise ValueError('backup state projects are invalid') - return { - str(root_key): dict(entry) - for root_key, entry in projects.items() - if isinstance(entry, dict) and entry.get('status') in {'backed_up', 'unbacked'} - } - except (OSError, UnicodeError, json.JSONDecodeError, ValueError) as error: - raise TaskCenterError('quick_run_backup', '当前队列的备份状态文件无效,已停止以避免重复或错误覆盖。') from error - - -def _write_backup_state(path: Path, task_id: str, projects: dict[str, dict[str, object]]) -> None: - path.parent.mkdir(parents=True, exist_ok=True) - temporary = path.with_name(f'.{path.name}.{uuid4().hex}.tmp') - payload = {'format_version': 1, 'task_id': task_id, 'projects': projects} - try: - with temporary.open('w', encoding='utf-8', newline='\n') as stream: - json.dump(payload, stream, ensure_ascii=False, indent=2) - stream.flush() - os.fsync(stream.fileno()) - os.replace(temporary, path) - except OSError as error: - temporary.unlink(missing_ok=True) - raise TaskCenterError('quick_run_backup', '无法保存队列备份状态,已停止以避免重复执行。') from error - - -def _reusable_backup(backup_root: Path, root_key: str, entry: dict[str, object]) -> bool: - destination = backup_root / str(entry.get('destination') or '') - manifest = destination / '.dxpartreplace-backup.json' - if not manifest.is_file() or str(entry.get('destination') or '').replace('\\', '/') != ( - f'{_BACKUP_DIRECTORY_NAME}/project-{_backup_key(root_key)}' - ): - return False - try: - payload = json.loads(manifest.read_text(encoding='utf-8')) - return ( - isinstance(payload, dict) - and payload.get('format_version') == 1 - and payload.get('scope') == 'dxdesigner_schematic_essentials' - and isinstance(payload.get('files'), list) - ) - except (OSError, UnicodeError, json.JSONDecodeError): - return False - - def _backup_project_root(data_root: Path, project_path: Path, destination: Path) -> None: last_error: OSError | None = None for attempt in range(3): diff --git a/src/dx_productivity/trial_task_center/batch_backup.py b/src/dx_productivity/trial_task_center/batch_backup.py new file mode 100644 index 0000000..31d9352 --- /dev/null +++ b/src/dx_productivity/trial_task_center/batch_backup.py @@ -0,0 +1,222 @@ +"""Durable backup coordination and one-project prefetch for serial CAD queues.""" +from concurrent.futures import ThreadPoolExecutor +import hashlib +import json +import os +from pathlib import Path +from uuid import uuid4 + +from .errors import TaskCenterError +from .execution_metrics import measure_phase +from .logging_setup import append_task_event +from .quick_run import TERMINAL_STATES, _path_key + +_BACKUP_STATE_NAME = 'batch-backups.json' +_BACKUP_DIRECTORY_NAME = 'batch-backups' + + +class BatchBackupCoordinator: + """Publish backup outcomes on the queue thread before allowing CAD work. + + Only file copying runs in the prefetch thread. Durable state, failure policy + and operator feedback remain on the serial queue thread. + """ + def __init__(self, service, task_id, session, projects, *, continue_after_failure, + backup, write_state): + self.service = service + self.task_id = task_id + self.session = session + self.data_root = service._quick_run_preparer.data_root + self.root = session.handoff.command_path.parent + self.state_path = self.root / _BACKUP_STATE_NAME + self.state = _read_backup_state(self.state_path, task_id) + self.backed_up_roots = { + key for key, entry in self.state.items() + if entry.get('status') == 'backed_up' and _reusable_backup(self.root, key, entry) + } + self.unbacked_project_paths = [Path(str(entry['project_path'])) + for entry in self.state.values() + if entry.get('status') == 'unbacked' and entry.get('project_path')] + self.project_root_keys = {_path_key(project.path): + _path_key(project.path.resolve(strict=False).parent) for project in projects} + self.continue_after_failure = continue_after_failure + self._backup = backup + self._write_state = write_state + self._search_exhausted = False + self._prefetched = None + self._executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix='dxpart-backup') + + def __enter__(self): + return self + + def __exit__(self, *exc): + # Match the queue's original executor boundary: wait for copying even + # when CAD fails, without publishing an unconsumed speculative result. + self._executor.shutdown(wait=True) + + def _destination(self, root_key): + return self.root / _BACKUP_DIRECTORY_NAME / f'project-{_backup_key(root_key)}' + + def perform_backup(self, project_path, destination): + with measure_phase(self.service._logging, self.task_id, 'backup_project', + project_path=str(project_path)) as metric: + self._backup(self.data_root, project_path, destination) + metric['completed_units'] = 1 + + def _failure(self, project_path, root_key, destination, error, progress): + self.state[root_key] = { + 'status': 'unbacked', 'project_path': str(project_path), + 'destination': str(destination.relative_to(self.root)), + 'error_id': error.error_id, 'error': error.message, + } + self._write_state(self.state_path, self.task_id, self.state) + if not self.continue_after_failure: + raise error + if project_path not in self.unbacked_project_paths: + self.unbacked_project_paths.append(project_path) + self.service._batch_feedback = (self.task_id, progress, f'备份失败已按确认跳过:{project_path.name}') + append_task_event(self.service._logging, level='WARNING', task_id=self.task_id, + operation='quick_run_backup_override', + message='操作员明确确认在原理图精简备份失败后继续当前队列。', error_id=error.error_id, + details={'state': 'continued_without_backup', 'project_path': str(project_path), + 'backup_error': error.message, 'rollback_available': False}) + + def _success(self, project_path, root_key, destination): + self.state[root_key] = { + 'status': 'backed_up', 'project_path': str(project_path), + 'destination': str(destination.relative_to(self.root)), + } + self._write_state(self.state_path, self.task_id, self.state) + self.backed_up_roots.add(root_key) + + def _backup_project(self, project_path, progress): + root_key = self.project_root_keys[_path_key(project_path)] + if root_key in self.backed_up_roots: + return + previous = self.state.get(root_key) + if previous is not None and previous.get('status') == 'unbacked': + if not self.continue_after_failure: + raise TaskCenterError('quick_run_backup', + f"工程此前备份失败,尚未建立可用回滚副本:{project_path};请排除原因后重试,或明确确认忽略备份失败。", + error_id=str(previous.get('error_id') or '') or None) + if project_path not in self.unbacked_project_paths: + self.unbacked_project_paths.append(project_path) + self.backed_up_roots.add(root_key) + return + self.service._batch_feedback = (self.task_id, progress, f'正在备份 {project_path.name}') + destination = self._destination(root_key) + try: + self.perform_backup(project_path, destination) + except TaskCenterError as error: + if error.code != 'quick_run_backup': + raise + self._failure(project_path, root_key, destination, error, progress) + else: + self._success(project_path, root_key, destination) + self.backed_up_roots.add(root_key) + + def _next_candidate(self, start_index, active_root_key): + if self._search_exhausted: + return None + for command in self.session.commands[start_index:]: + state = self.session.latest.get(command[1]) + if state is not None and state[0] in TERMINAL_STATES: + continue + project_path = Path(command[2]) + root_key = self.project_root_keys[_path_key(project_path)] + if root_key == active_root_key or root_key in self.backed_up_roots or root_key in self.state: + continue + return project_path, root_key + self._search_exhausted = True + return None + + def commit_prefetched(self, progress): + if self._prefetched is None: + return + project_path, root_key, destination, future = self._prefetched + try: + future.result() + except TaskCenterError as error: + if error.code != 'quick_run_backup': + raise + self._failure(project_path, root_key, destination, error, progress) + else: + self._success(project_path, root_key, destination) + self._prefetched = None + + def prepare(self, current, progress): + """Confirm current backup, then prefetch at most one other project root.""" + root_key = self.project_root_keys[_path_key(current)] + if root_key not in self.backed_up_roots: + if self._prefetched is not None and self._prefetched[1] == root_key: + self.service._batch_feedback = (self.task_id, progress, f'正在确认预备份 {current.name}') + self.commit_prefetched(progress) + else: + self.service._batch_feedback = (self.task_id, progress, f'正在备份 {current.name}') + self._backup_project(current, progress) + if self._prefetched is None: + candidate = self._next_candidate(self.session.next_index + 1, root_key) + if candidate is not None: + project_path, next_root_key = candidate + destination = self._destination(next_root_key) + future = self._executor.submit(self.perform_backup, project_path, destination) + self._prefetched = (project_path, next_root_key, destination, future) + + +def _backup_key(root_key: str) -> str: + return hashlib.sha256(root_key.encode('utf-8')).hexdigest()[:16] + + +def _read_backup_state(path: Path, task_id: str) -> dict[str, dict[str, object]]: + if not path.is_file(): + return {} + try: + payload = json.loads(path.read_text(encoding='utf-8')) + if not isinstance(payload, dict) or payload.get('format_version') != 1 or payload.get('task_id') != task_id: + raise ValueError('backup state does not belong to the current queue') + projects = payload.get('projects') + if not isinstance(projects, dict): + raise ValueError('backup state projects are invalid') + return { + str(root_key): dict(entry) + for root_key, entry in projects.items() + if isinstance(entry, dict) and entry.get('status') in {'backed_up', 'unbacked'} + } + except (OSError, UnicodeError, json.JSONDecodeError, ValueError) as error: + raise TaskCenterError('quick_run_backup', '当前队列的备份状态文件无效,已停止以避免重复或错误覆盖。') from error + + +def _write_backup_state(path: Path, task_id: str, projects: dict[str, dict[str, object]]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_name(f'.{path.name}.{uuid4().hex}.tmp') + payload = {'format_version': 1, 'task_id': task_id, 'projects': projects} + try: + with temporary.open('w', encoding='utf-8', newline='\n') as stream: + json.dump(payload, stream, ensure_ascii=False, indent=2) + stream.flush() + os.fsync(stream.fileno()) + os.replace(temporary, path) + except OSError as error: + temporary.unlink(missing_ok=True) + raise TaskCenterError('quick_run_backup', '无法保存队列备份状态,已停止以避免重复执行。') from error + + +def _reusable_backup(backup_root: Path, root_key: str, entry: dict[str, object]) -> bool: + destination = backup_root / str(entry.get('destination') or '') + manifest = destination / '.dxpartreplace-backup.json' + if not manifest.is_file() or str(entry.get('destination') or '').replace('\\', '/') != ( + f'{_BACKUP_DIRECTORY_NAME}/project-{_backup_key(root_key)}' + ): + return False + try: + payload = json.loads(manifest.read_text(encoding='utf-8')) + return ( + isinstance(payload, dict) + and payload.get('format_version') == 1 + and payload.get('scope') == 'dxdesigner_schematic_essentials' + and isinstance(payload.get('files'), list) + ) + except (OSError, UnicodeError, json.JSONDecodeError): + return False + + diff --git a/tests/v1_1/test_batch_backup.py b/tests/v1_1/test_batch_backup.py new file mode 100644 index 0000000..c673bde --- /dev/null +++ b/tests/v1_1/test_batch_backup.py @@ -0,0 +1,31 @@ +"""Backup coordination keeps durable state independent of CAD execution.""" +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from dx_productivity.trial_task_center.errors import TaskCenterError + + +def test_backup_failure_is_durable_before_propagating(tmp_path): + from dx_productivity.trial_task_center.batch_backup import BatchBackupCoordinator + project = tmp_path / 'board.prj' + project.write_text('project') + root = tmp_path / 'queue' + session = SimpleNamespace(handoff=SimpleNamespace(command_path=root / 'command.tsv'), + commands=(), latest={}, next_index=0) + service = SimpleNamespace(_quick_run_preparer=SimpleNamespace(data_root=tmp_path / 'data'), + _logging=None) + writes = [] + def fail(*args): + raise TaskCenterError('quick_run_backup', 'backup failed') + def write(path, task_id, state): + writes.append((path, task_id, dict(state))) + coordinator = BatchBackupCoordinator(service, 't', session, + (SimpleNamespace(path=project),), continue_after_failure=False, + backup=fail, write_state=write) + coordinator.perform_backup = lambda *args: fail() + with coordinator, pytest.raises(TaskCenterError, match='backup failed'): + coordinator.prepare(project, SimpleNamespace()) + assert writes[0][1] == 't' + assert next(iter(writes[0][2].values()))['status'] == 'unbacked'