diff --git a/src/dx_productivity/trial_task_center/quick_run.py b/src/dx_productivity/trial_task_center/quick_run.py index 0576f14..321f765 100644 --- a/src/dx_productivity/trial_task_center/quick_run.py +++ b/src/dx_productivity/trial_task_center/quick_run.py @@ -31,65 +31,9 @@ _BATCH_LOG_ROTATION_INTERVAL = 16 _MISSING_PROJECT_SHEET = ("__missing_project__", "0") -@dataclass(frozen=True, slots=True) -class QuickRunResult: - """The files an operator needs to run and diagnose one quick replacement pass.""" - - script_path: Path - command_path: Path - status_path: Path - log_path: Path - vbs_root_compatible: bool - - -@dataclass(frozen=True, slots=True) -class QuickRunStepResult: - """The correlated result produced by one automatic replacement pass.""" - - script_path: Path - command_path: Path - status_path: Path - log_path: Path - state: str - message: str - next_project_path: Path | None = None - next_old_part_number: str | None = None - next_new_part_number: str | None = None - next_schematic_name: str | None = None - next_sheet_number: str | None = None - progress: QuickRunProgress | None = None - - -@dataclass(frozen=True, slots=True) -class QuickRunProgress: - """Durable progress reconstructed from the correlated handoff files.""" - - completed_items: int - total_items: int - next_project_path: Path | None - next_old_part_number: str | None - next_new_part_number: str | None - completed_project_paths: tuple[Path, ...] - queue_complete: bool - no_match_items: int = 0 - project_summaries: tuple[tuple[Path, str], ...] = () - saved_items: int = 0 - next_schematic_name: str | None = None - next_sheet_number: str | None = None - page_addressed: bool = False - failed_items: int = 0 - failed_project_summaries: tuple[tuple[Path, str], ...] = () - - -@dataclass(frozen=True, slots=True) -class ProjectDiscovery: - sheets: tuple[tuple[str, str], ...] - matched_old_parts: dict[tuple[str, str], frozenset[str]] - components: tuple = () - - -# Preserve callers that injected the original discovery boundary. -_ProjectDiscovery = ProjectDiscovery +from .quick_run_protocol import (QuickRunResult, QuickRunStepResult, QuickRunProgress, + ProjectDiscovery, _ProjectDiscovery, _encode_vbs_field, _decode_vbs_field) +from .quick_run_snapshot import QuickRunSnapshot, read_snapshot @dataclass(slots=True) @@ -587,145 +531,27 @@ class QuickRunPreparer: progress, ) + def read_snapshot(self, task_id, projects, rules, *, copy_part_number_to_value=False, + read_control=None) -> QuickRunSnapshot: + """Read one consistent set of handoff evidence without changing it.""" + return read_snapshot(self, task_id, projects, rules, + copy_part_number_to_value=copy_part_number_to_value, read_control=read_control) + def has_interrupted(self, task_id: str) -> bool: - root = self._data_root / "quick-run" - if self.evidence_path(task_id) != root: - return False - if (root / "uncertain.flag").is_file(): - return True - try: - commands = _read_commands(root / "command.tsv") - statuses = _read_status_details(root / "status.tsv") - latest_states = {job_id: state for job_id, state, _, _ in statuses} - if any(state == BATCH_SAVED_UNVERIFIED_STATE for state in latest_states.values()): - return True - current = _next_unfinished_command(commands, statuses) - if current is None: - return False - final_state = next((entry[1] for entry in reversed(statuses) if entry[0] == current[1]), None) - if final_state == "awaiting_native_replace": - return True - return final_state == "hard_failure" and _recover_pre_mutation_hard_failures(root, commands, statuses) == statuses - except TaskCenterError: - return False + return self.read_snapshot(task_id, (), ()).interrupted - def current_phase( - self, - task_id: str, - projects: tuple[ProjectRecord, ...], - rules: tuple[RuleRecord, ...], - *, - copy_part_number_to_value: bool = False, - ) -> str: - """Read the matching local handoff queue without starting DxDesigner.""" - selected_projects = _selected_projects(projects) - enabled_rules = tuple(rule for rule in rules if rule.enabled) - if not selected_projects or not enabled_rules: - return "selection" - try: - self._validate_fields(selected_projects, enabled_rules) - root = self.evidence_path(task_id) or self._data_root / "quick-run" - command_path = root / "command.tsv" - status_path = root / "status.tsv" - if not command_path.is_file() or not status_path.is_file(): - return "selection" - commands = _read_commands(command_path) - command_project_keys = {_path_key(command[2]) for command in commands} - queued_projects = tuple( - project for project in selected_projects - if _path_key(project.path) in command_project_keys - ) - if not _value_mode_matches_option(_queue_value_mode(command_path), copy_part_number_to_value): - return "selection" - command_task_ids = {command_task_id for command_task_id, *_ in commands} - if command_task_ids != {task_id} or not _queue_matches_inputs( - command_path, commands, queued_projects, enabled_rules - ): - return "selection" - statuses = {job_id: state for job_id, state, _, _ in _read_status_details(status_path)} - except TaskCenterError: - return "selection" - relevant_states = tuple(statuses.get(job_id, "") for _, job_id, *_ in commands) - if any(state == "hard_failure" for state in relevant_states): - return "selection" - if relevant_states and all(state in TERMINAL_STATES for state in relevant_states): - return "complete" - return "selection" + def current_phase(self, task_id, projects, rules, *, copy_part_number_to_value=False, + read_control=None) -> str: + return self.read_snapshot(task_id, projects, rules, + copy_part_number_to_value=copy_part_number_to_value, read_control=read_control).phase - def progress( - self, - task_id: str, - projects: tuple[ProjectRecord, ...], - rules: tuple[RuleRecord, ...], - *, - copy_part_number_to_value: bool = False, - ) -> QuickRunProgress: - """Reconstruct task progress without executing or modifying DxDesigner.""" - all_selected_projects = _selected_projects(projects) - selected_projects = _queue_projects(projects) - enabled_rules = tuple(rule for rule in rules if rule.enabled) - expected = tuple( - (str(project.path), rule.old_part_number, rule.new_part_number) - for project in selected_projects - for rule in enabled_rules - ) - fallback = expected[0] if expected else (None, None, None) - empty = QuickRunProgress( - completed_items=0, - total_items=len(expected), - next_project_path=_optional_path(fallback[0]), - next_old_part_number=fallback[1], - next_new_part_number=fallback[2], - completed_project_paths=(), - queue_complete=False, - ) - root = self.evidence_path(task_id) or self._data_root / "quick-run" - command_path = root / "command.tsv" - status_path = root / "status.tsv" - if not command_path.is_file() or not status_path.is_file(): - return empty - try: - commands = _read_commands(command_path) - details = _read_status_details(status_path) - if not _value_mode_matches_option(_queue_value_mode(command_path), copy_part_number_to_value): - return empty - command_project_paths = {command[2] for command in commands} - queued_projects = tuple( - project for project in all_selected_projects - if str(project.path) in command_project_paths - ) - if {command_task_id for command_task_id, *_ in commands} != {task_id} or not _queue_matches_inputs( - command_path, commands, queued_projects, enabled_rules - ): - return empty - sheets = _read_command_sheet_targets(command_path) - except TaskCenterError: - return empty - return _progress_from_queue(queued_projects, commands, details, sheets) + def progress(self, task_id, projects, rules, *, copy_part_number_to_value=False, + read_control=None) -> QuickRunProgress: + return self.read_snapshot(task_id, projects, rules, + copy_part_number_to_value=copy_part_number_to_value, read_control=read_control).progress def evidence_path(self, task_id: str, project_path: Path | None = None) -> Path | None: - """Return the current or archived handoff directory bound to the task.""" - current = self._data_root / "quick-run" - history = self._data_root / "quick-run-history" - archived = tuple(sorted((path for path in history.glob("obsolete-*") if path.is_dir()), reverse=True)) - for root in (current, *archived): - command_path = root / "command.tsv" - status_path = root / "status.tsv" - if not command_path.is_file() or not status_path.is_file(): - continue - try: - commands = _read_commands(command_path) - except TaskCenterError: - continue - matching = tuple(command for command in commands if command[0] == task_id) - if not matching or len(matching) != len(commands): - continue - if project_path is not None and not any( - _path_key(command[2]) == _path_key(project_path) for command in matching - ): - continue - return root - return None + return read_snapshot(self, task_id, (), (), project_path=project_path).evidence_path def _resumable_handoff( self, @@ -1786,41 +1612,6 @@ def _write_atomic_queue_text(path: Path, text: str, code: str, message: str) -> raise TaskCenterError(code, message) from error -def _encode_vbs_field(value: str) -> str: - encoded: list[str] = [] - for character in str(value): - code = ord(character) - if character != "%" and 32 <= code <= 126: - encoded.append(character) - continue - units = character.encode("utf-16-le") - encoded.extend( - f"%{int.from_bytes(units[index:index + 2], 'little'):04X}" - for index in range(0, len(units), 2) - ) - return "".join(encoded) - - -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): - if value[index] == "%" and index + 4 < len(value): - token = value[index + 1:index + 5] - if all(character in "0123456789abcdefABCDEF" for character in token): - characters.append(chr(int(token, 16))) - index += 5 - continue - characters.append(value[index]) - index += 1 - try: - return "".join(characters).encode("utf-16-le", errors="surrogatepass").decode("utf-16-le") - except UnicodeError as error: - raise ValueError("VBS field contains malformed UTF-16") from error - - def _path_key(path: str | Path) -> str: return os.path.normcase(os.path.abspath(str(path))) diff --git a/src/dx_productivity/trial_task_center/quick_run_protocol.py b/src/dx_productivity/trial_task_center/quick_run_protocol.py new file mode 100644 index 0000000..61d5ed7 --- /dev/null +++ b/src/dx_productivity/trial_task_center/quick_run_protocol.py @@ -0,0 +1,101 @@ +"""Immutable execution protocol models and VBS field codec.""" +from __future__ import annotations +from dataclasses import dataclass +from pathlib import Path + +@dataclass(frozen=True, slots=True) +class QuickRunResult: + """The files an operator needs to run and diagnose one quick replacement pass.""" + + script_path: Path + command_path: Path + status_path: Path + log_path: Path + vbs_root_compatible: bool + + +@dataclass(frozen=True, slots=True) +class QuickRunStepResult: + """The correlated result produced by one automatic replacement pass.""" + + script_path: Path + command_path: Path + status_path: Path + log_path: Path + state: str + message: str + next_project_path: Path | None = None + next_old_part_number: str | None = None + next_new_part_number: str | None = None + next_schematic_name: str | None = None + next_sheet_number: str | None = None + progress: QuickRunProgress | None = None + + +@dataclass(frozen=True, slots=True) +class QuickRunProgress: + """Durable progress reconstructed from the correlated handoff files.""" + + completed_items: int + total_items: int + next_project_path: Path | None + next_old_part_number: str | None + next_new_part_number: str | None + completed_project_paths: tuple[Path, ...] + queue_complete: bool + no_match_items: int = 0 + project_summaries: tuple[tuple[Path, str], ...] = () + saved_items: int = 0 + next_schematic_name: str | None = None + next_sheet_number: str | None = None + page_addressed: bool = False + failed_items: int = 0 + failed_project_summaries: tuple[tuple[Path, str], ...] = () + + +@dataclass(frozen=True, slots=True) +class ProjectDiscovery: + sheets: tuple[tuple[str, str], ...] + matched_old_parts: dict[tuple[str, str], frozenset[str]] + components: tuple = () + + +# Preserve callers that injected the original discovery boundary. +_ProjectDiscovery = ProjectDiscovery + + +def _encode_vbs_field(value: str) -> str: + encoded: list[str] = [] + for character in str(value): + code = ord(character) + if character != "%" and 32 <= code <= 126: + encoded.append(character) + continue + units = character.encode("utf-16-le") + encoded.extend( + f"%{int.from_bytes(units[index:index + 2], 'little'):04X}" + for index in range(0, len(units), 2) + ) + return "".join(encoded) + + +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): + if value[index] == "%" and index + 4 < len(value): + token = value[index + 1:index + 5] + if all(character in "0123456789abcdefABCDEF" for character in token): + characters.append(chr(int(token, 16))) + index += 5 + continue + characters.append(value[index]) + index += 1 + try: + return "".join(characters).encode("utf-16-le", errors="surrogatepass").decode("utf-16-le") + except UnicodeError as error: + raise ValueError("VBS field contains malformed UTF-16") from error + + diff --git a/src/dx_productivity/trial_task_center/quick_run_snapshot.py b/src/dx_productivity/trial_task_center/quick_run_snapshot.py new file mode 100644 index 0000000..878a734 --- /dev/null +++ b/src/dx_productivity/trial_task_center/quick_run_snapshot.py @@ -0,0 +1,131 @@ +"""Read-only execution view reconstructed from one cached set of handoff files.""" +from __future__ import annotations +from dataclasses import dataclass +from pathlib import Path +from .errors import TaskCenterError +from .quick_run_protocol import QuickRunProgress + + +@dataclass(frozen=True, slots=True) +class QuickRunSnapshot: + progress: QuickRunProgress + has_evidence: bool + evidence_path: Path | None + interrupted: bool + phase: str + + +class _ReadFiles: + def __init__(self, control): + self.control = control + self.texts = {} + + def checkpoint(self): + if self.control is not None: + self.control.checkpoint() + + def path(self, path): + return _CachedPath(Path(path), self) + + def read(self, path): + self.checkpoint() + if path not in self.texts: + chunks = [] + with path.open('r', encoding='utf-8-sig') as source: + while True: + self.checkpoint() + chunk = source.read(65536) + self.checkpoint() + if not chunk: + break + chunks.append(chunk) + self.texts[path] = ''.join(chunks) + return self.texts[path] + + +class _CachedPath: + """Path-shaped parser input: every parser sees the same immutable text.""" + def __init__(self, path, files): + self.path, self.files = path, files + + def read_text(self, **kwargs): + return self.files.read(self.path) + + def with_name(self, name): + return self.files.path(self.path.with_name(name)) + + def exists(self): + self.files.checkpoint() + return self.path.exists() + + +def read_snapshot(preparer, task_id, projects, rules, *, copy_part_number_to_value=False, + read_control=None, project_path=None): + # Import lazily to preserve the historical quick_run private parser boundaries. + from . import quick_run as api + files = _ReadFiles(read_control) + files.checkpoint() + selected = api._selected_projects(projects) + queued = api._queue_projects(projects) + enabled = tuple(rule for rule in rules if rule.enabled) + expected = tuple((str(project.path), rule.old_part_number, rule.new_part_number) + for project in queued for rule in enabled) + first = expected[0] if expected else (None, None, None) + progress = QuickRunProgress(0, len(expected), api._optional_path(first[0]), first[1], first[2], (), False) + current = preparer._data_root / 'quick-run' + history = preparer._data_root / 'quick-run-history' + root = None + commands = () + # Avoid enumerating history when the active handoff already matches. + def candidates(): + yield current + files.checkpoint() + yield from sorted((path for path in history.glob('obsolete-*') if path.is_dir()), reverse=True) + for candidate in candidates(): + files.checkpoint() + command = candidate / 'command.tsv' + if not command.is_file() or not (candidate / 'status.tsv').is_file(): + continue + try: + parsed = api._read_commands(files.path(command)) + except TaskCenterError: + continue + if not parsed or {row[0] for row in parsed} != {task_id}: + continue + if project_path is not None and not any(api._path_key(row[2]) == api._path_key(project_path) for row in parsed): + continue + root, commands = candidate, parsed + break + if root is None: + files.checkpoint() + return QuickRunSnapshot(progress, False, None, False, 'selection') + interrupted = root == current and (root / 'uncertain.flag').is_file() + phase = 'selection' + try: + details = api._read_status_details(files.path(root / 'status.tsv')) + files.checkpoint() + if root == current: + latest = {job_id: state for job_id, state, _, _ in details} + interrupted = interrupted or any(state == api.BATCH_SAVED_UNVERIFIED_STATE for state in latest.values()) + unfinished = api._next_unfinished_command(commands, details) + if unfinished is not None: + final = latest.get(unfinished[1]) + interrupted = interrupted or final == 'awaiting_native_replace' + if final == 'hard_failure': + interrupted = interrupted or api._recover_pre_mutation_hard_failures(root, commands, details) == details + if selected and enabled: + preparer._validate_fields(selected, enabled) + command_path = files.path(root / 'command.tsv') + queued_projects = tuple(project for project in selected + if str(project.path) in {command[2] for command in commands}) + if (api._value_mode_matches_option(api._queue_value_mode(command_path), copy_part_number_to_value) + and api._queue_matches_inputs(command_path, commands, queued_projects, enabled)): + sheets = api._read_command_sheet_targets(command_path) + files.checkpoint() + progress = api._progress_from_queue(queued_projects, commands, details, sheets) + if progress.queue_complete: + phase = 'retry' if progress.failed_items else 'complete' + except TaskCenterError: + pass + files.checkpoint() + return QuickRunSnapshot(progress, True, root, interrupted, phase) diff --git a/tests/trial_task_center/test_quick_run_snapshot.py b/tests/trial_task_center/test_quick_run_snapshot.py new file mode 100644 index 0000000..893238a --- /dev/null +++ b/tests/trial_task_center/test_quick_run_snapshot.py @@ -0,0 +1,78 @@ +from pathlib import Path +import pytest +from dx_productivity.trial_task_center.models import ProjectRecord, ProjectStatus, RuleRecord +from dx_productivity.trial_task_center.quick_run import QuickRunPreparer + + +def fixture_queue(tmp_path): + script = tmp_path / 'runtime.vbs' + script.write_text("' fixture", encoding='ascii') + preparer = QuickRunPreparer(tmp_path, script_source=script, run_token_factory=lambda: 'snapshot') + project = ProjectRecord('project', 'task', 'One', Path('C:/one.prj'), Path('C:/'), True, True, ProjectStatus.PENDING, 0) + rule = RuleRecord('rule', 'task', 0, 'OLD', 'NEW', True) + handoff = preparer.prepare('task', (project,), (rule,)) + job = handoff.command_path.read_text(encoding='utf-8').splitlines()[1].split('\t')[1] + return preparer, project, rule, handoff, job + + +def test_snapshot_reads_each_file_once_and_uses_same_status(tmp_path, monkeypatch): + preparer, project, rule, handoff, job = fixture_queue(tmp_path) + handoff.status_path.write_text(f'job_id\tstate\tcode\tmessage\n{job}\tbatch_saved_unverified\t\tverify\n', encoding='utf-8') + opens = [] + original = Path.open + def tracked(path, *args, **kwargs): + if path.parent == handoff.command_path.parent: + opens.append(path.name) + return original(path, *args, **kwargs) + monkeypatch.setattr(Path, 'open', tracked) + snapshot = preparer.read_snapshot('task', (project,), (rule,)) + assert opens.count('command.tsv') == opens.count('status.tsv') == 1 + assert snapshot.evidence_path == handoff.command_path.parent + assert snapshot.has_evidence and snapshot.interrupted + assert snapshot.progress.saved_items == 0 + assert snapshot.progress.failed_items == 1 + + +def test_snapshot_cancellation_stops_before_next_file_and_never_writes(tmp_path, monkeypatch): + preparer, project, rule, handoff, job = fixture_queue(tmp_path) + original = Path.open + class Cancelled(Exception): + pass + class Control: + cancelled = False + def checkpoint(self): + if self.cancelled: + raise Cancelled + control = Control() + opened = [] + def tracked(path, *args, **kwargs): + opened.append(path.name) + result = original(path, *args, **kwargs) + if path == handoff.command_path: + control.cancelled = True + return result + monkeypatch.setattr(Path, 'open', tracked) + with pytest.raises(Cancelled): + preparer.read_snapshot('task', (project,), (rule,), read_control=control) + assert opened == ['command.tsv'] + + +@pytest.mark.parametrize('state', ['alien_state', 'awaiting_native_replace']) +def test_snapshot_unknown_states_do_not_complete_or_save(tmp_path, state): + preparer, project, rule, handoff, job = fixture_queue(tmp_path) + text = f'job_id\tstate\tcode\tmessage\n{job}\t{state}\t\tunknown\n' + handoff.status_path.write_text(text, encoding='utf-8') + snapshot = preparer.read_snapshot('task', (project,), (rule,)) + assert not snapshot.progress.queue_complete + assert snapshot.progress.saved_items == 0 + assert snapshot.interrupted == (state == 'awaiting_native_replace') + assert handoff.status_path.read_text(encoding='utf-8') == text + + +def test_snapshot_corruption_retains_evidence_without_claiming_progress(tmp_path): + preparer, project, rule, handoff, job = fixture_queue(tmp_path) + handoff.status_path.write_text('corrupt', encoding='utf-8') + snapshot = preparer.read_snapshot('task', (project,), (rule,)) + assert snapshot.has_evidence + assert snapshot.progress.completed_items == 0 + assert snapshot.phase == 'selection'