feat: record execution timings and speed up batch queues

This commit is contained in:
阿白叔 committed 2026-10-15 09:10:26 +08:00
1 parent 20d8b81a34
commit 0225787084
12 files changed
+509 -56

No files matched your search

+53 -27
View File
@@ -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,
@@ -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)
@@ -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:
@@ -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)
@@ -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
@@ -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}"
@@ -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: