From 0225787084c3a928ff1c8fbdad48825f4eb0b91d 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 09:10:26 +0800 Subject: [PATCH] feat: record execution timings and speed up batch queues --- .../dxdesigner795/QuickPartReplace.vbs | 4 + .../trial_task_center/batch.py | 80 +++++--- .../trial_task_center/execution_metrics.py | 24 +++ .../trial_task_center/quick_run.py | 77 ++++++-- .../trial_task_center/recovery.py | 4 +- .../trial_task_center/service.py | 32 +-- .../trial_task_center/ui/messages.py | 22 +++ .../trial_task_center/worker_monitor.py | 14 +- tests/trial_task_center/test_batch.py | 6 + tests/v1_1/test_execution_metrics.py | 102 ++++++++++ tests/v1_1/test_multi_project_regression.py | 17 ++ tools/measure_task_queue.py | 183 ++++++++++++++++++ 12 files changed, 509 insertions(+), 56 deletions(-) create mode 100644 src/dx_productivity/trial_task_center/execution_metrics.py create mode 100644 tests/v1_1/test_execution_metrics.py create mode 100644 tests/v1_1/test_multi_project_regression.py create mode 100644 tools/measure_task_queue.py diff --git a/integration/dxdesigner795/QuickPartReplace.vbs b/integration/dxdesigner795/QuickPartReplace.vbs index bd1a28f..6366cb8 100644 --- a/integration/dxdesigner795/QuickPartReplace.vbs +++ b/integration/dxdesigner795/QuickPartReplace.vbs @@ -413,6 +413,7 @@ Function QPAttachOrStart(ByVal ProcessCount) If ProcessCount = 0 Then QP_Stage = "launch_designer" QPLog QP_Root, "INFO", "stage=launch_designer method=COM" + QPProgress "launch_designer", 0, 1 Set App = CreateObject("Viewdraw.Application") App.Visible = True Else @@ -437,6 +438,7 @@ Sub QPEnsureProject(ByRef App, ByVal TargetPath) Err.Raise vbObjectError + 850, "QuickPartReplace.Session", "confirmed project file does not exist: " & TargetPath QP_Stage = "check_project" QPLog QP_Root, "INFO", "stage=check_project target=" & QPLogField(TargetPath) + QPProgress "check_project", 0, 1 Set ProjectData = App.GetProjectData() CurrentPath = "" If Not ProjectData Is Nothing Then CurrentPath = CStr(ProjectData.GetProjectFilePath()) @@ -449,6 +451,7 @@ Sub QPEnsureProject(ByRef App, ByVal TargetPath) Else QP_Stage = "open_project" QPLog QP_Root, "INFO", "stage=open_project target=" & QPLogField(TargetPath) + QPProgress "open_project", 0, 1 Opened = App.OpenProject(CStr(TargetPath)) If Not Opened Then Err.Raise vbObjectError + 854, "QuickPartReplace.Session", "DxDesigner refused to open the target project" QP_OwnedProject = True @@ -460,6 +463,7 @@ Sub QPEnsureProject(ByRef App, ByVal TargetPath) Err.Raise vbObjectError + 854, "QuickPartReplace.Session", "opened project does not match the confirmed target" If QP_DiscoveryMode Then Exit Sub QP_Stage = "open_sheet" + QPProgress "open_sheet", 0, 1 Set View = App.ActiveView If Not View Is Nothing And Not QP_BatchMode Then Exit Sub Set Documents = App.SchematicSheetDocuments() diff --git a/src/dx_productivity/trial_task_center/batch.py b/src/dx_productivity/trial_task_center/batch.py index feac9c7..6f5de9d 100644 --- a/src/dx_productivity/trial_task_center/batch.py +++ b/src/dx_productivity/trial_task_center/batch.py @@ -25,6 +25,7 @@ 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' @@ -71,12 +72,14 @@ def execute_batch( 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') - session = preparer.begin_batch_session( - task_id, - projects, - rules, - copy_part_number_to_value=task.copy_part_number_to_value, - ) + with measure_phase(service._logging, task_id, 'prepare_queue', unit='step') as metric: + session = preparer.begin_batch_session( + task_id, + projects, + rules, + copy_part_number_to_value=task.copy_part_number_to_value, + ) + metric['completed_units'] = len(session.commands) initial_progress = progress progress = session.progress backup_root = session.handoff.command_path.parent @@ -94,10 +97,19 @@ def execute_batch( ] 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', @@ -137,7 +149,7 @@ def execute_batch( backed_up_roots.add(root_key) def backup_project(project_path: Path) -> None: - root_key = _path_key(project_path.resolve(strict=False).parent) + root_key = project_root_keys[_path_key(project_path)] if root_key in backed_up_roots: return previous = backup_state.get(root_key) @@ -155,11 +167,7 @@ def execute_batch( service._batch_feedback = (task_id, progress, f'正在备份 {project_path.name}') destination = backup_destination(root_key) try: - _backup_project_root( - preparer._data_root, - project_path, - destination, - ) + perform_backup(project_path, destination) except TaskCenterError as error: if error.code != 'quick_run_backup': raise @@ -169,15 +177,19 @@ def execute_batch( 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 = _path_key(project_path.resolve(strict=False).parent) + 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: @@ -233,7 +245,8 @@ def execute_batch( current = progress.next_project_path if current is None: raise TaskCenterError('quick_run_queue_progress', '队列未结束但找不到下一项,已停止。') - root_key = _path_key(current.resolve(strict=False).parent) + 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}') @@ -246,12 +259,7 @@ def execute_batch( if next_backup is not None: project_path, next_root_key = next_backup destination = backup_destination(next_root_key) - future = backup_executor.submit( - _backup_project_root, - preparer._data_root, - project_path, - destination, - ) + future = backup_executor.submit(perform_backup, project_path, destination) prefetched_backup = (project_path, next_root_key, destination, future) service._batch_feedback = (task_id, progress, f'正在处理 {current.name}') if stop_event.is_set(): @@ -262,8 +270,23 @@ def execute_batch( 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 '当前图页' service._batch_feedback = (task_id, progress, f'正在执行 {current.name} | {sheet}:{expected[1]} → {expected[2]}') - last_result = preparer.execute_step(task_id, projects, rules, copy_part_number_to_value=task.copy_part_number_to_value, - expected_item=expected, batch_mode=True, batch_session=session) + with measure_phase(service._logging, task_id, 'execute_step', unit='step', persist=False, + project_path=str(current), schematic_name=progress.next_schematic_name, + sheet_number=progress.next_sheet_number, old_part_number=expected[1], + new_part_number=expected[2], job_id=session.commands[session.next_index][1]) as metric: + try: + last_result = preparer.execute_step(task_id, projects, rules, copy_part_number_to_value=task.copy_part_number_to_value, + expected_item=expected, batch_mode=True, batch_session=session) + metric['state'] = last_result.state + metric['completed_units'] = int(last_result.state in {'saved_ok', 'restored_ok', 'no_match'}) + finally: + worker_progress = session.handoff.command_path.parent / 'worker-progress.json' + try: + native = json.loads(worker_progress.read_text(encoding='utf-8')) + if isinstance(native, dict) and native.get('job_id') == metric['job_id']: + metric['worker_stage_seconds'] = native.get('stage_seconds', {}) + except (OSError, ValueError): + pass if 'NC synced:' in last_result.message or last_result.state in { BATCH_FAILED_STATE, BATCH_SAVED_UNVERIFIED_STATE, @@ -279,15 +302,17 @@ def execute_batch( or candidate.queue_complete or last_result.state in {BATCH_FAILED_STATE, BATCH_SAVED_UNVERIFIED_STATE} ) - updated = service._synchronize_quick_run_progress(task_id, progress=candidate) if synchronize else candidate + if synchronize: + with measure_phase(service._logging, task_id, 'persist_progress', job_id=metric['job_id']) as persistence: + updated = service._synchronize_quick_run_progress(task_id, progress=candidate) + persistence['completed_units'] = 1 + 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') raise TaskCenterError('quick_run_queue_progress', '执行器返回后队列进度异常,已停止,避免重复执行。') # Keep every verified step: one project can contain many sheets and rules. - project_id = next( - (project.project_id for project in projects if _path_key(project.path) == _path_key(current)), - None, - ) + project_id = project_ids.get(current_key) event_level = 'WARNING' if last_result.state in { BATCH_FAILED_STATE, BATCH_SAVED_UNVERIFIED_STATE, @@ -295,6 +320,7 @@ def execute_batch( append_task_event(service._logging, level=event_level, task_id=task_id, project_id=project_id, operation='quick_run_executed', message=last_result.message, details={'state': last_result.state, 'continue_queue': not updated.queue_complete, + 'timing': metric, 'project_path': str(current), 'schematic_name': progress.next_schematic_name, 'sheet_number': progress.next_sheet_number, diff --git a/src/dx_productivity/trial_task_center/execution_metrics.py b/src/dx_productivity/trial_task_center/execution_metrics.py new file mode 100644 index 0000000..d542e30 --- /dev/null +++ b/src/dx_productivity/trial_task_center/execution_metrics.py @@ -0,0 +1,24 @@ +"""Monotonic phase measurements persisted beside task execution evidence.""" + +from contextlib import contextmanager +import time + +from .logging_setup import append_task_event + + +@contextmanager +def measure_phase(logging, task_id: str, phase: str, *, unit: str = 'operation', persist: bool = True, **details): + metric = {'phase': phase, 'unit': unit, 'completed_units': 0, 'state': 'completed', **details} + started = time.perf_counter() + try: + yield metric + except Exception as error: + metric.update(state='error', completed_units=0, error_code=getattr(error, 'code', type(error).__name__)) + raise + finally: + elapsed = max(0.0, time.perf_counter() - started) + metric['elapsed_seconds'] = elapsed + metric['units_per_minute'] = metric['completed_units'] * 60 / elapsed if elapsed > 0 else None + if persist or metric['state'] == 'error': + append_task_event(logging, level='WARNING' if metric['state'] == 'error' else 'INFO', + task_id=task_id, operation='execution_timing', details=metric) diff --git a/src/dx_productivity/trial_task_center/quick_run.py b/src/dx_productivity/trial_task_center/quick_run.py index 79e8f04..1b825cd 100644 --- a/src/dx_productivity/trial_task_center/quick_run.py +++ b/src/dx_productivity/trial_task_center/quick_run.py @@ -107,6 +107,10 @@ class QuickRunBatchSession: command_stamp: tuple[int, int, int, int, int] manifest_stamp: tuple[int, int, int, int, int] | None completed_project_keys: set[str] + status_stamp: tuple[int, int, int, int, int] + command_header: str + target_command_rows: dict[str, str] + worker_paths: tuple[str, str] class _ProcessRunner(Protocol): @@ -310,6 +314,10 @@ class QuickRunPreparer: project_keys_by_index = tuple(_path_key(command[2]) for command in commands) status_stat = _required_stat(handoff.status_path, "quick_run_status", "cannot inspect quick-run status") manifest_path = handoff.command_path.with_name("sheets.tsv") + command_lines = handoff.command_path.read_text(encoding='utf-8-sig').splitlines() + job_column = command_lines[0].split('\t').index('job_id') + target_command_rows = ({line.split('\t')[job_column]: line for line in command_lines[1:] if line} + if 'target_scope' in command_lines[0].split('\t') else {}) return QuickRunBatchSession( task_id, _value_mode(copy_part_number_to_value), @@ -328,6 +336,10 @@ class QuickRunPreparer: _file_stamp(handoff.command_path), _file_stamp(manifest_path) if sheets is not None else None, {_path_key(path) for path in progress.completed_project_paths}, + _stat_stamp(status_stat), + command_lines[0], + target_command_rows, + _vbs_worker_paths(handoff.script_path, handoff.script_path.parent), ) def execute_step( @@ -346,12 +358,15 @@ class QuickRunPreparer: if uncertain_path.exists(): raise TaskCenterError("quick_run_uncertain", "a previous quick-run worker timed out or returned an uncorrelated status; reconcile the project before retrying") current_root = self._data_root / "quick-run" - if self.evidence_path(task_id) == current_root and (current_root / "status.tsv").is_file(): + if batch_session is None and self.evidence_path(task_id) == current_root and (current_root / "status.tsv").is_file(): recorded = _read_status_details(current_root / "status.tsv") latest_states = {job_id: state for job_id, state, _, _ in recorded} if any(state == BATCH_SAVED_UNVERIFIED_STATE for state in latest_states.values()): _write_uncertain_flag(uncertain_path, "saved_readback_unverified") raise TaskCenterError("quick_run_uncertain", "saved readback was not verified; reconcile before continuing") + if batch_session is not None and any(state == BATCH_SAVED_UNVERIFIED_STATE for state, _ in batch_session.latest.values()): + _write_uncertain_flag(uncertain_path, 'saved_readback_unverified') + raise TaskCenterError('quick_run_uncertain', 'saved readback was not verified; reconcile before continuing') value_mode = _value_mode(copy_part_number_to_value) if batch_session is not None: if not batch_mode or batch_session.task_id != task_id or batch_session.value_mode != value_mode: @@ -391,11 +406,13 @@ class QuickRunPreparer: actual_item = (*selected_command[2:], value_mode) if expected_item is not None and actual_item != expected_item: raise TaskCenterError("quick_run_selection_changed", "confirmed queue item or Value policy changed; confirm again") + script_argument, root_argument = (batch_session.worker_paths if batch_session is not None + else _vbs_worker_paths(handoff.script_path, handoff.script_path.parent)) command = ( str(self._cscript_resolver()), "//nologo", - str(handoff.script_path), - str(handoff.script_path.parent), + script_argument, + root_argument, *_native_helper_launch_arguments(), selected_command[1], ) @@ -447,7 +464,7 @@ class QuickRunPreparer: status_offset = 0 status_identity = (0, 0) else: - appended, status_offset, status_identity = _read_appended_status_details(batch_session) + appended, status_offset, status_identity, status_stamp = _read_appended_status_details(batch_session) after = before + appended except TaskCenterError as error: _write_uncertain_flag(uncertain_path, "malformed_status_after_worker") @@ -539,6 +556,7 @@ class QuickRunPreparer: batch_session.statuses = after batch_session.status_offset = status_offset batch_session.status_identity = status_identity + batch_session.status_stamp = status_stamp _advance_batch_session(batch_session, changed) progress = batch_session.progress next_command = commands[batch_session.next_index] if batch_session.next_index < len(commands) else None @@ -812,11 +830,12 @@ class QuickRunPreparer: ) if collect_components: (root / "component-inventory.request").write_text(job_id, encoding="ascii") + script_argument, root_argument = _vbs_worker_paths(script, root) command = ( str(self._cscript_resolver()), "//nologo", - str(script), - str(root), + script_argument, + root_argument, *_native_helper_launch_arguments(), job_id, ) @@ -1570,7 +1589,7 @@ def _read_status_details(path: Path) -> tuple[tuple[str, str, str, str], ...]: def _read_appended_status_details( session: QuickRunBatchSession, -) -> tuple[tuple[tuple[str, str, str, str], ...], int, tuple[int, int]]: +) -> tuple[tuple[tuple[str, str, str, str], ...], int, tuple[int, int], tuple[int, int, int, int, int]]: path = session.handoff.status_path try: with path.open("rb") as handle: @@ -1581,7 +1600,7 @@ def _read_appended_status_details( handle.seek(session.status_offset) payload = handle.read() final = os.fstat(handle.fileno()) - if _file_identity(final) != identity or final.st_size != current.st_size: + if _stat_stamp(final)[:4] != _stat_stamp(current)[:4]: raise ValueError("status file changed while it was being read") if len(payload) != final.st_size - session.status_offset: raise ValueError("status tail length is inconsistent") @@ -1596,7 +1615,7 @@ def _read_appended_status_details( if len(fields) != 4 or not fields[0] or not fields[1]: raise ValueError("status tail is malformed") entries.append(tuple(_decode_vbs_field(field) for field in fields)) - return tuple(entries), final.st_size, identity + return tuple(entries), final.st_size, identity, _stat_stamp(final) except (OSError, UnicodeError, ValueError) as error: raise TaskCenterError("quick_run_status", "cannot incrementally read quick-run status") from error @@ -1614,10 +1633,22 @@ def _file_identity(stat: os.stat_result) -> tuple[int, int]: def _file_stamp(path: Path) -> tuple[int, int, int, int, int]: stat = _required_stat(path, "quick_run_command", "cannot inspect quick-run queue") + return _stat_stamp(stat) + + +def _stat_stamp(stat: os.stat_result) -> tuple[int, int, int, int, int]: return stat.st_dev, stat.st_ino, stat.st_size, stat.st_mtime_ns, stat.st_ctime_ns def _assert_batch_files_unchanged(session: QuickRunBatchSession) -> None: + try: + # On Windows, stat() and fstat() report different ctime semantics. + changed_status = _file_stamp(session.handoff.status_path)[:4] != session.status_stamp[:4] + except TaskCenterError: + changed_status = True + if changed_status: + _write_uncertain_flag(session.handoff.command_path.with_name('uncertain.flag'), 'status_changed_between_workers') + raise TaskCenterError('quick_run_uncertain', '执行状态文件在步骤间发生变化,尚未启动下一项,请先核验。') if _file_stamp(session.handoff.command_path) != session.command_stamp: raise TaskCenterError("quick_run_selection_changed", "batch command queue changed during execution") manifest_path = session.handoff.command_path.with_name("sheets.tsv") @@ -1630,14 +1661,12 @@ def _write_current_command( command: tuple[str, str, str, str, str], ) -> tuple[int, int, int, int, int]: task_id, job_id, project_path, old_part, new_part = command - full_lines = session.handoff.command_path.read_text(encoding="utf-8-sig").splitlines() - if "target_scope" in full_lines[0].split("\t"): - job_index = full_lines[0].split("\t").index("job_id") - matching = [line for line in full_lines[1:] if line.split("\t")[job_index] == job_id] - if len(matching) != 1: + if session.target_command_rows: + matching = session.target_command_rows.get(job_id) + if matching is None: raise TaskCenterError("quick_run_command", "target command is missing or duplicated") path = session.handoff.command_path.with_name("current-command.tsv") - _write_atomic_queue_text(path, full_lines[0] + "\r\n" + matching[0] + "\r\n", + _write_atomic_queue_text(path, session.command_header + "\r\n" + matching + "\r\n", "quick_run_command", "cannot publish the current target command") state = session.latest.get(job_id) state_path = path.with_name("current-state.tsv") @@ -1732,6 +1761,8 @@ def _encode_vbs_field(value: str) -> str: def _decode_vbs_field(value: str) -> str: + if value.isascii() and '%' not in value: + return value characters: list[str] = [] index = 0 while index < len(value): @@ -1815,6 +1846,22 @@ def _next_unfinished_command( return next((command for command in commands if final_states.get(command[1]) not in TERMINAL_STATES), None) +def _vbs_worker_paths(script: Path, root: Path) -> tuple[str, str]: + """FSO cannot see some paths beyond MAX_PATH, including monitor handshakes.""" + if os.name != 'nt' or len(str(root)) + 100 < 260: + return str(script), str(root) + import ctypes + get_short_path = ctypes.WinDLL('kernel32', use_last_error=True).GetShortPathNameW + get_short_path.argtypes = [ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint] + get_short_path.restype = ctypes.c_uint + buffer = ctypes.create_unicode_buffer(32768) + count = get_short_path(str(root.resolve(strict=True)), buffer, len(buffer)) + if not count or count >= len(buffer) or len(buffer.value) + 100 >= 260: + raise TaskCenterError('quick_run_path_length', + '执行证据目录过长,且系统未提供可用短路径。请将工具和数据放到较短目录后重试;尚未启动 CAD 操作。') + return str(Path(buffer.value) / script.name), buffer.value + + def _resolve_cscript(windows_root: Path | None = None, is_64_bit: bool | None = None) -> Path: windows = Path(windows_root) if windows_root is not None else Path(os.environ.get("WINDIR", r"C:\Windows")) if is_64_bit is None: diff --git a/src/dx_productivity/trial_task_center/recovery.py b/src/dx_productivity/trial_task_center/recovery.py index 3763b7c..a0d5fc0 100644 --- a/src/dx_productivity/trial_task_center/recovery.py +++ b/src/dx_productivity/trial_task_center/recovery.py @@ -190,7 +190,9 @@ def recover(preparer, task_id, projects, rules, *, copy_part_number_to_value=Fal row = (*row, 'targets', selectors) (worker / 'command.tsv').write_text(header + '\n' + '\t'.join(row) + '\n', encoding='utf-8') _write_status_details(worker / 'status.tsv', ()) - launch = (str(preparer._cscript_resolver()), '//nologo', str(script), str(worker), + from .quick_run import _vbs_worker_paths + script_argument, root_argument = _vbs_worker_paths(script, worker) + launch = (str(preparer._cscript_resolver()), '//nologo', script_argument, root_argument, *_native_helper_launch_arguments(), job_id) try: result = preparer._process_runner(launch, IDLE_PROGRESS_TIMEOUT_SECONDS) diff --git a/src/dx_productivity/trial_task_center/service.py b/src/dx_productivity/trial_task_center/service.py index a521bba..8199d13 100644 --- a/src/dx_productivity/trial_task_center/service.py +++ b/src/dx_productivity/trial_task_center/service.py @@ -23,6 +23,7 @@ from .inventory import collect_target_inventory from .spreadsheet_plan import export_target_plan as _export_target_plan, import_target_plan as _import_target_plan from .bom_plan import read_bom_plan as _read_bom_plan, write_bom_template as _write_bom_template from .project_context import ProjectTaskContext +from .execution_metrics import measure_phase _Result = TypeVar("_Result") @@ -365,7 +366,10 @@ class TaskCenterService: project = self._store.list_projects(task_id) if len(project) != 1: raise TaskCenterError("target_inventory", "target inventory requires one project task") - rows = collect_target_inventory(self._quick_run_preparer, project[0].path, parts) + with measure_phase(self._logging, task_id, 'collect_inventory', unit='component', + project_path=str(project[0].path)) as metric: + rows = collect_target_inventory(self._quick_run_preparer, project[0].path, parts) + metric['completed_units'] = len(rows) prior = self._store.list_target_plan(task_id) current = self._store.record_target_inventory(task_id, rows) if not current: @@ -639,17 +643,23 @@ class TaskCenterService: if self._store.get_task(task_id).status not in {TaskStatus.DRAFT, TaskStatus.READY, TaskStatus.RUNNING, TaskStatus.PAUSED}: raise TaskCenterError('quick_run_task_state', '当前任务状态不允许启动自动队列。') try: - result = self._operation( - 'execute_quick_run_queue', - task_id, - lambda: execute_batch( - self, + with measure_phase(self._logging, task_id, 'task_total', unit='task') as metric: + result = self._operation( + 'execute_quick_run_queue', task_id, - expected_item=expected_item, - stop_event=stop_event, - continue_after_backup_failure=continue_after_backup_failure, - ), - ) + lambda: execute_batch( + self, + task_id, + expected_item=expected_item, + stop_event=stop_event, + continue_after_backup_failure=continue_after_backup_failure, + ), + ) + metric['state'] = 'paused' if result.paused else 'failed' if result.progress.failed_items else 'completed' + metric['completed_units'] = int(result.progress.queue_complete and not result.progress.failed_items and not result.paused) + metric['completed_steps'] = result.progress.completed_items + metric['saved_steps'] = result.progress.saved_items + metric['failed_steps'] = result.progress.failed_items if result.paused: self._pause_quick_run_queue(task_id, 'queue paused at item boundary') return result diff --git a/src/dx_productivity/trial_task_center/ui/messages.py b/src/dx_productivity/trial_task_center/ui/messages.py index 8b8b957..0a4deb3 100644 --- a/src/dx_productivity/trial_task_center/ui/messages.py +++ b/src/dx_productivity/trial_task_center/ui/messages.py @@ -26,6 +26,7 @@ ERROR_TEXT = { "quick_run_session": "本次执行在启动或工程检查阶段停止,尚未开始本项替换。请按具体原因处理后重试。", "quick_run_complete": "当前任务中的替换规则已经全部完成。", "quick_run_cscript": "未找到 Windows 脚本运行组件,无法连接 DxDesigner。", + "quick_run_path_length": "执行目录过长,请使用较短的工具及数据目录。", "quick_run_command": "替换命令文件无效,请查看日志。", "quick_run_uncertain": "无法确认本次替换结果,请使用“核验并恢复中断任务”,不要直接清锁重跑。", "quick_run_recovery": "中断任务恢复未通过,原保护状态仍保留。", @@ -138,6 +139,22 @@ def _format_task_log_line(line: str) -> str: message = f'已保存但核验未通过,修改结果待确认。{message}' elif state in {'batch_failed', 'hard_failure'}: message = f'本步骤失败,未计入成功修改。{message}' + elif operation == 'execution_timing': + phases = {'prepare_queue': '图页枚举与队列准备', 'backup_project': '工程备份', + 'execute_step': '执行步骤(含保存回读)', 'persist_progress': '进度同步', + 'task_total': '本次任务执行合计', 'collect_inventory': '采集位号'} + elapsed = details.get('elapsed_seconds', 0) + location = ':'.join(str(details[key]) for key in ('schematic_name', 'sheet_number') if details.get(key)) + message = f"{phases.get(details.get('phase'), details.get('phase', '执行'))}:{elapsed:.3f} 秒" + if location: + message += f' · 图页 {location}' + if details.get('old_part_number'): + message += f" · {details['old_part_number']} → {details.get('new_part_number', '')}" + message += f" · 状态 {details.get('state', '')}" + rate = details.get('units_per_minute') + units = {'step': '步骤', 'task': '任务', 'component': '器件', 'operation': '次'} + if rate and details.get('completed_units'): + message += f" · {rate:.2f} {units.get(details.get('unit'), '次')}/分钟" elif operation == "quick_run_queue_paused": message = "自动队列已在项目边界暂停。" elif operation == "confirm_native_attempt": @@ -145,6 +162,11 @@ def _format_task_log_line(line: str) -> str: elif not message: message = operation.replace("_", " ") or "任务状态已更新。" + timing = details.get('timing') + if operation == 'quick_run_executed' and isinstance(timing, dict): + message += f"\n本步骤耗时 {timing['elapsed_seconds']:.3f} 秒" + if timing.get('completed_units') and timing.get('units_per_minute'): + message += f" · {timing['units_per_minute']:.2f} 步骤/分钟" error_id = str(event.get("error_id") or "").strip() if error_id: message = f"{message} 错误编号:{error_id}" diff --git a/src/dx_productivity/trial_task_center/worker_monitor.py b/src/dx_productivity/trial_task_center/worker_monitor.py index cf486bc..90f4960 100644 --- a/src/dx_productivity/trial_task_center/worker_monitor.py +++ b/src/dx_productivity/trial_task_center/worker_monitor.py @@ -32,6 +32,9 @@ class ProgressWatch: self.done = 0 self.total = 0 self.safe_stop = True + self.started = started + self.stage_started = started + self.stage_seconds: dict[str, float] = {} def accept(self, line: bytes, now: float) -> bool: try: @@ -45,6 +48,9 @@ class ProgressWatch: return False except (ValueError, UnicodeError): return False + if fields[4] != self.stage: + self.stage_seconds[self.stage] = self.stage_seconds.get(self.stage, 0.0) + max(0.0, now - self.stage_started) + self.stage_started = now self.sequence = sequence self.last_progress = now self.stage, self.done, self.total, self.safe_stop = fields[4], done, total, bool(safe) @@ -59,8 +65,12 @@ class ProgressWatch: return 'unresponsive' return None - def snapshot(self) -> dict: - return {name: getattr(self, name) for name in ('token', 'job_id', 'sequence', 'stage', 'done', 'total', 'safe_stop', 'stop_requested')} + def snapshot(self, *, now: float | None = None) -> dict: + now = time.monotonic() if now is None else now + stages = dict(self.stage_seconds) + stages[self.stage] = stages.get(self.stage, 0.0) + max(0.0, now - self.stage_started) + return {name: getattr(self, name) for name in ('token', 'job_id', 'sequence', 'stage', 'done', 'total', 'safe_stop', 'stop_requested')} | { + 'elapsed_seconds': max(0.0, now - self.started), 'stage_seconds': stages} def _atomic_text(path: Path, text: str) -> None: diff --git a/tests/trial_task_center/test_batch.py b/tests/trial_task_center/test_batch.py index 556b1fd..24555cb 100644 --- a/tests/trial_task_center/test_batch.py +++ b/tests/trial_task_center/test_batch.py @@ -386,6 +386,12 @@ def test_thousand_item_multisheet_mixed_queue_has_bounded_runtime_and_memory(tmp total = project_count * sheet_count * rule_count saved = len(range(0, total, 11)) + (tmp_path / 'stress-metrics.json').write_text(json.dumps({ + 'mode': 'simulated_worker_with_tracemalloc', 'projects': project_count, + 'sheets_per_project': sheet_count, 'rules_per_sheet': rule_count, + 'steps': total, 'saved_steps': saved, 'elapsed_seconds': elapsed, + 'peak_bytes': peak, 'steps_per_second': total / elapsed, + }, indent=2), encoding='utf-8') assert result.progress.queue_complete assert result.progress.total_items == total assert result.progress.saved_items == saved diff --git a/tests/v1_1/test_execution_metrics.py b/tests/v1_1/test_execution_metrics.py new file mode 100644 index 0000000..cd87dd7 --- /dev/null +++ b/tests/v1_1/test_execution_metrics.py @@ -0,0 +1,102 @@ +import json +import os +import subprocess + +import pytest + +from dx_productivity.trial_task_center import worker_monitor +from dx_productivity.trial_task_center.logging_setup import configure_logging + + +def test_phase_timing_records_completed_units_and_failure_without_success(tmp_path, monkeypatch): + from dx_productivity.trial_task_center import execution_metrics + + clock = iter((10.0, 12.0, 20.0, 23.0)) + monkeypatch.setattr(execution_metrics.time, 'perf_counter', lambda: next(clock)) + logging = configure_logging(tmp_path) + with execution_metrics.measure_phase(logging, 'task', 'execute_step', unit='step') as metric: + metric['completed_units'] = 1 + metric['state'] = 'saved_ok' + with pytest.raises(RuntimeError, match='worker failed'): + with execution_metrics.measure_phase(logging, 'task', 'execute_step', unit='step'): + raise RuntimeError('worker failed') + events = [json.loads(line) for line in (tmp_path / 'tasks/task/events.jsonl').read_text().splitlines()] + assert events[0]['details']['elapsed_seconds'] == 2 + assert events[0]['details']['units_per_minute'] == 30 + assert events[0]['details']['state'] == 'saved_ok' + assert events[1]['details']['elapsed_seconds'] == 3 + assert events[1]['details']['state'] == 'error' + assert events[1]['details']['completed_units'] == 0 + + +def test_worker_stages_include_repeated_stages_without_double_counting(): + watch = worker_monitor.ProgressWatch('token', 'job', 150, 0) + def frame(n, stage): + return f'DX_PROGRESS\ttoken\tjob\t{n}\t{stage}\t0\t1\t1\n'.encode() + assert watch.accept(frame(1, 'capture'), 2) + assert watch.accept(frame(2, 'native_replace'), 5) + assert not watch.accept(frame(2, 'ignored'), 100) + assert watch.accept(frame(3, 'capture'), 9) + snapshot = watch.snapshot(now=12) + assert snapshot['elapsed_seconds'] == 12 + assert snapshot['stage_seconds'] == {'starting': 2, 'capture': 6, 'native_replace': 4} + assert sum(snapshot['stage_seconds'].values()) == snapshot['elapsed_seconds'] + assert watch.snapshot(now=12) == snapshot + + +@pytest.mark.skipif(os.name != 'nt', reason='Windows Script Host path compatibility') +def test_long_evidence_path_remains_visible_to_real_vbs(tmp_path): + from dx_productivity.trial_task_center.quick_run import _vbs_worker_paths, _resolve_cscript + + root = tmp_path / ('evidence-' + 'x' * 80) / ('discovery-' + 'y' * 60) + root.mkdir(parents=True) + script = root / 'QuickPartReplace.vbs' + script.write_text("Set f=CreateObject(\"Scripting.FileSystemObject\")\n" + "WScript.Echo CStr(f.FileExists(f.BuildPath(WScript.Arguments(0), WScript.Arguments(1))))\n") + marker = 'monitor-' + 'a' * 32 + '.ready' + (root / marker).write_text('token') + assert len(str(root / marker)) > 259 + script_arg, root_arg = _vbs_worker_paths(script, root) + result = subprocess.run((str(_resolve_cscript()), '//nologo', script_arg, root_arg, marker), + capture_output=True, text=True, timeout=10) + assert result.returncode == 0 and result.stdout.strip() == 'True' + + +def test_external_status_append_blocks_next_worker_before_cad_write(tmp_path): + from pathlib import Path + from threading import Event + from dx_productivity.trial_task_center.quick_run import QuickRunPreparer + from dx_productivity.trial_task_center.service import TaskCenterService + from dx_productivity.trial_task_center.store import TaskStore + from dx_productivity.trial_task_center.errors import TaskCenterError + + root = tmp_path / 'projects'; root.mkdir() + (root / 'board.prj').write_text('KEY FrontEndSnapshot "DxD"\nKEY iCDBDir "database"\n') + data = tmp_path / 'data'; calls = [] + def worker(command, timeout): + calls.append(command[-1]) + with (Path(command[3]) / 'status.tsv').open('a', encoding='utf-8') as stream: + stream.write(f'{command[-1]}\tno_match\tbatch_closed\tnot found\n') + return subprocess.CompletedProcess(command, 0, '', '') + store = TaskStore(tmp_path / 'tasks.db') + preparer = QuickRunPreparer(data, process_runner=worker, cscript_resolver=lambda: Path('cscript'), + sheet_discoverer=lambda _: (('MAIN', '1'),)) + service = TaskCenterService(store, configure_logging(data), quick_run_preparer=preparer) + task = service.create_project_tasks(root)[0] + service.add_rule(task.task_id, 'A', 'B'); service.add_rule(task.task_id, 'C', 'D') + child = service.for_project_task(task.task_id)._quick_run_preparer + original = child.execute_step + def inject(*args, **kwargs): + result = original(*args, **kwargs) + if len(calls) == 1: + with result.status_path.open('a', encoding='utf-8') as stream: + stream.write('foreign_job\tno_match\tbatch_closed\tchanged externally\n') + return result + child.execute_step = inject + progress = service.quick_run_progress(task.task_id) + with pytest.raises(TaskCenterError): + service.execute_quick_run_queue(task.task_id, + expected_item=(str(progress.next_project_path), 'A', 'B', 'preserve'), stop_event=Event()) + assert len(calls) == 1 + assert (child._data_root / 'quick-run/uncertain.flag').exists() + store.close() diff --git a/tests/v1_1/test_multi_project_regression.py b/tests/v1_1/test_multi_project_regression.py new file mode 100644 index 0000000..6646629 --- /dev/null +++ b/tests/v1_1/test_multi_project_regression.py @@ -0,0 +1,17 @@ +import importlib.util +from pathlib import Path + +import pytest + + +@pytest.mark.parametrize('behavior', ['success', 'failure_continue', 'uncertain_stop', 'pause_resume']) +def test_multiple_projects_preserve_task_order_scope_results_and_measurements(tmp_path, behavior): + path = Path(__file__).resolve().parents[2] / 'tools/measure_task_queue.py' + spec = importlib.util.spec_from_file_location('measure_task_queue', path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + report = module.run_scenario(tmp_path / behavior, projects=3, sheets=2, rules=2, behavior=behavior) + assert report['checks'] == 'passed' + timings = report['timings'] + assert len([row for row in timings if row['phase'] == 'execute_step']) == report['executed_steps'] + assert all(row['elapsed_seconds'] >= 0 for row in timings) diff --git a/tools/measure_task_queue.py b/tools/measure_task_queue.py new file mode 100644 index 0000000..c43f2ae --- /dev/null +++ b/tools/measure_task_queue.py @@ -0,0 +1,183 @@ +"""Multi-project regression with real storage/BOM/queues and a simulated CAD worker. + +This measures software overhead, never native CAD replacement throughput. +""" +from __future__ import annotations + +import argparse +import csv +from dataclasses import asdict +import json +from pathlib import Path +import subprocess +import sys +from threading import Event +import time + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'src')) + +from dx_productivity.trial_task_center.bom_plan import write_bom_template +from dx_productivity.trial_task_center.inventory import HEADER +from dx_productivity.trial_task_center.logging_setup import configure_logging +from dx_productivity.trial_task_center.quick_run import QuickRunPreparer, _decode_vbs_field, _encode_vbs_field +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 +from dx_productivity.trial_task_center.task_queue import execute_task_queue +from dx_productivity.trial_task_center.ui.messages import _format_task_log_lines + + +def run_scenario(output: Path, *, projects=3, sheets=2, rules=2, behavior='success') -> dict: + output = Path(output).resolve() + output.mkdir(parents=True, exist_ok=False) + started = time.perf_counter() + timings, calls, targets, model = [], [], {}, {} + stop = Event() + + def measured(phase, action): + tick = time.perf_counter() + value = action() + timings.append({'layer': 'workflow', 'phase': phase, 'elapsed_seconds': time.perf_counter() - tick}) + return value + + def write_tsv(path, header, rows): + path.write_text('\t'.join(header) + '\n' + ''.join( + '\t'.join(_encode_vbs_field(str(value)) for value in row) + '\n' for row in rows), encoding='utf-8') + + root = output / 'projects' + for index in range(projects): + path = root / f'board-{index:03}' / 'board.prj' + path.parent.mkdir(parents=True) + path.write_text('KEY FrontEndSnapshot "DxD"\nKEY iCDBDir "database"\n') + inventory = tuple(ComponentTarget(path, 'MAIN', str(sheet), f'{sheet}-{part}-{ref}', + f'R{part * 3 + ref}', f'OLD-{part}', '10K/NC' if ref == 1 else '10K') + for sheet in range(1, sheets + 1) for part in range(rules) for ref in range(1, 4)) + targets[str(path).casefold()] = inventory + model.update({target.key: target.old_part_number for target in inventory}) + + def worker(command, timeout): + evidence = Path(command[3]) + with (evidence / ('current-command.tsv' if (evidence / 'current-command.tsv').exists() else 'command.tsv')).open(encoding='utf-8-sig') as stream: + item = next(csv.DictReader(stream, delimiter='\t')) + path = Path(item['project_path']) + inventory = targets[str(path).casefold()] + if (evidence / 'sheet-discovery.request').exists(): + write_tsv(evidence / 'sheets.tsv', ('project_path', 'schematic_name', 'sheet_number'), + ((path, 'MAIN', s) for s in range(1, sheets + 1))) + write_tsv(evidence / 'inventory.tsv', ('project_path', 'schematic_name', 'sheet_number', 'old_part'), + ((path, 'MAIN', s, f'OLD-{p}') for s in range(1, sheets + 1) for p in range(rules))) + write_tsv(evidence / 'components.tsv', HEADER, + ((path, t.schematic_name, t.sheet_number, t.uid, t.refdes, t.old_part_number, t.old_value) for t in inventory)) + return subprocess.CompletedProcess(command, 0, '', '') + assert item['target_scope'] == 'targets' + selected = [entry.split('\x1f') for entry in _decode_vbs_field(item['target_selectors']).split('\x1e')] + matched = [t for t in inventory if t.sheet_number == item['sheet_number'] and t.uid in {s[0] for s in selected}] + assert len(matched) == 2 + assert {(t.uid, t.refdes, t.old_value) for t in matched} == {tuple(s) for s in selected} + assert all(model[t.key] == item['old_part'] for t in matched) + state = 'saved_ok' + if not calls and behavior in {'failure_continue', 'uncertain_stop'}: + state = 'batch_failed' if behavior == 'failure_continue' else 'batch_saved_unverified' + if state == 'saved_ok': + for target in matched: + model[target.key] = item['new_part'] + job = command[-1] + assert item['job_id'] == job + assert job not in {call['job_id'] for call in calls} + calls.append({'job_id': job, 'project': path.parent.name, 'task_id': item['task_id'], + 'sheet': item['sheet_number'], 'old': item['old_part'], 'new': item['new_part'], + 'refdes': [t.refdes for t in matched], 'state': state}) + message = ('Native replacement and parameter readback passed on current sheet. Replacements: ' + + '; '.join(f'{t.refdes} {item["old_part"]} -> {item["new_part"]}' for t in matched) + + ' Display verified: attributes=2. Saved, reopened for readback, and closed.') + if state != 'saved_ok': + message = 'Injected worker failure for regression; no native CAD operation.' + with (evidence / 'status.tsv').open('a', encoding='utf-8') as stream: + stream.write(f'{job}\tawaiting_native_replace\t\tcaptured\n') + stream.write(f'{job}\t{state}\tbatch_closed\t{message}\n') + if behavior == 'pause_resume' and len(calls) == 2: + stop.set() + return subprocess.CompletedProcess(command, 0, '', '') + + store = TaskStore(output / 'tasks.db') + service = TaskCenterService(store, configure_logging(output / 'data'), + quick_run_preparer=QuickRunPreparer(output / 'data', process_runner=worker, + cscript_resolver=lambda: Path('simulated-cscript'), + sheet_discoverer=lambda _: tuple(('MAIN', str(s)) for s in range(1, sheets + 1)))) + try: + tasks = measured('create_tasks', lambda: service.create_project_tasks(root)) + assert len(tasks) == projects + for task in tasks: + for part in range(rules): + service.add_rule(task.task_id, f'OLD-{part}', f'NEW-{part}') + rows = measured('collect_inventory', lambda: service.collect_target_inventory(task.task_id)) + assert len(rows) == sheets * rules * 3 + bom = output / f'{task.task_id}.xlsx' + records = [] + for sheet in range(1, sheets + 1): + for part in range(rules): + records.append({'old_part_number': f'OLD-{part}', 'new_part_number': f'NEW-{part}', + 'refdes': f'R{part * 3 + 1}, R{part * 3 + 2}', 'schematic_name': 'MAIN', + 'sheet_number': str(sheet), 'sync_nc': part % 2 == 0}) + measured('write_bom', lambda: write_bom_template(bom, records)) + preview = measured('import_bom', lambda: service.preview_bom_plan(task.task_id, bom)) + measured('save_plan', lambda: service.replace_target_plan(task.task_id, preview)) + ids = tuple(task.task_id for task in tasks) + result = measured('queue_wall', lambda: execute_task_queue(service, ids, stop_event=stop)) + if behavior == 'pause_resume': + assert result.paused and len(calls) == 2 + stop.clear() + result = measured('queue_resume_wall', lambda: execute_task_queue(service, ids, stop_event=stop, queue_id=result.queue_id)) + expected_steps = projects * sheets * rules + assert len(calls) == (1 if behavior == 'uncertain_stop' else expected_steps) + if behavior == 'uncertain_stop': + assert result.paused and result.entries[0].state == 'blocked' + assert all(entry.state == 'pending' for entry in result.entries[1:]) + else: + assert not result.paused + assert [entry.state for entry in result.entries] == ['failed' if behavior == 'failure_continue' and i == 0 else 'completed' for i in range(projects)] + # Every task runs contiguously and each unselected RefDes keeps its baseline. + order = [call['task_id'] for call in calls] + assert order == sorted(order, key=ids.index) + changed = sum(model[t.key] != t.old_part_number for inventory in targets.values() for t in inventory) + assert changed == sum(call['state'] == 'saved_ok' for call in calls) * 2 + assert all(model[t.key] == t.old_part_number for inventory in targets.values() for t in inventory if int(t.uid.split('-')[-1]) == 3) + for task in tasks: + events = [json.loads(line) for line in service.tail_log(task.task_id, limit=None)] + timings.extend(event['details'] | {'layer': 'execution', 'task_id': task.task_id, 'project': service.projects(task.task_id)[0].path.parent.name} + for event in events if event['operation'] == 'execution_timing') + timings.extend(event['details']['timing'] | {'layer': 'execution', 'task_id': task.task_id, + 'project': service.projects(task.task_id)[0].path.parent.name} + for event in events if event['operation'] == 'quick_run_executed' and 'timing' in event['details']) + executed = [event for event in events if event['operation'] == 'quick_run_executed'] + own = [call for call in calls if call['task_id'] == task.task_id] + assert len(executed) == len(own) + rendered = '\n'.join(_format_task_log_lines(tuple(json.dumps(event) for event in executed))) + for call in own: + if call['state'] == 'saved_ok': + assert all(f'位号 {ref}:{call["old"]} → {call["new"]}' in rendered for ref in call['refdes']) + report = {'mode': 'simulated_cad_worker_real_storage_bom_and_queue', 'behavior': behavior, + 'projects': projects, 'sheets_per_project': sheets, 'rules_per_sheet': rules, + 'executed_steps': len(calls), 'changed_components': changed, + 'unselected_components_preserved': projects * sheets * rules, + 'elapsed_seconds': time.perf_counter() - started, 'result': asdict(result), + 'calls': calls, 'timings': timings, 'checks': 'passed'} + (output / 'report.json').write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8') + fields = sorted({key for row in timings for key in row}) + with (output / 'timings.csv').open('w', newline='', encoding='utf-8-sig') as stream: + writer = csv.DictWriter(stream, fieldnames=fields); writer.writeheader(); writer.writerows(timings) + return report + finally: + store.close() + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--output', type=Path, required=True) + parser.add_argument('--projects', type=int, default=3) + parser.add_argument('--sheets', type=int, default=2) + parser.add_argument('--rules', type=int, default=2) + parser.add_argument('--behavior', choices=('success', 'failure_continue', 'uncertain_stop', 'pause_resume'), default='success') + args = parser.parse_args() + result = run_scenario(args.output, projects=args.projects, sheets=args.sheets, rules=args.rules, behavior=args.behavior) + print(json.dumps({key: result[key] for key in ('mode', 'behavior', 'projects', 'executed_steps', 'elapsed_seconds', 'checks')}))