args = (WindowsPath('F:/DxAcceptanceTmp-20261111/pytest-pr27-97f1ca0caa/test_bom_cli_inspection_does_n1/projects/a/same.prj'), ('OLD', 'NEW-0')) kwargs = {'runtime': None} def fail(*args, **kwargs): > raise TaskCenterError('inventory_cleanup', 'reader did not close') E dx_productivity.trial_task_center.errors.TaskCenterError: DXT-20261113-033A3515 inventory_cleanup: reader did not close tests\v1_1\test_batch_runtime_integration.py:106: TaskCenterError The above exception was the direct cause of the following exception: batch = (<dx_productivity.trial_task_center.service.TaskCenterService object at 0x000001C23AE2F260>, <dx_productivity.trial_ta...er='1', uid='u2', refdes='R2', old_part_number='OLD', old_value='33R', actual_part_label=None, actual_cell=None))}, []) tmp_path = WindowsPath('F:/DxAcceptanceTmp-20261111/pytest-pr27-97f1ca0caa/test_bom_cli_inspection_does_n1') runtime_module = (<class 'test_batch_runtime_integration.runtime_module.<locals>.Runtime'>, []) read_error = True @pytest.mark.parametrize('read_error', [False, True]) def test_bom_cli_inspection_does_not_create_cad_runtime(batch, tmp_path, runtime_module, read_error): from dx_productivity.trial_task_center.bom_import_report import inspect_batch from dx_productivity.trial_task_center.bom_plan import write_bom_template Runtime, scopes = runtime_module Runtime.fail_cleanup = True service, store, tasks, targets, calls = batch if read_error: def fail(*args, **kwargs): raise TaskCenterError('inventory_cleanup', 'reader did not close') service.for_project_task(tasks[0].task_id)._quick_run_preparer.collect_inventory = fail > report = inspect_batch(service, tasks[0].task_id, write_bom_template(tmp_path / 'cleanup.xlsx', records_for(tasks, targets))) tests\v1_1\test_batch_runtime_integration.py:108: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ service = <dx_productivity.trial_task_center.service.TaskCenterService object at 0x000001C23AE2F260> task_id = 'ba6a29c0-7fdf-4880-9c3f-1f92d2816446' path = WindowsPath('F:/DxAcceptanceTmp-20261111/pytest-pr27-97f1ca0caa/test_bom_cli_inspection_does_n1/cleanup.xlsx') def inspect_batch(service, task_id, path, *, stop_event=None, on_progress=None, on_phase=None, runtime=None, allow_partial=False, spreadsheet_only=False, task_scope=False, force_inventory=False): """Validate all independent rows; never persist inventory or return partial plans. Native read failures are reported per project. Explicit CAD runtimes retain their session cleanup gate; cancellation always propagates. """ def check_cancelled(): if stop_event is not None and stop_event.is_set(): raise TaskCenterError('operation_cancelled', 'BOM 导入已取消') def notify(message, phase=None): if phase is not None and on_phase is not None: on_phase(phase, message) if on_progress is not None: on_progress(message) check_cancelled() notify('正在读取并校验 BOM Excel 表格…', BomImportPhase.READING) if task_scope: task = service._store.get_task(task_id) projects = service._store.list_projects(task_id) if len(projects) != 1: raise TaskCenterError('project_binding', 'BOM 核验需要当前任务绑定一个工程') scope = ((task, projects[0]),) else: scope = _scope(service._store, task_id) if runtime is not None: runtime.bind_logs(service._logging, tuple(task.task_id for task, _ in scope)) routing = ProjectIdentityResolver() owners = {routing.project(project.path): (task, project) for task, project in scope} if len(owners) != len(scope): raise TaskCenterError('project_binding', '同批任务存在重复工程') rows, records, grouped = [], {}, {} source_hash = hashlib.sha256(Path(path).read_bytes()).hexdigest() if Path(path).is_file() else '' workbook = None workbook_stream = None try: workbook_stream = Path(path).open('rb') workbook = load_workbook(workbook_stream, read_only=True, data_only=False) sheet = workbook.active cells = iter(sheet.iter_rows()) header = next(cells, ()) notify('正在校验 BOM Excel 格式与工程归属…', BomImportPhase.VALIDATING) header_error = '' if len(workbook.worksheets) != 1: header_error = 'BOM 工作簿只能包含一个工作表' elif not header: header_error = 'BOM 工作表为空' headers = _normal_headers(tuple(cell.value for cell in header)) 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 any(cell.data_type == 'f' for cell in header): header_error = 'BOM 表头不接受公式' positions = {name: index for index, name in enumerate(headers) if name} for number, row_cells in enumerate(cells, 2): check_cancelled() if number % 250 == 0: notify(f'正在校验 BOM Excel 第 {number} 行…') 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(routing.project(project_path)) 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 = routing.project(record.project_path) 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 TaskCenterError: raise except (OSError, ValueError, TypeError, KeyError, BadZipFile) as error: return _report(rows, errors=(str(error),)) finally: if workbook is not None: workbook.close() if workbook_stream is not None: workbook_stream.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(): check_cancelled() _check_record_conflicts(rows, records, indices) 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) and not allow_partial: return _report(rows) if spreadsheet_only: failed_paths = {row.project_path for row in rows if row.status == 'failed'} eligible = any(row.project_path not in failed_paths for row in rows) return replace(_report(rows), deferred=eligible) notify(f'BOM 表格校验通过,共 {len(rows)} 行、涉及 {len(grouped)} 个工程;开始核验工程位号。') previews = [] for position, (key, indices) in enumerate(grouped.items(), 1): check_cancelled() task, project = owners[key] # One invalid row rejects its whole project, including parsed rows which # were excluded from grouped because they failed Excel validation. if any(row.status == 'failed' and row.project_path == str(project.path) for row in rows): continue task_default_value_mode = 'part_label' if task.copy_part_number_to_value else 'preserve' def progress(message, phase=None): notify(f'工程 {position}/{len(grouped)} · {message}', phase) progress(f'正在核验「{task.name}」的位号库存…', BomImportPhase.INVENTORY) baseline = tuple(service._store.list_target_plan(task.task_id)) requested = tuple(dict.fromkeys(part for index in indices for part in (records[index].old, records[index].new))) known = tuple(dict.fromkeys(row.target.old_part_number for row in baseline)) known_parts = {part.casefold() for part in known} project_rules = service.rules(task.task_id) defaults = {(rule.old_part_number.casefold(), rule.new_part_number): rule.target_cell for rule in project_rules if rule.enabled} missing_metadata = False already_target_inventory = False for index in indices: record = records[index] mode = task_default_value_mode if record.value_mode == 'inherit' else record.value_mode for row in baseline: if (record.enabled and row.target.old_part_number.casefold() == record.new.casefold() and row.target.refdes.casefold() in {ref.casefold() for ref in record.refs}): already_target_inventory = True cell = (row.target_cell if row.new_part_number == record.new else '') or defaults.get( (record.old.casefold(), record.new), '') missing_metadata |= ((mode == 'part_label' and row.target.actual_part_label is None) or (bool(cell) and row.target.actual_cell is None)) if not force_inventory and baseline and all(records[index].old.casefold() in known_parts or records[index].new.casefold() in known_parts for index in indices) and not already_target_inventory: progress(f'「{task.name}」复用已有位号库存,无需启动 CAD') inventory = tuple(row.target for row in baseline) else: progress(f'「{task.name}」正在获取位号库存,仅采集本表涉及的旧料号及已有计划料号') preparer = service.for_project_task(task.task_id)._quick_run_preparer if missing_metadata: preparer.invalidate_discovery(project.path) collector = preparer.collect_inventory controls = ({'runtime': runtime} if any( parameter.name == 'runtime' or parameter.kind is inspect.Parameter.VAR_KEYWORD for parameter in inspect.signature(collector).parameters.values()) else {}) if stop_event is not None: controls['stop_event'] = stop_event if on_progress is not None: controls['on_progress'] = progress try: inventory = tuple(collector( project.path, tuple(dict.fromkeys((*known, *requested))), **controls)) except TaskCenterError as error: if error.code == 'operation_cancelled': raise reason = f'工程采集失败:{error.message}(错误编号:{error.error_id})' for index in indices: rows[index] = replace(rows[index], status='failed', reason=reason, origin_code=error.code, error_id=error.error_id) from .execution_problems import classify_execution_failure safe_read = classify_execution_failure(error.code, 'failed', phase='read')['continue_allowed'] if safe_read and (task_scope or isinstance(error, ReleasedProjectReadError)): progress(f'「{task.name}」采集失败,已记录;继续核验其他工程') continue for index, row in enumerate(rows): if row.status == 'unchecked': rows[index] = replace(row, reason='前序工程采集异常,已停止后续核验') report = _report(rows, errors=( f'已停止批量采集:{task.name};{error.message}(错误编号:{error.error_id})',)) > raise BomInspectionError(error, report) from error E dx_productivity.trial_task_center.bom_import_report.BomInspectionError: DXT-20261113-033A3515 inventory_cleanup: reader did not close src\dx_productivity\trial_task_center\bom_import_report.py:353: BomInspectionErrortmp_path = WindowsPath('F:/DxAcceptanceTmp-20261111/pytest-pr27-97f1ca0caa/test_dialog_is_serviced_while_0') @pytest.mark.skipif(os.name != 'nt', reason='Native modal dialog while the business thread waits') def test_dialog_is_serviced_while_business_thread_is_blocked(tmp_path): import sys from dx_productivity.trial_task_center import isolated_cad as runtime from dx_productivity.trial_task_center.cad_dialogs import CadDialogGuard from dx_productivity.trial_task_center.batch_runtime import BatchCadRuntime, _DesktopLease code = "import ctypes; ctypes.windll.user32.MessageBoxW(None, 'Microsoft VBScript compilation error', 'Script Error', 0)" with BatchCadRuntime(tmp_path / 'runtime', 'dialog-sample') as batch: lease = _DesktopLease(batch, tmp_path) lease.__enter__() process = lease.start_process((sys.executable, '-c', code)) session = runtime.IsolatedCadSession(tmp_path, desktop=lease) session.cad = process session._dialogs = CadDialogGuard(lease, process, tmp_path / 'cad-dialogs.json', session.token) session._start_dialog_monitor() try: > assert process.wait(timeout=5) == 0 # No polling from this blocked thread. ^^^^^^^^^^^^^^^^^^^^^^^ tests\v1_1\test_cad_dialogs.py:307: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <dx_productivity.trial_task_center.isolated_desktop._Win32Process object at 0x000001C23D734530> timeout = 5 def wait(self, timeout=None): if self.returncode is not None: return self.returncode if self.handle is None: raise OSError('owned process handle is closed before exit was confirmed') milliseconds = 0xFFFFFFFF if timeout is None else min(max(math.ceil(timeout * 1000), 0), 0xFFFFFFFE) status = self._event_api.WaitForSingleObject(self.handle, milliseconds) if status == 258: > raise subprocess.TimeoutExpired(self.args, timeout) E subprocess.TimeoutExpired: Command '('C:\\Users\\ABS_Windows\\AppData\\Local\\Programs\\Python\\Python312\\python.exe', '-c', "import ctypes; ctypes.windll.user32.MessageBoxW(None, 'Microsoft VBScript compilation error', 'Script Error', 0)")' timed out after 5 seconds src\dx_productivity\trial_task_center\isolated_desktop.py:411: TimeoutExpiredself = <dx_productivity.dsh.run_journal.RunJournal object at 0x000001C24A89EBD0> run_id = 'ffffffffffffffffffffffffffffffff' receipt = {'acceptance': {'status': 'not_required', 'tasks': {}, 'verified': False}, 'awaiting_user_resume': False, 'cad_verific...ffffffffffffffffff\\verification.json', 'state': 'completed', 'task_id': '740bcf1a-f3b9-4d4e-af66-999f43d978c2'}], ...} def fail_enrichment(self, run_id, receipt): calls.append(run_id) if len(calls) > 1: > raise OSError('controlled enrichment persistence failure') E OSError: controlled enrichment persistence failure tests\ui\test_dsh_operations.py:125: OSError During handling of the above exception, another exception occurred: ui = namespace(window=<dx_productivity.trial_task_center.ui.main_window.TrialTaskCenterWindow(0x1c252f0c410) at 0x000001C24...46277A60>, data=WindowsPath('F:/DxAcceptanceTmp-20261111/pytest-pr27-97f1ca0caa/test_receipt_enrichment_failur0/data')) monkeypatch = <_pytest.monkeypatch.MonkeyPatch object at 0x000001C24A90E6C0> def test_receipt_enrichment_failure_does_not_erase_executor_result(ui, monkeypatch): from threading import Event from dx_productivity.dsh import task_lifecycle as api from dx_productivity.dsh.execution_runs import execute_confirmed_run from dx_productivity.dsh.run_journal import RunJournal original = RunJournal.finish calls = [] def fail_enrichment(self, run_id, receipt): calls.append(run_id) if len(calls) > 1: raise OSError('controlled enrichment persistence failure') return original(self, run_id, receipt) monkeypatch.setattr(RunJournal, 'finish', fail_enrichment) ids = [ui.tasks[0].task_id] > receipt = execute_confirmed_run(ui.service, ui.data, ids, api.preflight(ui.service, ids), Event(), 'f' * 32) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ tests\ui\test_dsh_operations.py:129: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ src\dx_productivity\dsh\execution_runs.py:62: in execute_confirmed_run return _execute_confirmed_run(service, root, task_ids, report, stop, run_id, resume=resume) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ src\dx_productivity\dsh\execution_runs.py:103: in _execute_confirmed_run return _finish_execution_run(service, root, task_ids, stop, run_id, result, src\dx_productivity\dsh\execution_runs.py:146: in _finish_execution_run _persist_execution_receipt(service, journal, run_id, receipt, baseline) src\dx_productivity\dsh\execution_runs.py:168: in _persist_execution_receipt journal.finish(run_id, failure) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <dx_productivity.dsh.run_journal.RunJournal object at 0x000001C24A89EBD0> run_id = 'ffffffffffffffffffffffffffffffff' receipt = {'acceptance': {'status': 'not_required', 'tasks': {}, 'verified': False}, 'awaiting_user_resume': False, 'cad_verific...upted': False, 'netlist_status': 'not_required', 'netlist_verified': False, ...}]}, 'code': 'receipt_write_error', ...} def fail_enrichment(self, run_id, receipt): calls.append(run_id) if len(calls) > 1: > raise OSError('controlled enrichment persistence failure') E OSError: controlled enrichment persistence failure tests\ui\test_dsh_operations.py:125: OSError