feat: share batch runtime across queues and expose resource cleanup

This commit is contained in:
阿白叔 committed 2026-10-21 14:30:01 +08:00
1 parent 832ab5d563
commit 00861a59d6
17 files changed
+322 -36

No files matched your search

@@ -41,6 +41,7 @@ def execute_batch(
stop_event: Event,
continue_after_backup_failure: bool = False,
reuse_project_session: bool = True,
runtime=None,
) -> BatchRunResult:
preparer = service._quick_run_preparer
retention = maintain_quick_run_storage(preparer.data_root)
@@ -71,6 +72,7 @@ def execute_batch(
projects,
rules,
copy_part_number_to_value=task.copy_part_number_to_value,
**({'runtime': runtime} if runtime is not None else {}),
)
metric['completed_units'] = len(session.commands)
initial_progress = progress
@@ -108,7 +110,8 @@ def execute_batch(
progress.total_items,
)
progress = session.progress
with backups, preparer.project_session_scope(enabled=reuse_project_session) as project_session:
with backups, preparer.project_session_scope(enabled=reuse_project_session,
**({'runtime': runtime} if runtime is not None else {})) as project_session:
while not progress.queue_complete:
if stop_event.is_set():
backups.commit_prefetched(progress)
@@ -137,7 +140,8 @@ def execute_batch(
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,
**({'project_session': project_session} if project_session.enabled else {}))
**({'project_session': project_session} if project_session.enabled else {}),
**({'runtime': runtime} if runtime is not None else {}))
metric['state'] = last_result.state
metric['completed_units'] = int(last_result.state in {'saved_ok', 'restored_ok', 'no_match'})
finally:
@@ -1,4 +1,6 @@
"""Read-only, exhaustive BOM validation with an all-or-nothing preview."""
import inspect
from dataclasses import dataclass, replace
from pathlib import Path
from zipfile import BadZipFile
@@ -121,12 +123,24 @@ def _check_record_conflicts(rows, records, indices):
rows[index] = replace(rows[index], status='failed', reason=reason)
def inspect_batch(service, task_id, path, *, stop_event=None, on_progress=None, on_phase=None):
def inspect_batch(service, task_id, path, *, stop_event=None, on_progress=None, on_phase=None, runtime=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.
"""
if runtime is None:
from .batch_runtime import BatchCadRuntime, BatchResourceCleanupError
report = None
try:
with BatchCadRuntime(service._logging.root, 'bom_import', stop_event) as owned_runtime:
report = inspect_batch(service, task_id, path, stop_event=stop_event,
on_progress=on_progress, on_phase=on_phase, runtime=owned_runtime)
owned_runtime.result = report
return report
except BatchResourceCleanupError as error:
error.bom_report = report
raise
def check_cancelled():
if stop_event is not None and stop_event.is_set():
raise TaskCenterError('operation_cancelled', 'BOM 导入已取消')
@@ -243,13 +257,16 @@ def inspect_batch(service, task_id, path, *, stop_event=None, on_progress=None,
inventory = tuple(row.target for row in baseline)
else:
progress(f'「{task.name}」正在获取位号库存,仅采集本表涉及的旧料号及已有计划料号')
controls = {}
collector = service.for_project_task(task.task_id)._quick_run_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(service.for_project_task(task.task_id)._quick_run_preparer.collect_inventory(
inventory = tuple(collector(
project.path, tuple(dict.fromkeys((*known, *requested))), **controls))
except TaskCenterError as error:
if error.code == 'operation_cancelled':
@@ -71,7 +71,7 @@ class NativeInventoryReader:
raise NativeInventoryUnsupported('本机未安装完整的原生器件清单工具')
return tools
def read(self, project, old_part_numbers, *, stop_event=None, on_progress=None):
def read(self, project, old_part_numbers, *, stop_event=None, on_progress=None, runtime=None):
check_cancelled(stop_event)
try:
project = Path(project).resolve(strict=True)
@@ -81,9 +81,9 @@ class NativeInventoryReader:
report_progress(on_progress, f'使用 CAD 核验位号:{str(error)[:160]}')
return None
return self._read(project, text, block, snapshot, database, tools, old_part_numbers,
stop_event=stop_event, on_progress=on_progress)
stop_event=stop_event, on_progress=on_progress, runtime=runtime)
def _read(self, project, text, block, snapshot, database, tools, old_part_numbers, *, stop_event, on_progress):
def _read(self, project, text, block, snapshot, database, tools, old_part_numbers, *, stop_event, on_progress, runtime=None):
token = uuid4().hex
evidence = self.data_root / 'quick-run-history' / ('native-inventory-' + token)
evidence.mkdir(parents=True, exist_ok=False)
@@ -91,7 +91,8 @@ class NativeInventoryReader:
/ 'DxProductivity' / 'native-inventory').resolve()
base.mkdir(parents=True, exist_ok=True)
workspace = Path(tempfile.mkdtemp(prefix='dx-cli-', dir=base)).resolve()
desktop = self.desktop_factory('dx-cli-' + token, enabled=True)
desktop = (runtime.native_scope(evidence) if runtime is not None
else self.desktop_factory('dx-cli-' + token, enabled=True))
record = {'backend': 'native_cli', 'project': str(project), 'state': 'reading',
'workspace': str(workspace), 'tools': []}
started = time.monotonic()
@@ -20,6 +20,11 @@ class ReleasedProjectReadError(TaskCenterError):
def _read_failure(root, message):
error_type = TaskCenterError
if (root / 'project-checkpoint.json').exists():
from .batch_runtime import project_checkpoint_released
if project_checkpoint_released(root):
error_type = ReleasedProjectReadError
return error_type('quick_run_sheet_discovery', message)
try:
record = json.loads((root / 'private-desktop.json').read_text(encoding='utf-8'))
cleanup = record['desktop_cleanup']
@@ -132,6 +137,10 @@ def discover_project(
def _require_released_reader(root):
if (root / 'project-checkpoint.json').exists():
from .batch_runtime import project_checkpoint_released
if not project_checkpoint_released(root):
raise TaskCenterError('inventory_cleanup', f'工程读取关闭检查点无效,请保留诊断记录:{root}')
if (root / 'uncertain.flag').exists():
raise TaskCenterError('inventory_cleanup', f'采集会话未能正常收尾,请检查诊断记录后重试:{root}')
@@ -33,7 +33,7 @@ class ProjectSessionWorker:
The VBS worker owns CAD. This driver never attaches to COM or terminates CAD.
A separate monitor thread retains the existing idle watchdog and worker job.
"""
def __init__(self, project: Path, root: Path, *, private_desktop=False):
def __init__(self, project: Path, root: Path, *, private_desktop=False, runtime=None):
self.project, self.root = Path(project), Path(root).resolve()
self.token = uuid4().hex
self._done, self._abort = Event(), Event()
@@ -46,12 +46,13 @@ class ProjectSessionWorker:
self._timeout = 150
self.starts = 0
self.private_desktop = private_desktop
self.runtime = runtime
def _monitor(self, command, timeout):
try:
if self.private_desktop:
if self.private_desktop or self.runtime is not None:
from .isolated_cad import run_isolated_process
self._result = run_isolated_process(command, timeout, abort_event=self._abort)
self._result = run_isolated_process(command, timeout, abort_event=self._abort, **({'runtime': self.runtime} if self.runtime is not None else {}))
else:
self._result = run_monitored_process(command, timeout, abort_event=self._abort)
except Exception as error:
@@ -130,10 +131,11 @@ class ProjectSessionWorker:
class ProjectSessionScope:
"""One serial task can visit projects, but can hold only one worker at a time."""
def __init__(self, fallback, *, enabled, private_desktop=False):
def __init__(self, fallback, *, enabled, private_desktop=False, runtime=None):
self.fallback, self.enabled = fallback, enabled
self.worker = None
self.private_desktop = private_desktop
self.runtime = runtime
def __enter__(self):
return self
@@ -143,7 +145,7 @@ class ProjectSessionScope:
return self.fallback(command, timeout)
self.prepare(project)
if self.worker is None:
self.worker = ProjectSessionWorker(Path(project), Path(command[3]), private_desktop=self.private_desktop)
self.worker = ProjectSessionWorker(Path(project), Path(command[3]), private_desktop=self.private_desktop, runtime=self.runtime)
return self.worker.run_step(command, timeout)
def prepare(self, project):
@@ -7,6 +7,7 @@ from contextlib import contextmanager
from dataclasses import dataclass
from datetime import datetime, timezone
from functools import lru_cache
import inspect
import json
import os
from pathlib import Path
@@ -171,6 +172,7 @@ class QuickRunPreparer:
*,
copy_part_number_to_value: bool = False,
before_sheet_discovery: Callable[[Path], None] | None = None,
runtime=None,
) -> QuickRunResult:
"""Create a page-addressed queue after read-only sheet discovery."""
all_selected_projects = _selected_projects(projects)
@@ -201,7 +203,8 @@ class QuickRunPreparer:
before_sheet_discovery(project.path)
if self._sheet_discoverer is None:
discovery = self.discover_project(project.path, old_part_numbers,
**({'collect_components': True} if targeted else {}))
**({'collect_components': True} if targeted else {}),
**({'runtime': runtime} if runtime is not None else {}))
if targeted:
from .inventory import validate_target_inventory
validate_target_inventory(project.path, enabled_rules, discovery.components)
@@ -244,6 +247,7 @@ class QuickRunPreparer:
*,
copy_part_number_to_value: bool = False,
before_sheet_discovery: Callable[[Path], None] | None = None,
runtime=None,
) -> QuickRunBatchSession:
enabled_rules = tuple(rule for rule in rules if rule.enabled)
handoff = self.ensure_batch_handoff(
@@ -252,6 +256,7 @@ class QuickRunPreparer:
rules,
copy_part_number_to_value=copy_part_number_to_value,
before_sheet_discovery=before_sheet_discovery,
**({'runtime': runtime} if runtime is not None else {}),
)
source = self._required_script_source()
if source.resolve() != handoff.script_path.resolve():
@@ -301,13 +306,13 @@ class QuickRunPreparer:
)
@contextmanager
def project_session_scope(self, *, enabled=True):
def project_session_scope(self, *, enabled=True, runtime=None):
"""Retain only the built-in supervised worker; injected workers stay compatible."""
from .project_session import ProjectSessionScope
from .worker_monitor import WorkerMonitorError
try:
with ProjectSessionScope(self._process_runner,
enabled=enabled and self._process_runner is _run_process, private_desktop=True) as scope:
enabled=enabled and self._process_runner is _run_process, private_desktop=True, runtime=runtime) as scope:
yield scope
except (WorkerMonitorError, subprocess.TimeoutExpired) as error:
_write_uncertain_flag(self._data_root / 'quick-run/uncertain.flag', 'project_session_cleanup')
@@ -325,6 +330,7 @@ class QuickRunPreparer:
batch_mode: bool = False,
batch_session: QuickRunBatchSession | None = None,
project_session=None,
runtime=None,
) -> QuickRunStepResult:
"""Prepare or resume a queue, then execute one replacement rule end to end."""
uncertain_path = self._data_root / "quick-run" / "uncertain.flag"
@@ -367,7 +373,8 @@ class QuickRunPreparer:
if handoff is None:
if any(getattr(rule, "scope", "all") == "targets" for rule in enabled_rules):
handoff = self.ensure_batch_handoff(task_id, projects, rules,
copy_part_number_to_value=copy_part_number_to_value)
copy_part_number_to_value=copy_part_number_to_value,
**({'runtime': runtime} if runtime is not None else {}))
else:
handoff = self.prepare(task_id, projects, rules,
copy_part_number_to_value=copy_part_number_to_value)
@@ -407,6 +414,8 @@ class QuickRunPreparer:
try:
if project_session is not None:
completed = project_session.run_step(Path(selected_command[2]), command, IDLE_PROGRESS_TIMEOUT_SECONDS)
elif runtime is not None and self._process_runner is _run_process:
completed = _run_process(command, IDLE_PROGRESS_TIMEOUT_SECONDS, runtime=runtime)
else:
completed = self._process_runner(command, IDLE_PROGRESS_TIMEOUT_SECONDS)
except subprocess.TimeoutExpired as error:
@@ -681,10 +690,14 @@ class QuickRunPreparer:
self._discovery_cache.invalidate(project_path)
def discover_project(self, project_path: Path, old_part_numbers: tuple[str, ...], *,
collect_components: bool = False, stop_event=None, on_progress=None) -> ProjectDiscovery:
collect_components: bool = False, stop_event=None, on_progress=None, runtime=None) -> ProjectDiscovery:
from .operation_control import check_cancelled, control_options, report_progress
check_cancelled(stop_event)
controls = control_options(stop_event, on_progress)
if runtime is not None and any(
parameter.name == 'runtime' or parameter.kind is inspect.Parameter.VAR_KEYWORD
for parameter in inspect.signature(self._discover_project_sheets).parameters.values()):
controls['runtime'] = runtime
attempt = 0
def load():
nonlocal attempt
@@ -700,14 +713,15 @@ class QuickRunPreparer:
Path(project_path), old_part_numbers, collect_components, load,
**({'stop_event': stop_event} if stop_event is not None else {}))
def collect_inventory(self, project_path: Path, old_part_numbers: tuple[str, ...], *, stop_event=None, on_progress=None) -> tuple:
def collect_inventory(self, project_path: Path, old_part_numbers: tuple[str, ...], *, stop_event=None, on_progress=None, runtime=None) -> tuple:
"""Collect validated component targets, retaining reusable sheet evidence."""
if not old_part_numbers:
raise TaskCenterError("target_inventory", "at least one old Part Number is required")
requested = {part.casefold() for part in old_part_numbers}
from .operation_control import control_options
return tuple(component for component in self.discover_project(
project_path, old_part_numbers, collect_components=True, **control_options(stop_event, on_progress)).components
project_path, old_part_numbers, collect_components=True, **control_options(stop_event, on_progress),
**({'runtime': runtime} if runtime is not None else {})).components
if component.old_part_number.casefold() in requested)
def _discover_project_sheets(
@@ -718,6 +732,7 @@ class QuickRunPreparer:
collect_components: bool = False,
stop_event=None,
on_progress=None,
runtime=None,
) -> _ProjectDiscovery:
"""Enumerate sheets and requested source parts while the owned project is open."""
from .project_discovery import DiscoveryRuntime, discover_project
@@ -726,14 +741,16 @@ class QuickRunPreparer:
if collect_components and self._process_runner is _run_process:
from .native_inventory import NativeInventoryReader
native = NativeInventoryReader(self._data_root).read(
project_path, old_part_numbers, stop_event=stop_event, on_progress=on_progress)
project_path, old_part_numbers, stop_event=stop_event, on_progress=on_progress,
**({'runtime': runtime} if runtime is not None else {}))
if native is not None:
return native
process_runner = self._process_runner
if stop_event is not None and process_runner is _run_process:
if (stop_event is not None or runtime is not None) and process_runner is _run_process:
def process_runner(command, timeout):
return _run_process(command, timeout, abort_event=stop_event)
return _run_process(command, timeout, abort_event=stop_event,
**({'runtime': runtime} if runtime is not None else {}))
return discover_project(project_path, old_part_numbers,
data_root=self._data_root, script_source=self._required_script_source(),
@@ -1751,12 +1768,13 @@ def _cached_native_helper_launch_arguments(frozen: bool, executable: str) -> tup
return (resolved_executable, str(Path(__file__).with_name("application.py")))
def _run_process(command: tuple[str, ...], timeout: int, *, abort_event=None) -> subprocess.CompletedProcess[str]:
def _run_process(command: tuple[str, ...], timeout: int, *, abort_event=None, runtime=None) -> subprocess.CompletedProcess[str]:
from .isolated_cad import run_isolated_process
from .legacy_paths import validate_project_access
validate_project_access(Path(command[3]))
result = run_isolated_process(command, timeout,
**({'runtime': runtime} if runtime is not None else {}),
**({'abort_event': abort_event, 'cooperative_abort': True} if abort_event is not None else {}))
validate_project_access(Path(command[3]))
return result
@@ -663,12 +663,21 @@ class TaskCenterService:
stop_event: threading.Event,
continue_after_backup_failure: bool = False,
reuse_project_session: bool = True,
runtime=None,
):
if runtime is None:
from .batch_runtime import BatchCadRuntime
with BatchCadRuntime(self._logging.root, 'quick_run_queue', stop_event) as owned_runtime:
result = self.execute_quick_run_queue(task_id, expected_item=expected_item,
stop_event=stop_event, continue_after_backup_failure=continue_after_backup_failure,
reuse_project_session=reuse_project_session, runtime=owned_runtime)
owned_runtime.result = result
return result
delegated = self._project_task_service(task_id)
if delegated is not self:
return delegated.execute_quick_run_queue(task_id, expected_item=expected_item,
stop_event=stop_event, continue_after_backup_failure=continue_after_backup_failure,
reuse_project_session=reuse_project_session)
reuse_project_session=reuse_project_session, runtime=runtime)
from .batch import execute_batch
from .task_queue import assert_task_queue_idle
@@ -690,6 +699,7 @@ class TaskCenterService:
stop_event=stop_event,
continue_after_backup_failure=continue_after_backup_failure,
reuse_project_session=reuse_project_session,
runtime=runtime,
),
)
metric['state'] = 'paused' if result.paused else 'failed' if result.progress.failed_items else 'completed'
@@ -700,7 +710,9 @@ class TaskCenterService:
if result.paused:
self._pause_quick_run_queue(task_id, 'queue paused at item boundary')
return result
except Exception:
except Exception as error:
if getattr(error, 'code', None) == 'batch_resources_pending':
raise
self._pause_quick_run_queue(task_id, 'queue stopped after execution error')
raise
finally:
@@ -775,6 +787,19 @@ class TaskCenterService:
return self._idle_quick_run_operation('start_new_round', task_id,
lambda: start_new_round(self, task_id))
def pending_batch_resources(self):
from .batch_runtime import pending_resources
return pending_resources(self._logging.root)
def cleanup_batch_resources(self):
"""Retry owned-resource release without opening or changing any project."""
from .batch_runtime import cleanup_pending_resources
from .task_queue import assert_task_queue_idle
assert_task_queue_idle(self._logging.root)
with _quick_run_lease(self._logging.root):
return self._operation('cleanup_batch_resources', None,
lambda: cleanup_pending_resources(self._logging.root))
def inspect_bom_batch(self, task_id: str, path: Path, *, stop_event=None, on_progress=None, on_phase=None):
from .bom_import_report import inspect_batch
return self._idle_quick_run_operation('inspect_bom_batch', task_id,
@@ -3,6 +3,7 @@
from contextlib import contextmanager
from dataclasses import asdict, dataclass, is_dataclass
import hashlib
import inspect
import json
import os
from pathlib import Path
@@ -119,8 +120,15 @@ def _save(path: Path, state: dict) -> None:
def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
queue_id: str | None = None) -> TaskQueueResult:
queue_id: str | None = None, runtime=None) -> TaskQueueResult:
"""Execute the frozen order; uncertain state stops before the next project."""
if runtime is None:
from .batch_runtime import BatchCadRuntime
with BatchCadRuntime(service._logging.root, 'task_queue', stop_event) as owned_runtime:
result = execute_task_queue(service, task_ids, stop_event=stop_event,
queue_id=queue_id, runtime=owned_runtime)
owned_runtime.result = result
return result
ids = tuple(task_ids)
if not ids or len(set(ids)) != len(ids):
raise TaskCenterError('task_queue_selection', '请选择不同的单工程任务。')
@@ -183,8 +191,13 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
expected = (str(progress.next_project_path), progress.next_old_part_number,
progress.next_new_part_number,
'part_label' if child.get_task(task_id).copy_part_number_to_value else 'preserve')
result = child.execute_quick_run_queue(task_id, expected_item=expected,
stop_event=stop_event)
execute = child.execute_quick_run_queue
parameters = inspect.signature(execute).parameters.values()
runtime_options = ({'runtime': runtime} if any(
parameter.name == 'runtime' or parameter.kind is inspect.Parameter.VAR_KEYWORD
for parameter in parameters) else {})
result = execute(task_id, expected_item=expected, stop_event=stop_event,
**runtime_options)
if child.has_interrupted_quick_run(task_id) or (
result.last_result is not None and result.last_result.state == 'batch_saved_unverified'
):
@@ -88,6 +88,7 @@ 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.cleanup_resources_button.clicked.connect(self._cleanup_batch_resources)
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)
@@ -285,15 +286,18 @@ class TrialTaskCenterWindow(QMainWindow):
def _update_gates(self):
busy = bool(self._workers) or self._loading
resources_pending = bool(self.service.pending_batch_resources())
self.run_panel.cleanup_resources_button.setVisible(resources_pending)
self.run_panel.cleanup_resources_button.setEnabled(resources_pending and not busy)
state = execution_state(self._context, busy=busy, dirty=self.plan_panel.table.dirty)
group_unsaved = self._group_has_unsaved_plans() if state.editable or state.new_round else False
context = self._context
self.run_panel.quick_run_button.setText(state.execute_text)
self.run_panel.quick_run_button.setEnabled(state.execute)
self.run_panel.quick_run_button.setEnabled(state.execute and not resources_pending)
self.run_panel.retry_button.setVisible(bool(context and context.phase == 'retry'))
self.run_panel.retry_button.setEnabled(state.retry)
self.run_panel.retry_button.setEnabled(state.retry and not resources_pending)
self.run_panel.recover_button.setVisible(bool(context and context.interrupted))
self.run_panel.recover_button.setEnabled(state.recover)
self.run_panel.recover_button.setEnabled(state.recover and not resources_pending)
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 group_unsaved)
self.run_panel.history_button.setVisible(bool(context and
@@ -305,6 +309,9 @@ class TrialTaskCenterWindow(QMainWindow):
rule_editable = state.editable and not group_unsaved
self.mapping_table.set_rules_editable(rule_editable)
self.plan_panel.set_plan_editable(state.editable, busy=busy)
if resources_pending:
self.plan_panel.collect_button.setEnabled(False)
self.plan_panel.import_bom_button.setEnabled(False)
self.add_mapping_button.setEnabled(rule_editable)
selected = self.mapping_table.current_rule_id() is not None
for button in (self.edit_mapping_button, self.delete_mapping_button,
@@ -331,7 +338,7 @@ class TrialTaskCenterWindow(QMainWindow):
and t.status is not TaskStatus.DELETED}
group_dirty = self.plan_panel.has_unsaved_plan(group_ids)
group_active = any(t.status in {TaskStatus.RUNNING, TaskStatus.PAUSED} for t in self._tasks if t.task_id in group_ids)
self.task_list.queue_button.setEnabled(grouped and not busy and not group_dirty and not bool(context.interrupted))
self.task_list.queue_button.setEnabled(grouped and not busy and not group_dirty and not bool(context.interrupted) and not resources_pending)
for button in (self.task_list.up_button, self.task_list.down_button):
button.setEnabled(grouped and not busy and not group_active
and self.task_list.sort.currentData() == 'execution'
@@ -342,7 +349,7 @@ class TrialTaskCenterWindow(QMainWindow):
if self._loading and not self._message:
self.run_panel.operator_band.setText('正在读取任务,可继续选择其他任务。')
if not busy:
self.run_panel.execution_status.setText('任务读取失败' if read_failed else
self.run_panel.execution_status.setText('资源待清理' if resources_pending else '任务读取失败' if read_failed else
'结果待核验' if context and context.interrupted else '空闲')
def _group_has_unsaved_plans(self):
@@ -573,6 +580,17 @@ class TrialTaskCenterWindow(QMainWindow):
self._set_operator_message(f"任务「{name}」{'已暂停' if result.paused else '已结束'}:已保存 {p.saved_items},失败 {p.failed_items},未命中 {p.no_match_items}。",
'warning' if result.paused or p.failed_items else 'success')
def _cleanup_batch_resources(self):
if not self.run_panel.cleanup_resources_button.isEnabled():
return
def done(pending):
self._set_operator_message(
'后台资源仍待清理,请保留诊断记录后重试。' if pending else '后台资源已释放,可以继续。',
'warning' if pending else 'success')
self._update_gates()
self._run_async(self.service.cleanup_batch_resources, done,
self.run_panel.cleanup_resources_button)
def _retry_failed(self):
if self.run_panel.retry_button.isEnabled():
task_id = self._task_id
@@ -4,6 +4,7 @@ import json
import re
ERROR_TEXT = {
"batch_resources_pending": "已核验的替换结果已保留。后台资源尚未释放,请使用“重新清理资源”后再开始下一批。",
"task_required": "请先选择任务。",
"directory_required": "请先选择工程目录。",
"discovery_root_locked": "旧目录已有执行记录,不能在同一任务中更换目录;请新建任务。",
@@ -25,6 +25,8 @@ class RunPanel(QWidget):
self.stop_queue_button = QPushButton('完成当前项后暂停', objectName='stopQueueButton')
self.retry_button = QPushButton('重试失败项', objectName='retryTaskItems')
self.recover_button = QPushButton('核验并恢复', objectName='recoverQuickRunButton')
self.cleanup_resources_button = QPushButton('重新清理资源', objectName='cleanupBatchResources')
self.cleanup_resources_button.setToolTip('只释放本程序拥有的后台资源,不执行工程替换。')
self.new_round_button = QPushButton('开始新一轮', objectName='startNewRoundButton')
self.history_button = QPushButton('查看轮次证据', objectName='roundHistoryButton')
self.copy_value_check = QCheckBox('Value 策略:替换后将 Part Label 写入 Value(逐行自定义优先)', objectName='copyPartNumberToValue')
@@ -37,7 +39,7 @@ class RunPanel(QWidget):
self.log_dialog = None
self.toggle_log_button.toggled.connect(self._toggle_log)
buttons = QHBoxLayout()
for button in (self.quick_run_button, self.retry_button, self.recover_button,
for button in (self.quick_run_button, self.retry_button, self.recover_button, self.cleanup_resources_button,
self.new_round_button, self.history_button, self.stop_queue_button):
buttons.addWidget(button)
buttons.addStretch()