From 7f0ec29d3177d80e0932bfc4c3e22a8b67f1baf7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=98=BF=E7=99=BD=E5=8F=94?= <11794527+absfan@user.noreply.gitee.com> Date: Thu, 15 Oct 2026 17:12:55 +0800 Subject: [PATCH] feat: report BOM validation and start new rounds from completed batches --- .../trial_task_center/bom_import_report.py | 225 ++++++++++++++ .../trial_task_center/bom_plan.py | 50 ++-- .../trial_task_center/new_round.py | 130 +++++++++ .../trial_task_center/service.py | 25 +- .../trial_task_center/store.py | 47 ++- .../trial_task_center/ui/execution_state.py | 6 +- .../trial_task_center/ui/main_window.py | 39 +++ .../trial_task_center/ui/project_plan.py | 34 ++- .../trial_task_center/ui/run_panel.py | 5 +- tests/v1_1/test_bom_import_report.py | 125 ++++++++ tests/v1_1/test_new_round.py | 275 ++++++++++++++++++ 11 files changed, 924 insertions(+), 37 deletions(-) create mode 100644 src/dx_productivity/trial_task_center/bom_import_report.py create mode 100644 src/dx_productivity/trial_task_center/new_round.py create mode 100644 tests/v1_1/test_bom_import_report.py create mode 100644 tests/v1_1/test_new_round.py diff --git a/src/dx_productivity/trial_task_center/bom_import_report.py b/src/dx_productivity/trial_task_center/bom_import_report.py new file mode 100644 index 0000000..c7ef3ec --- /dev/null +++ b/src/dx_productivity/trial_task_center/bom_import_report.py @@ -0,0 +1,225 @@ +"""Read-only, exhaustive BOM validation with an all-or-nothing preview.""" +from dataclasses import dataclass, replace +from pathlib import Path +from zipfile import BadZipFile + +from openpyxl import load_workbook + +from .bom_batch import BomBatchPreview, BomProjectPreview, _assert_editable, _identity, _scope +from .bom_plan import _normal_headers, _text, match_bom_records, parse_bom_row +from .errors import TaskCenterError +from .store_target_plan import merge_target_inventory +from .target_plan import compile_target_rules + + +@dataclass(frozen=True) +class BomRowResult: + excel_row: int + project_path: str + project_name: str + status: str # passed, failed, unchecked + reason: str = '' + + +@dataclass(frozen=True) +class BomProjectResult: + project_path: str + project_name: str + status: str + excel_rows: tuple[int, ...] + + +@dataclass(frozen=True) +class BomImportReport: + rows: tuple[BomRowResult, ...] + projects: tuple[BomProjectResult, ...] + preview: BomBatchPreview | None = None + errors: tuple[str, ...] = () + + @property + def total_rows(self): + return len(self.rows) + + @property + def passed_rows(self): + return sum(row.status == 'passed' for row in self.rows) + + @property + def failed_rows(self): + return sum(row.status == 'failed' for row in self.rows) + + @property + def unchecked_rows(self): + return sum(row.status == 'unchecked' for row in self.rows) + + @property + def total_projects(self): + return len(self.projects) + + @property + def passed_projects(self): + return sum(project.status == 'passed' for project in self.projects) + + @property + def failed_projects(self): + return sum(project.status == 'failed' for project in self.projects) + + @property + def unchecked_projects(self): + return sum(project.status == 'unchecked' for project in self.projects) + + +def _report(rows, preview=None, errors=()): + grouped = {} + for row in rows: + grouped.setdefault((row.project_path, row.project_name), []).append(row) + projects = tuple(BomProjectResult(path, name, + 'failed' if any(row.status == 'failed' for row in items) else + 'unchecked' if any(row.status == 'unchecked' for row in items) else 'passed', + tuple(row.excel_row for row in items)) for (path, name), items in grouped.items()) + return BomImportReport(tuple(rows), projects, preview, tuple(errors)) + + +def inspect_batch(service, task_id, path, *, stop_event=None, on_progress=None): + """Validate all independent rows; never persist inventory or return partial plans. + + Operational failures (including cancellation and native cleanup) propagate so + callers cannot accidentally continue opening CAD after an unsafe failure. + """ + def check_cancelled(): + if stop_event is not None and stop_event.is_set(): + raise TaskCenterError('operation_cancelled', 'BOM 导入已取消') + + check_cancelled() + scope = _scope(service._store, task_id) + owners = {str(project.path.resolve()).casefold(): (task, project) for task, project in scope} + if len(owners) != len(scope): + raise TaskCenterError('project_binding', '同批任务存在重复工程') + rows, records, grouped = [], {}, {} + workbook = None + try: + workbook = load_workbook(Path(path), read_only=True, data_only=False) + sheet = workbook.active + cells = list(sheet.iter_rows()) + header_error = '' + if len(workbook.worksheets) != 1: + header_error = 'BOM 工作簿只能包含一个工作表' + elif not cells: + header_error = 'BOM 工作表为空' + headers = _normal_headers(tuple(cell.value for cell in cells[0])) if cells else () + names = tuple(name for name in headers if name) + if not header_error and len(set(names)) != len(names): + header_error = 'BOM 列名重复' + if not header_error and not {'old_part_number', 'new_part_number', 'refdes'} <= set(headers): + header_error = 'BOM 必须包含旧料号、新料号和位号列' + if cells and any(cell.data_type == 'f' for cell in cells[0]): + header_error = 'BOM 表头不接受公式' + positions = {name: index for index, name in enumerate(headers) if name} + for number, row_cells in enumerate(cells[1:], 2): + check_cancelled() + values = tuple(cell.value for cell in row_cells) + if not any(value not in (None, '') for value in values): + continue + project_path = _text(values, positions, 'project_path') + project_name = _text(values, positions, 'project_name') + if project_path: + owner = owners.get(str(Path(project_path).resolve()).casefold()) + if owner is not None: + project_path, project_name = str(owner[1].path), owner[0].name + elif len(scope) == 1: + project_path, project_name = str(scope[0][1].path), scope[0][0].name + reason = header_error + record = None + if not reason: + try: + record = parse_bom_row(row_cells, positions) + if record is None: + continue + except (ValueError, TypeError, TaskCenterError) as error: + reason = str(error) + key = '' + if not reason: + if not record.project_path and len(scope) != 1: + reason = '多工程 BOM 必须填写工程路径列,不能按位号猜测工程' + else: + key = str(Path(record.project_path).resolve()).casefold() if record.project_path else next(iter(owners)) + if key not in owners: + reason = f'BOM 工程不属于当前批次:{record.project_path}' + else: + task, project = owners[key] + project_path, project_name = str(project.path), task.name + records[len(rows)] = record + grouped.setdefault(key, []).append(len(rows)) + rows.append(BomRowResult(number, project_path, project_name, + 'failed' if reason else 'unchecked', reason or '尚未匹配工程位号')) + if header_error: + return _report(rows, errors=(f'Excel 第 1 行:{header_error}',)) + except (OSError, ValueError, TypeError, KeyError, BadZipFile) as error: + return _report(rows, errors=(str(error),)) + finally: + if workbook is not None: + workbook.close() + if not rows: + return _report(rows, errors=('BOM 尚未填写替换行,请填写旧料号、新料号和位号',)) + # Do not start any reader until all spreadsheet/routing/editability checks pass. + for key, indices in grouped.items(): + try: + _assert_editable(service, owners[key][0].task_id) + except TaskCenterError as error: + for index in indices: + rows[index] = replace(rows[index], status='failed', reason=error.message) + if any(row.status == 'failed' for row in rows): + return _report(rows) + previews = [] + for position, (key, indices) in enumerate(grouped.items(), 1): + check_cancelled() + task, project = owners[key] + def progress(message): + if on_progress is not None: + on_progress(f'工程 {position}/{len(grouped)} · {message}') + progress(f'正在读取工程「{task.name}」({project.path})') + baseline = tuple(service._store.list_target_plan(task.task_id)) + requested = tuple(dict.fromkeys(records[index].old for index in indices)) + known = tuple(dict.fromkeys(row.target.old_part_number for row in baseline)) + if baseline and {part.casefold() for part in requested} <= {part.casefold() for part in known}: + inventory = tuple(row.target for row in baseline) + else: + controls = {} + if stop_event is not None: + controls['stop_event'] = stop_event + if on_progress is not None: + controls['on_progress'] = progress + inventory = tuple(service.for_project_task(task.task_id)._quick_run_preparer.collect_inventory( + project.path, tuple(dict.fromkeys((*known, *requested))), **controls)) + check_cancelled() + merged = merge_target_inventory(baseline, inventory) + matched_rows, touched = {}, {} + for index in indices: + try: + # A per-record match reports independent row errors without hiding later rows. + matched = match_bom_records(merged, (records[index],)) + selected = tuple(row for row in matched if row.new_part_number) + for row in selected: + touched.setdefault(row.target.key, []).append(index) + matched_rows[row.target.key] = row + rows[index] = replace(rows[index], status='passed', reason='校验通过') + except TaskCenterError as error: + rows[index] = replace(rows[index], status='failed', reason=error.message) + for target, indices_for_target in touched.items(): + if len(indices_for_target) > 1: + for index in indices_for_target: + rows[index] = replace(rows[index], status='failed', reason='位号在 BOM 中重复(Excel 行 ' + + ', '.join(str(rows[item].excel_row) for item in indices_for_target) + ')') + combined = tuple(matched_rows.get(row.target.key, row) for row in merged) + try: + compile_target_rules(combined) + except TaskCenterError as error: + for index in indices: + if rows[index].status == 'passed': + rows[index] = replace(rows[index], status='failed', reason=error.message) + previews.append(BomProjectPreview(task.task_id, project.path, baseline, inventory, combined)) + progress(f'「{task.name}」校验完成') + check_cancelled() + preview = None if any(row.status != 'passed' for row in rows) else BomBatchPreview( + task_id, _identity(scope), tuple(previews)) + return _report(rows, preview) diff --git a/src/dx_productivity/trial_task_center/bom_plan.py b/src/dx_productivity/trial_task_center/bom_plan.py index 697733d..9a9cdaa 100644 --- a/src/dx_productivity/trial_task_center/bom_plan.py +++ b/src/dx_productivity/trial_task_center/bom_plan.py @@ -111,28 +111,9 @@ def read_bom_records(path: Path) -> tuple[BomRecord, ...]: positions = {name: index for index, name in enumerate(headers) if name} result = [] for cells in records[1:]: - values = tuple(cell.value for cell in cells) - if not any(value not in (None, '') for value in values): - continue - if any(cell.data_type == 'f' for cell in cells): - raise ValueError('BOM 不接受公式,请填写实际值') - old = _text(values, positions, 'old_part_number') - new = _text(values, positions, 'new_part_number') - refs = _split_refdes(_text(values, positions, 'refdes')) - if not old and not new and not refs and not _text(values, positions, 'custom_value'): - continue # An untouched project row is a scaffold, not a rule. - if not old or not new or not refs: - raise ValueError('BOM 行的旧料号、新料号和位号不能为空') - enabled = _bool(_value(values, positions, 'enabled', True)) - sync_nc = _bool(_value(values, positions, 'sync_nc', True)) - custom = _text(values, positions, 'custom_value') - schematic = _text(values, positions, 'schematic_name') - sheet_number = _text(values, positions, 'sheet_number') - uid = _text(values, positions, 'uid') - project = _text(values, positions, 'project_path') - if project and not Path(project).is_absolute(): - raise ValueError('工程路径必须使用模板中的完整路径') - result.append(BomRecord(project, old, new, refs, schematic, sheet_number, uid, enabled, custom, sync_nc)) + record = parse_bom_row(cells, positions) + if record is not None: + result.append(record) return tuple(result) except (OSError, ValueError, TypeError, KeyError) as error: if isinstance(error, TaskCenterError): @@ -143,6 +124,31 @@ def read_bom_records(path: Path) -> tuple[BomRecord, ...]: workbook.close() +def parse_bom_row(cells, positions): + values = tuple(cell.value for cell in cells) + if not any(value not in (None, '') for value in values): + return None + if any(cell.data_type == 'f' for cell in cells): + raise ValueError('BOM 不接受公式,请填写实际值') + old = _text(values, positions, 'old_part_number') + new = _text(values, positions, 'new_part_number') + refs = _split_refdes(_text(values, positions, 'refdes')) + if not old and not new and not refs and not _text(values, positions, 'custom_value'): + return None # An untouched project row is a scaffold, not a rule. + if not old or not new or not refs: + raise ValueError('BOM 行的旧料号、新料号和位号不能为空') + enabled = _bool(_value(values, positions, 'enabled', True)) + sync_nc = _bool(_value(values, positions, 'sync_nc', True)) + custom = _text(values, positions, 'custom_value') + schematic = _text(values, positions, 'schematic_name') + sheet_number = _text(values, positions, 'sheet_number') + uid = _text(values, positions, 'uid') + project = _text(values, positions, 'project_path') + if project and not Path(project).is_absolute(): + raise ValueError('工程路径必须使用模板中的完整路径') + return BomRecord(project, old, new, refs, schematic, sheet_number, uid, enabled, custom, sync_nc) + + def match_bom_records(baseline, records) -> tuple[TargetPlanRow, ...]: if not baseline: raise TaskCenterError('target_inventory', '未采集到可匹配的工程位号') diff --git a/src/dx_productivity/trial_task_center/new_round.py b/src/dx_productivity/trial_task_center/new_round.py new file mode 100644 index 0000000..25422e2 --- /dev/null +++ b/src/dx_productivity/trial_task_center/new_round.py @@ -0,0 +1,130 @@ +"""Explicit completed-round archival; previous handoffs never become resumable.""" +from dataclasses import asdict +import json +import os +from pathlib import Path +from uuid import uuid4 + +from .errors import TaskCenterError +from .models import ProjectStatus, TaskStatus +from .target_plan import compile_target_rules + + +def _write(path, value): + temporary = path.with_name(f'.{path.name}.{uuid4().hex}.tmp') + try: + temporary.write_text(json.dumps(value, ensure_ascii=False, indent=2, default=str), encoding='utf-8') + with temporary.open('r+b') as stream: + os.fsync(stream.fileno()) + temporary.replace(path) + finally: + temporary.unlink(missing_ok=True) + + +def recover_archives(service): + """Recover a process exit between atomic directory moves and the DB commit.""" + for journal in (service._logging.root / 'round-transitions').glob('*/journal.json'): + if (journal.parent / 'committed').exists() or (journal.parent / 'rolled-back').exists(): + continue + value = json.loads(journal.read_text(encoding='utf-8')) + committed = service._store.round_committed(journal.parent.name) + if committed: + (journal.parent / 'committed').touch() + continue + # The database transaction is atomic, so an uncommitted journal restores + # the original current handoff. Never merge or overwrite newer files. + for source, destination in reversed(value['moves']): + source, destination = Path(source), Path(destination) + if destination.exists(): + if source.exists(): + raise TaskCenterError('round_recovery', '新一轮归档恢复发生目录冲突,请保留证据并检查归档日志。') + destination.rename(source) + (journal.parent / 'rolled-back').touch() + + +def start_new_round(service, task_id): + recover_archives(service) + transition = {} + try: + # Include the actual COMMIT boundary, not only the SQL/reset body. + with service._store.transaction(): + tasks, journal_root = _stage_new_round(service, task_id, transition) + except BaseException: + if transition: + _restore_moves(transition['moves']) + (transition['journal_root'] / 'rolled-back').touch() + raise + (journal_root / 'committed').touch() + return tasks + + +def _restore_moves(moves): + for source, destination in reversed(moves): + source, destination = Path(source), Path(destination) + if destination.exists(): + if source.exists(): + raise TaskCenterError('round_recovery', '归档回滚目录冲突,请保留证据并检查日志。') + destination.rename(source) + + +def _stage_new_round(service, task_id, transition): + store = service._store + with store.transaction(): + task = store.get_task(task_id) + if task.status is not TaskStatus.COMPLETED: + raise TaskCenterError('new_round_state', '只有已完成任务可以开始新一轮;当前轮次不会重复重置。') + if store.has_active_project(): + raise TaskCenterError('active_project_exists', '请先完成当前活动工程。') + members = (tuple(t for t in store.list_project_group(task.group_id) if t.status is not TaskStatus.DELETED) + if task.group_id else (task,)) + completed = tuple(t for t in members if t.status is TaskStatus.COMPLETED) + for member in members: + facade = service._project_task_service(member.task_id) + root = facade._quick_run_preparer.data_root / 'quick-run' + rules = (compile_target_rules(store.list_target_plan(member.task_id)) + if member.target_plan_mode else store.list_rules(member.task_id)) + snapshot = facade._quick_run_preparer.read_snapshot(member.task_id, + store.list_projects(member.task_id), rules, + copy_part_number_to_value=member.copy_part_number_to_value) + if snapshot.interrupted or (root / 'uncertain.flag').exists(): + raise TaskCenterError('new_round_interrupted', '同批任务有中断或不确定结果,请先核验恢复。') + if member.status is not TaskStatus.COMPLETED: + if member.status not in {TaskStatus.DRAFT, TaskStatus.READY} or snapshot.has_evidence: + raise TaskCenterError('new_round_batch_active', '同批任务仍有执行记录,请先完成或核验;未执行的草稿可以保留。') + continue + selected = tuple(p for p in store.list_projects(member.task_id) if p.selected) + if not selected or any(p.status is not ProjectStatus.COMPLETED for p in selected): + raise TaskCenterError('new_round_unverified', '工程尚未全部校验完成,不能开始新一轮。') + if snapshot.has_evidence and (not snapshot.progress.queue_complete or snapshot.progress.failed_items): + raise TaskCenterError('new_round_unverified', '替换队列尚未校验完成,不能开始新一轮。') + round_id = uuid4().hex + summary = f'new round {round_id}: collect current inventory before execution' + journal_root = service._logging.root / 'round-transitions' / round_id + journal_root.mkdir(parents=True) + moves, archives = [], [] + for member in completed: + root = service._project_task_service(member.task_id)._quick_run_preparer.data_root + archive = root / 'rounds' / round_id + archive.mkdir(parents=True) + archives.append(archive) + _write(archive / 'plan.json', dict(task=asdict(member), + projects=[asdict(p) for p in store.list_projects(member.task_id)], + rules=[asdict(r) for r in store.list_rules(member.task_id)], + targets=[asdict(r) for r in store.list_target_plan(member.task_id)])) + for name in ('quick-run', 'quick-run-history'): + if (root / name).exists(): + moves.append((str(root / name), str(archive / name))) + _write(journal_root / 'journal.json', dict(task_ids=[t.task_id for t in completed], + summary=summary, moves=moves, archives=[str(path) for path in archives])) + transition.update(moves=moves, journal_root=journal_root) + for source, destination in moves: + Path(source).rename(destination) + for member in completed: + store.reset_completed_round(member.task_id, summary) + store.record_round_commit(round_id) + return tuple(store.get_task(t.task_id) for t in completed), journal_root + + +def latest_archive(preparer): + plans = tuple((preparer.data_root / 'rounds').glob('*/plan.json')) + return max(plans, key=lambda path: path.stat().st_mtime_ns).parent if plans else None diff --git a/src/dx_productivity/trial_task_center/service.py b/src/dx_productivity/trial_task_center/service.py index 109d60f..9cd5cee 100644 --- a/src/dx_productivity/trial_task_center/service.py +++ b/src/dx_productivity/trial_task_center/service.py @@ -745,6 +745,17 @@ class TaskCenterService: with _quick_run_lease(self._logging.root): return self._operation("prepare_failed_quick_run", task_id, prepare_retry) + def start_new_round(self, task_id: str) -> tuple[TaskRecord, ...]: + """Archive and reopen completed members of the selected task's batch.""" + from .new_round import start_new_round + return self._idle_quick_run_operation('start_new_round', task_id, + lambda: start_new_round(self, task_id)) + + def inspect_bom_batch(self, task_id: str, path: Path, *, stop_event=None, on_progress=None): + 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, **control_options(stop_event, on_progress))) + def _pause_quick_run_queue(self, task_id: str, message: str) -> None: if self._store.get_task(task_id).status is TaskStatus.RUNNING: self._store.set_task_status(task_id, TaskStatus.PAUSED, summary=message) @@ -919,12 +930,24 @@ class TaskCenterService: self._store.get_task(task_id) path = self._quick_run_preparer.evidence_path(task_id) if path is None: - raise TaskCenterError("evidence_missing", "quick-run evidence is unavailable for this task") + from .new_round import latest_archive + path = latest_archive(self._quick_run_preparer) + if path is None: + raise TaskCenterError("evidence_missing", "quick-run evidence is unavailable for this task") self._path_opener(path) return path return self._operation("open_quick_run_evidence", task_id, open_path) + def open_round_history(self, task_id: str) -> Path: + """Open all retained rounds, or the current evidence before the first reset.""" + facade = self._project_task_service(task_id) + rounds = facade._quick_run_preparer.data_root / 'rounds' + if rounds.is_dir(): + return self._operation('open_round_history', task_id, + lambda: (self._path_opener(rounds), rounds)[1]) + return facade.open_quick_run_evidence(task_id) + def _operation(self, name: str, task_id: str | None, action: Callable[[], _Result]) -> _Result: timestamp = self._clock().isoformat() self._logging.logger.info("operation_start=%s task_id=%s at=%s", name, task_id or "", timestamp) diff --git a/src/dx_productivity/trial_task_center/store.py b/src/dx_productivity/trial_task_center/store.py index 00e0076..6f78ecb 100644 --- a/src/dx_productivity/trial_task_center/store.py +++ b/src/dx_productivity/trial_task_center/store.py @@ -186,6 +186,34 @@ class TaskStore: def list_target_plan(self, task_id: str) -> tuple: return self._target_plans.list_target_plan(task_id) + def reset_completed_round(self, task_id: str, summary: str) -> TaskRecord: + """Dedicated reset gate; keep binding, rules and numbered attempt history.""" + with self.transaction(): + task = self.get_task(task_id) + if task.status is not TaskStatus.COMPLETED: + raise TaskCenterError('new_round_state', 'task is not completed') + self._connection.execute('DELETE FROM target_plan WHERE task_id = ?', (task_id,)) + self._connection.execute( + """UPDATE projects SET status = ?, error_id = NULL, summary = '', + retry_count = MAX(retry_count, COALESCE((SELECT MAX(attempt_number) + FROM attempts WHERE attempts.project_id = projects.project_id), 0)) WHERE task_id = ?""", + (ProjectStatus.PENDING.value, task_id)) + self._connection.execute( + """UPDATE tasks SET status = ?, started_utc = NULL, completed_utc = NULL, + error_id = NULL, summary = ?, target_plan_mode = 1, updated_utc = ? WHERE task_id = ?""", + (TaskStatus.DRAFT.value, summary, _utc_text(self._next_timestamp(task.updated_utc)), task_id)) + return self.get_task(task_id) + + def record_round_commit(self, round_id: str) -> None: + """Immutable token committed in the same transaction as round resets.""" + self._connection.execute('INSERT INTO metadata(key, value) VALUES (?, ?)', + (f'round_committed:{round_id}', '1')) + + def round_committed(self, round_id: str) -> bool: + with self._lock: + return self._connection.execute('SELECT 1 FROM metadata WHERE key = ?', + (f'round_committed:{round_id}',)).fetchone() is not None + def _ensure_rule_columns(self) -> None: return self._schema._ensure_rule_columns() @@ -204,18 +232,21 @@ class TaskStore: self._transaction_depth += 1 try: yield - except BaseException: - if outermost: - self._connection.execute("ROLLBACK") - else: - self._connection.execute(f"ROLLBACK TO SAVEPOINT {savepoint}") - self._connection.execute(f"RELEASE SAVEPOINT {savepoint}") - raise - else: if outermost: self._connection.execute("COMMIT") else: self._connection.execute(f"RELEASE SAVEPOINT {savepoint}") + except BaseException: + try: + if outermost: + self._connection.execute("ROLLBACK") + else: + self._connection.execute(f"ROLLBACK TO SAVEPOINT {savepoint}") + self._connection.execute(f"RELEASE SAVEPOINT {savepoint}") + except BaseException: + # Preserve the original body/commit failure for diagnosis. + pass + raise finally: self._transaction_depth -= 1 diff --git a/src/dx_productivity/trial_task_center/ui/execution_state.py b/src/dx_productivity/trial_task_center/ui/execution_state.py index e6edbf6..9d91cf1 100644 --- a/src/dx_productivity/trial_task_center/ui/execution_state.py +++ b/src/dx_productivity/trial_task_center/ui/execution_state.py @@ -11,6 +11,7 @@ class ExecutionState: recover: bool = False execute_text: str = '执行当前任务' message: str = '点击新建,在弹窗中选择工程。' + new_round: bool = False def execution_state(context, *, busy=False, dirty=False): @@ -31,9 +32,10 @@ def execution_state(context, *, busy=False, dirty=False): message = ('结果待核验,请先恢复中断步骤。' if context.interrupted else '位号计划有未保存编辑,请先保存。' if dirty else '正在处理当前步骤,暂停会等待安全收尾。' if busy else - '任务已完成。' if context.progress.queue_complete and not retry else + '任务已完成。可查看原计划和日志;点击“开始新一轮”归档本批已完成任务,再采集当前料号。' if task.status is TaskStatus.COMPLETED else '有失败项,可核对原因后重试。' if retry else '工程不可用,请检查路径。' if not project.available else '先填写旧、新料号,再采集并勾选位号。' if not pending else '配置就绪,可执行当前任务或按顺序执行本批任务。') - return ExecutionState(editable, execute, retry, context.interrupted and not busy and not dirty, text, message) + return ExecutionState(editable, execute, retry, context.interrupted and not busy and not dirty, text, message, + task.status is TaskStatus.COMPLETED and not context.interrupted and not busy and not dirty) diff --git a/src/dx_productivity/trial_task_center/ui/main_window.py b/src/dx_productivity/trial_task_center/ui/main_window.py index 8125eef..ea995bc 100644 --- a/src/dx_productivity/trial_task_center/ui/main_window.py +++ b/src/dx_productivity/trial_task_center/ui/main_window.py @@ -85,6 +85,8 @@ class TrialTaskCenterWindow(QMainWindow): self.run_panel.stop_queue_button.clicked.connect(self._pause_queue) self.run_panel.retry_button.clicked.connect(self._retry_failed) self.run_panel.recover_button.clicked.connect(self._recover_quick_run) + 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) self.run_panel.reset_layout_button.clicked.connect(self._reset_layout) self.run_panel.toggle_log_button.toggled.connect(lambda on: self._refresh_live_task_log() if on else None) @@ -275,6 +277,11 @@ class TrialTaskCenterWindow(QMainWindow): self.run_panel.retry_button.setEnabled(state.retry) self.run_panel.recover_button.setVisible(bool(context and context.interrupted)) self.run_panel.recover_button.setEnabled(state.recover) + self.run_panel.new_round_button.setVisible(bool(context and context.task.status is TaskStatus.COMPLETED)) + self.run_panel.new_round_button.setEnabled(state.new_round and not self._group_has_unsaved_plans()) + self.run_panel.history_button.setVisible(bool(context and + (context.has_evidence or context.task.status is TaskStatus.COMPLETED or context.task.summary.startswith('new round ')))) + self.run_panel.history_button.setEnabled(bool(context and not busy)) self.run_panel.stop_queue_button.setVisible(self._batch_stop is not None) self.run_panel.stop_queue_button.setEnabled(bool(self._batch_stop and not self._batch_stop.is_set())) self.run_panel.copy_value_check.setEnabled(state.editable) @@ -543,6 +550,38 @@ class TrialTaskCenterWindow(QMainWindow): self._run_async(lambda: self.service.prepare_failed_quick_run(task_id), lambda _: self._load_task_data(), self.run_panel.retry_button, expected_task_id=task_id) + def _start_new_round(self): + if not self.run_panel.new_round_button.isEnabled(): + return + task_id = self._task_id + group_id = self._context.task.group_id + members = tuple(t for t in self._tasks if t.status is TaskStatus.COMPLETED + and (t.group_id == group_id if group_id else t.task_id == task_id)) + names = '\n'.join(t.name for t in members) + if QMessageBox.question(self, '开始新一轮', + f'将为以下 {len(members)} 个已完成任务开始新一轮:\n{names}\n\n' + '旧计划、命令、快照和日志会保留为轮次证据;当前位号基线将清空。' + '请按工程当前料号重新填写规则或导入 BOM,再采集位号、保存并执行。' + '本批尚未执行的草稿保留原配置。', + QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No, + QMessageBox.StandardButton.No) != QMessageBox.StandardButton.Yes: + return + def done(tasks): + self._project_queues.pop(group_id, None) + self._context_query.invalidate() + for task in tasks: + self.plan_panel.forget_task(task.task_id) + self._metadata_changed(None) + self._set_operator_message('新一轮已创建。请按当前料号导入 BOM 或修改规则,并重新采集位号;旧轮次可通过“查看轮次证据”打开。') + self._run_async(lambda: self.service.start_new_round(task_id), done, + self.run_panel.new_round_button, expected_task_id=task_id) + + def _open_round_history(self): + if self.run_panel.history_button.isEnabled() and self._task_id: + task_id = self._task_id + self._run_async(lambda: self.service.open_round_history(task_id), lambda _: None, + self.run_panel.history_button, expected_task_id=task_id) + def _recover_quick_run(self): if not self.run_panel.recover_button.isEnabled(): return diff --git a/src/dx_productivity/trial_task_center/ui/project_plan.py b/src/dx_productivity/trial_task_center/ui/project_plan.py index 9de8a7d..37dd2bb 100644 --- a/src/dx_productivity/trial_task_center/ui/project_plan.py +++ b/src/dx_productivity/trial_task_center/ui/project_plan.py @@ -8,7 +8,7 @@ from time import monotonic from PySide6.QtCore import Qt, QThreadPool, QObject, Signal, QSignalBlocker from PySide6.QtWidgets import (QDialog, QDialogButtonBox, QFileDialog, QHBoxLayout, QLabel, QLineEdit, QListWidget, QListWidgetItem, QMessageBox, QPushButton, - QVBoxLayout, QWidget) + QVBoxLayout, QWidget, QPlainTextEdit) from ..errors import TaskCenterError from .target_table import TargetTable @@ -197,6 +197,11 @@ class ProjectPlanPanel(QWidget): self.find_result = QLabel() self.summary = QLabel('先添加旧、新料号规则,再采集位号;可直接在这里编辑,也可选用 Excel。') self.summary.setWordWrap(True) + self.bom_report = QPlainTextEdit(objectName='bomImportReport') + self.bom_report.setReadOnly(True) + self.bom_report.setMaximumHeight(170) + self.bom_report.hide() + self.last_bom_report = None actions = QHBoxLayout() for button in (self.collect_button, self.save_button, self.import_button, self.export_button, self.import_bom_button, self.export_bom_button): @@ -212,6 +217,7 @@ class ProjectPlanPanel(QWidget): layout.setContentsMargins(0, 0, 0, 0) layout.addLayout(actions) layout.addWidget(self.summary) + layout.addWidget(self.bom_report) search = QHBoxLayout() for widget in (self.find_text, self.find_button, self.find_next_button, self.clear_find_button, self.find_result): @@ -442,9 +448,31 @@ class ProjectPlanPanel(QWidget): path, _ = QFileDialog.getOpenFileName(self, '导入 BOM 模板', '', 'BOM Excel (*.xlsx)') if path: task_id = self.task_id - self._dispatch_cancellable(lambda stop, progress: self.window.service.preview_bom_batch( + self._dispatch_cancellable(lambda stop, progress: self.window.service.inspect_bom_batch( task_id, Path(path), stop_event=stop, on_progress=progress), - self._preview_bom, self.import_bom_button) + self._received_bom_report, self.import_bom_button) + + def _received_bom_report(self, report): + self.last_bom_report = report + summary = (f'BOM 校验:共 {report.total_rows} 行,通过 {report.passed_rows} 行、' + f'失败 {report.failed_rows} 行、未检查 {report.unchecked_rows} 行;' + f'共 {report.total_projects} 个工程,通过 {report.passed_projects} 个、' + f'失败 {report.failed_projects} 个、未检查 {report.unchecked_projects} 个。') + details = [summary, *report.errors] + details.extend(f'Excel 第 {row.excel_row} 行 · {row.project_name or "未指定工程"} ' + f'({row.project_path or "无工程路径"})· ' + f'{ {"passed": "通过", "failed": "失败", "unchecked": "未检查"}[row.status]}:{row.reason}' + for row in report.rows) + if report.preview is None: + details.append('本次未暂存或保存任何计划;请修正后重新导入。') + else: + details.append('校验通过,已暂存预览;请确认后保存本批位号计划。') + self.bom_report.setPlainText('\n'.join(details)) + self.bom_report.show() + if report.preview is not None: + self._preview_bom(report.preview) + else: + self._summary() def _active_bom_batch(self): return next((batch for batch in (*self._bom_batches.values(), *self._orphaned_bom_batches.values()) diff --git a/src/dx_productivity/trial_task_center/ui/run_panel.py b/src/dx_productivity/trial_task_center/ui/run_panel.py index 1d28bbb..a41170d 100644 --- a/src/dx_productivity/trial_task_center/ui/run_panel.py +++ b/src/dx_productivity/trial_task_center/ui/run_panel.py @@ -20,6 +20,8 @@ class RunPanel(QWidget): self.stop_queue_button = QPushButton('完成当前项后暂停', objectName='stopQueueButton') self.retry_button = QPushButton('重试失败项', objectName='retryTaskItems') self.recover_button = QPushButton('核验并恢复', objectName='recoverQuickRunButton') + self.new_round_button = QPushButton('开始新一轮', objectName='startNewRoundButton') + self.history_button = QPushButton('查看轮次证据', objectName='roundHistoryButton') self.copy_value_check = QCheckBox('替换后将 Part Label 写入 Value', objectName='copyPartNumberToValue') self.copy_value_check.setToolTip('每行自定义 Value 优先;同步 NC 由每行开关控制。开始执行后选项冻结。') self.toggle_log_button = QToolButton(objectName='toggleLogButton') @@ -45,7 +47,8 @@ class RunPanel(QWidget): self.toggle_log_button.toggled.connect(self.log_navigation.setVisible) self.toggle_log_button.toggled.connect(lambda on: self.toggle_log_button.setText('收起日志' if on else '显示日志')) buttons = QHBoxLayout() - for button in (self.quick_run_button, self.retry_button, self.recover_button, self.stop_queue_button): + for button in (self.quick_run_button, self.retry_button, self.recover_button, + self.new_round_button, self.history_button, self.stop_queue_button): buttons.addWidget(button) buttons.addStretch() buttons.addWidget(self.toggle_log_button) diff --git a/tests/v1_1/test_bom_import_report.py b/tests/v1_1/test_bom_import_report.py new file mode 100644 index 0000000..0887042 --- /dev/null +++ b/tests/v1_1/test_bom_import_report.py @@ -0,0 +1,125 @@ +from dataclasses import replace +from threading import Event + +import pytest + +from test_bom_batch import batch, records_for +from dx_productivity.trial_task_center.bom_plan import write_bom_template +from dx_productivity.trial_task_center.bom_import_report import inspect_batch +from dx_productivity.trial_task_center.errors import TaskCenterError + + +def test_reports_independent_excel_errors_without_collecting_or_partial_preview(batch, tmp_path): + service, store, tasks, targets, calls = batch + records = list(records_for(tasks, targets)) + records.extend([dict(records[0], new_part_number='', refdes='R2'), + dict(records[1], new_part_number='=1+1')]) + report = inspect_batch(service, tasks[0].task_id, write_bom_template(tmp_path / 'bad.xlsx', records)) + assert (report.total_rows, report.passed_rows, report.failed_rows, report.unchecked_rows) == (4, 0, 2, 2) + assert [row.excel_row for row in report.rows if row.status == 'failed'] == [4, 5] + assert report.preview is None and not calls + assert all(not store.list_target_plan(task.task_id) for task in tasks) + + +def test_reports_all_matching_errors_and_success_is_read_only(batch, tmp_path): + service, store, tasks, targets, calls = batch + records = list(records_for(tasks, targets)) + records[0]['refdes'] = 'R9' + records[1]['refdes'] = 'R8' + report = inspect_batch(service, tasks[0].task_id, write_bom_template(tmp_path / 'bad.xlsx', records)) + assert report.failed_rows == 2 and report.failed_projects == 2 and report.preview is None + assert all(row.project_path and row.reason for row in report.rows) + report = inspect_batch(service, tasks[0].task_id, + write_bom_template(tmp_path / 'good.xlsx', records_for(tasks, targets))) + assert report.passed_rows == 2 and report.passed_projects == 2 and report.preview + assert all(not store.list_target_plan(task.task_id) for task in tasks) + + +def test_duplicate_marks_both_rows_and_cross_row_chain_rejected(batch, tmp_path): + service, store, tasks, targets, calls = batch + record = records_for(tasks, targets)[0] + report = inspect_batch(service, tasks[0].task_id, + write_bom_template(tmp_path / 'dup.xlsx', [record, record])) + assert report.failed_rows == 2 and report.preview is None + target = targets[tasks[0].task_id][1] + targets[tasks[0].task_id] = (targets[tasks[0].task_id][0], replace(target, old_part_number='NEW-0')) + report = inspect_batch(service, tasks[0].task_id, write_bom_template(tmp_path / 'chain.xlsx', + [record, dict(record, old_part_number='NEW-0', new_part_number='NEXT', refdes='R2')])) + assert report.failed_rows == 2 and report.preview is None + + +def test_cancel_and_native_cleanup_errors_propagate_without_next_project(batch, tmp_path): + service, store, tasks, targets, calls = batch + path = write_bom_template(tmp_path / 'bom.xlsx', records_for(tasks, targets)) + stop = Event() + stop.set() + with pytest.raises(TaskCenterError, match='取消'): + inspect_batch(service, tasks[0].task_id, path, stop_event=stop) + assert not calls + def unsafe(*args, **kwargs): + raise TaskCenterError('native_cleanup', 'cleanup failed') + service.for_project_task(tasks[0].task_id)._quick_run_preparer.collect_inventory = unsafe + with pytest.raises(TaskCenterError, match='cleanup failed'): + inspect_batch(service, tasks[0].task_id, path) + assert not calls + + + +def test_cancellation_after_reader_prevents_opening_next_project(batch, tmp_path): + service, store, tasks, targets, calls = batch + stop = Event() + path = write_bom_template(tmp_path / 'bom.xlsx', records_for(tasks, targets)) + def cancel_after_read(*args, **kwargs): + calls.append(tasks[0].task_id) + stop.set() + return targets[tasks[0].task_id] + service.for_project_task(tasks[0].task_id)._quick_run_preparer.collect_inventory = cancel_after_read + with pytest.raises(TaskCenterError, match='取消'): + inspect_batch(service, tasks[0].task_id, path, stop_event=stop) + assert calls == [tasks[0].task_id] + assert all(not store.list_target_plan(task.task_id) for task in tasks) + + +def test_scaffolds_skipped_but_header_and_bool_errors_report_excel_rows(batch, tmp_path): + from openpyxl import load_workbook + service, store, tasks, targets, calls = batch + path = service.export_bom_template(tasks[0].task_id, tmp_path / 'scaffold.xlsx') + report = inspect_batch(service, tasks[0].task_id, path) + assert report.total_rows == 0 and report.preview is None and report.errors and not calls + path = write_bom_template(tmp_path / 'bool.xlsx', [dict(records_for(tasks, targets)[0], enabled='maybe')]) + report = inspect_batch(service, tasks[0].task_id, path) + assert report.rows[0].excel_row == 2 and report.failed_rows == 1 and 'TRUE/FALSE' in report.rows[0].reason + workbook = load_workbook(path) + workbook.active['C1'] = 'wrong header' + workbook.save(path) + workbook.close() + report = inspect_batch(service, tasks[0].task_id, path) + assert report.failed_rows == 1 and '第 1 行' in report.errors[0] and not calls + + +def test_ui_report_is_persistent_and_failure_does_not_stage(batch, tmp_path, qtbot, monkeypatch): + from PySide6.QtWidgets import QFileDialog + from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow + service, store, tasks, targets, calls = batch + # Exercise the real async import callback without any blocking message box. + monkeypatch.setattr(service, 'inspect_bom_batch', lambda *args, **kwargs: inspect_batch( + service, *args, **kwargs), raising=False) + records = list(records_for(tasks, targets)) + records[1]['new_part_number'] = '' + path = write_bom_template(tmp_path / 'bad-ui.xlsx', records) + window = TrialTaskCenterWindow(service) + qtbot.addWidget(window) + window.open_task(tasks[0].task_id) + qtbot.waitUntil(lambda: not window._loading and not window._context_query.busy) + monkeypatch.setattr(QFileDialog, 'getOpenFileName', lambda *args: (str(path), 'Excel (*.xlsx)')) + window.plan_panel.import_bom_button.click() + qtbot.waitUntil(lambda: not window._workers) + panel = window.plan_panel + assert panel.last_bom_report.failed_rows == 1 + assert 'Excel 第 3 行' in panel.bom_report.toPlainText() + assert '未检查 1 行' in panel.bom_report.toPlainText() + assert not panel._bom_batches and not panel._drafts and not calls + panel._summary() + assert '失败 1 行' in panel.bom_report.toPlainText() + assert all(not store.list_target_plan(task.task_id) for task in tasks) + window.close() diff --git a/tests/v1_1/test_new_round.py b/tests/v1_1/test_new_round.py new file mode 100644 index 0000000..6803c7f --- /dev/null +++ b/tests/v1_1/test_new_round.py @@ -0,0 +1,275 @@ +from dataclasses import replace +import json + +import pytest + +from dx_productivity.trial_task_center.errors import TaskCenterError +from dx_productivity.trial_task_center.logging_setup import configure_logging +from dx_productivity.trial_task_center.models import TaskStatus, ProjectStatus +from dx_productivity.trial_task_center.service import TaskCenterService +from dx_productivity.trial_task_center.store import TaskStore +from dx_productivity.trial_task_center.target_plan import ComponentTarget, TargetPlanRow + + +@pytest.fixture +def completed(tmp_path): + store = TaskStore(tmp_path / 'tasks.db') + service = TaskCenterService(store, configure_logging(tmp_path / 'data')) + path = tmp_path / 'board.prj' + path.touch() + task = store.create_task('board') + project = store.sync_projects(task.task_id, tmp_path, (path,))[0] + store.set_project_selected(project.project_id, True) + store.bind_project_task(task.task_id, project.project_id, 'batch', 0) + service.add_rule(task.task_id, 'OLD', 'NEW') + target = ComponentTarget(path, 'MAIN', '1', 'u1', 'R1', 'OLD', 'before') + store.record_target_inventory(task.task_id, (target,)) + store.replace_target_plan(task.task_id, (TargetPlanRow(target, True, 'NEW'),)) + store.record_quick_run_progress(task.task_id, (project.project_id,), queue_complete=True, has_progress=True) + yield service, store, task.task_id, project.project_id, target + store.close() + + +def test_restart_preserves_plan_and_evidence_but_requires_new_baseline(completed): + service, store, task_id, project_id, target = completed + root = service.for_project_task(task_id)._quick_run_preparer.data_root + history = root / 'quick-run-history' / 'obsolete-test' + history.mkdir(parents=True) + (history / 'native.log').write_text('original evidence') + old_task = store.get_task(task_id) + restarted = service.start_new_round(task_id) + assert [t.task_id for t in restarted] == [task_id] + task = store.get_task(task_id) + assert task.status is TaskStatus.DRAFT and task.target_plan_mode + assert task.group_id == old_task.group_id and task.primary_project_id == project_id + assert task.completed_utc is None and task.started_utc is None + assert store.get_project(project_id).status is ProjectStatus.PENDING + assert not store.list_target_plan(task_id) + archives = list((root / 'rounds').glob('*/plan.json')) + assert len(archives) == 1 + snapshot = json.loads(archives[0].read_text(encoding='utf-8')) + assert snapshot['targets'][0]['target']['old_part_number'] == 'OLD' + assert (archives[0].parent / 'quick-run-history' / 'obsolete-test' / 'native.log').read_text() == 'original evidence' + assert not service.task_context(task_id).has_evidence + assert not service.task_context(task_id).progress.next_project_path + # Previous UID with current PN/value becomes a new baseline only after collection. + current = replace(target, old_part_number='NEW', old_value='after') + store.record_target_inventory(task_id, (current,)) + store.replace_target_plan(task_id, (TargetPlanRow(current, True, 'NEXT'),)) + assert service.task_context(task_id).progress.next_old_part_number == 'NEW' + with pytest.raises(TaskCenterError): + service.start_new_round(task_id) + assert len(list((root / 'rounds').glob('*/plan.json'))) == 1 + + +def test_restart_rejects_interrupted_and_noncompleted_without_changing_plan(completed): + service, store, task_id, _, _ = completed + root = service.for_project_task(task_id)._quick_run_preparer.data_root / 'quick-run' + root.mkdir(parents=True) + (root / 'uncertain.flag').write_text('uncertain') + before = store.list_target_plan(task_id) + with pytest.raises(TaskCenterError): + service.start_new_round(task_id) + assert store.get_task(task_id).status is TaskStatus.COMPLETED + assert store.list_target_plan(task_id) == before + assert (root / 'uncertain.flag').exists() + + +def test_restart_rolls_back_files_when_database_reset_fails(completed, monkeypatch): + service, store, task_id, _, _ = completed + root = service.for_project_task(task_id)._quick_run_preparer.data_root + history = root / 'quick-run-history' + history.mkdir(parents=True) + (history / 'proof.txt').write_text('retain') + def fail(*args): + raise RuntimeError('database failure') + monkeypatch.setattr(store, 'reset_completed_round', fail) + with pytest.raises(TaskCenterError): + service.start_new_round(task_id) + assert (history / 'proof.txt').read_text() == 'retain' + assert store.get_task(task_id).status is TaskStatus.COMPLETED + assert store.list_target_plan(task_id) + + +def test_completed_group_restarts_together_and_rules_are_editable(completed, tmp_path): + service, store, task_id, _, _ = completed + other = store.create_task('second') + path = tmp_path / 'second.prj' + path.touch() + project = store.sync_projects(other.task_id, tmp_path, (path,))[0] + store.set_project_selected(project.project_id, True) + store.bind_project_task(other.task_id, project.project_id, 'batch', 1) + store.record_quick_run_progress(other.task_id, (project.project_id,), queue_complete=True, has_progress=True) + assert len(service.start_new_round(task_id)) == 2 + service.update_rule(store.list_rules(task_id)[0].rule_id, old_part_number='NEW', new_part_number='NEXT', enabled=True) + assert store.list_rules(other.task_id)[-1].old_part_number == 'NEW' + assert all(t.status is TaskStatus.DRAFT for t in store.list_project_group('batch')) + + +def test_pristine_group_sibling_is_preserved_and_does_not_lock_rules(completed, tmp_path): + service, store, task_id, _, _ = completed + other = store.create_task('untouched') + path = tmp_path / 'untouched.prj' + path.touch() + project = store.sync_projects(other.task_id, tmp_path, (path,))[0] + store.bind_project_task(other.task_id, project.project_id, 'batch', 1) + before = store.get_task(other.task_id) + service.start_new_round(task_id) + assert store.get_task(other.task_id) == before + service.update_rule(store.list_rules(task_id)[0].rule_id, old_part_number='NEW', new_part_number='NEXT', enabled=True) + assert store.list_rules(other.task_id)[-1].new_part_number == 'NEXT' + + +def test_archived_handoff_cannot_supply_next_round_old_values(completed): + service, store, task_id, project_id, _ = completed + from dx_productivity.trial_task_center.target_plan import compile_target_rules + facade = service.for_project_task(task_id) + root = facade._quick_run_preparer.data_root + handoff = facade._quick_run_preparer.prepare(task_id, + (replace(store.get_project(project_id), status=ProjectStatus.PENDING),), + compile_target_rules(store.list_target_plan(task_id)), + sheet_targets={str(store.get_project(project_id).path).casefold(): (('MAIN', '1'),)}) + command = handoff.command_path.read_text(encoding='utf-8').splitlines()[1].split('\t') + header = handoff.command_path.read_text(encoding='utf-8').splitlines()[0].split('\t') + job = dict(zip(header, command))['job_id'] + handoff.status_path.write_text(f'job_id\tstate\tcode\tmessage\n{job}\tsaved_ok\t\tverified\n', encoding='utf-8') + old_bytes = handoff.command_path.read_bytes() + service.start_new_round(task_id) + assert not service.task_context(task_id).has_evidence + assert not service.task_context(task_id).progress.next_project_path + archives = list((root / 'rounds').glob('*/quick-run/command.tsv')) + assert len(archives) == 1 and archives[0].read_bytes() == old_bytes + assert not handoff.command_path.exists() + + +def test_pending_journal_recovers_interrupted_archival_before_retry(completed): + service, store, task_id, _, _ = completed + root = service.for_project_task(task_id)._quick_run_preparer.data_root + archive = root / 'rounds' / 'crashed' / 'quick-run-history' + archive.mkdir(parents=True) + (archive / 'evidence').write_text('unchanged') + journal = service._logging.root / 'round-transitions' / 'crashed' + journal.mkdir(parents=True) + source = root / 'quick-run-history' + (journal / 'journal.json').write_text(json.dumps(dict(task_ids=[task_id], summary='uncommitted round', + moves=[(str(source), str(archive))])), encoding='utf-8') + service.start_new_round(task_id) + assert (journal / 'rolled-back').exists() + assert any(path.read_text() == 'unchanged' for path in (root / 'rounds').glob('*/quick-run-history/evidence')) + + +def test_restart_is_rejected_while_execution_lease_is_held(completed): + service, store, task_id, _, _ = completed + from dx_productivity.trial_task_center.service import _quick_run_lease + with _quick_run_lease(service._logging.root): + with pytest.raises(TaskCenterError) as error: + service.start_new_round(task_id) + assert error.value.code == 'quick_run_busy' + assert store.get_task(task_id).status is TaskStatus.COMPLETED + + +def test_new_round_ui_confirms_scope_and_invalidates_paused_queue_token(completed, qtbot, monkeypatch): + from PySide6.QtWidgets import QMessageBox + from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow + service, store, task_id, _, _ = completed + window = TrialTaskCenterWindow(service) + qtbot.addWidget(window) + window.open_task(task_id) + qtbot.waitUntil(lambda: not window._loading and not window._context_query.busy) + assert window.run_panel.new_round_button.isEnabled() + assert not window.run_panel.quick_run_button.isEnabled() + assert window.plan_panel.table.rowCount() == 1 + window._project_queues['batch'] = ('old-queue-token', (task_id,)) + monkeypatch.setattr(QMessageBox, 'question', lambda *args: QMessageBox.StandardButton.Yes) + window.run_panel.new_round_button.click() + qtbot.waitUntil(lambda: not window._workers and not window._loading and not window._context_query.busy) + assert 'batch' not in window._project_queues + assert window.plan_panel.table.rowCount() == 0 + assert not window.run_panel.quick_run_button.isEnabled() + assert window.add_mapping_button.isEnabled() + assert store.get_task(task_id).status is TaskStatus.DRAFT + window.close() + + +def test_commit_failure_rolls_back_database_and_restores_handoff(completed): + service, store, task_id, _, _ = completed + root = service.for_project_task(task_id)._quick_run_preparer.data_root + history = root / 'quick-run-history' + history.mkdir(parents=True) + (history / 'proof').write_text('original') + original = store._connection + class FailCommit: + def execute(self, sql, *args): + if sql == 'COMMIT': + raise RuntimeError('injected commit failure') + return original.execute(sql, *args) + def __getattr__(self, name): + return getattr(original, name) + store._connection = FailCommit() + try: + with pytest.raises(TaskCenterError): + service.start_new_round(task_id) + assert not original.in_transaction + assert store._transaction_depth == 0 + assert store.get_task(task_id).status is TaskStatus.COMPLETED + assert store.list_target_plan(task_id) + assert (history / 'proof').read_text() == 'original' + finally: + store._connection = original + + +def test_committed_journal_uses_immutable_token_after_task_summary_changes(completed): + from dx_productivity.trial_task_center.new_round import recover_archives + service, store, task_id, _, _ = completed + root = service.for_project_task(task_id)._quick_run_preparer.data_root + history = root / 'quick-run-history' + history.mkdir(parents=True) + (history / 'proof').write_text('original') + service.start_new_round(task_id) + journal = next((service._logging.root / 'round-transitions').glob('*/journal.json')) + (journal.parent / 'committed').unlink() + store._connection.execute("UPDATE tasks SET summary = 'later edit' WHERE task_id = ?", (task_id,)) + recover_archives(service) + assert (journal.parent / 'committed').exists() + assert not history.exists() + assert next((root / 'rounds').glob('*/quick-run-history/proof')).read_text() == 'original' + + +def test_pristine_target_mode_sibling_with_no_enabled_rows_is_not_execution_validated(completed, tmp_path): + service, store, task_id, _, target = completed + other = store.create_task('draft-empty-plan') + path = tmp_path / 'draft.prj' + path.touch() + project = store.sync_projects(other.task_id, tmp_path, (path,))[0] + store.bind_project_task(other.task_id, project.project_id, 'batch', 1) + store.record_target_inventory(other.task_id, (replace(target, project_path=path),)) + before = store.list_target_plan(other.task_id) + service.start_new_round(task_id) + assert store.list_target_plan(other.task_id) == before + assert store.get_task(other.task_id).status is TaskStatus.DRAFT + + +@pytest.mark.parametrize('marker', ['committed', 'rolled-back']) +def test_terminal_corrupted_journal_does_not_block_round_recovery(completed, marker): + from dx_productivity.trial_task_center.new_round import recover_archives + service, _, _, _, _ = completed + folder = service._logging.root / 'round-transitions' / 'terminal' + folder.mkdir(parents=True) + (folder / 'journal.json').write_text('{truncated') + (folder / marker).touch() + recover_archives(service) + + +def test_failed_atomic_journal_write_does_not_publish_truncated_json(tmp_path, monkeypatch): + from pathlib import Path + from dx_productivity.trial_task_center.new_round import _write + destination = tmp_path / 'journal.json' + original = Path.write_text + def fail_partial(path, text, **options): + original(path, text[:4], **options) + raise OSError('injected partial write') + monkeypatch.setattr(Path, 'write_text', fail_partial) + with pytest.raises(OSError, match='partial write'): + _write(destination, {'moves': ['complete']}) + assert not destination.exists() + assert not tuple(tmp_path.iterdir())