fix: use extended filesystem paths for deep queue evidence
This commit is contained in:
1 parent
3c4e6e7e37
commit
c787ef325b
9 files changed
+208
-87
No files matched your search
@@ -5,9 +5,11 @@ import os
|
||||
from pathlib import Path
|
||||
|
||||
from .logging_setup import LoggingContext, append_task_event, configure_logging
|
||||
from .path_access import internal_path
|
||||
|
||||
|
||||
def _append_line(path, line):
|
||||
path = internal_path(path)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with path.open('a', encoding='utf-8', newline='\n') as stream:
|
||||
stream.write(line + '\n')
|
||||
|
||||
@@ -305,13 +305,13 @@ class BatchCadRuntime:
|
||||
def recover_native_failure(self, project, evidence, reason):
|
||||
"""One read-only recovery, based on durable source and worker proof."""
|
||||
from .batch_attempt import can_retry_attempt
|
||||
project, evidence = Path(project).resolve(), Path(evidence).resolve()
|
||||
project, evidence = canonical_path(project), canonical_path(evidence)
|
||||
key = str(project).casefold()
|
||||
if (self._retry_counts.get(key) or self.record['state'] == 'blocked'
|
||||
or self.stop_event is not None and self.stop_event.is_set()):
|
||||
return False
|
||||
try:
|
||||
proof = json.loads((evidence / 'native-retry-proof.json').read_text(encoding='utf-8'))
|
||||
proof = json.loads(internal_path(evidence / 'native-retry-proof.json').read_text(encoding='utf-8'))
|
||||
sources = proof['source_hashes']
|
||||
operation = self.record['native_operations'][str(evidence)]
|
||||
if (proof['version'] != 1 or proof['native_read_only'] is not True
|
||||
@@ -321,8 +321,8 @@ class BatchCadRuntime:
|
||||
or proof['workers_closed'] is not True or proof['project_path'] != str(project)
|
||||
or proof['evidence_root'] != str(evidence) or str(project) not in sources
|
||||
or len(sources) != 2
|
||||
or not all(Path(name).resolve().is_relative_to(project.parent) for name in sources)
|
||||
or not all(hashlib.sha256(Path(name).read_bytes()).hexdigest() == digest
|
||||
or not all(canonical_path(name).is_relative_to(project.parent) for name in sources)
|
||||
or not all(hashlib.sha256(internal_path(name).read_bytes()).hexdigest() == digest
|
||||
for name, digest in sources.items())
|
||||
or not all(can_retry_attempt(path, record)
|
||||
for path, record in self._project_attempts.get(key, ()))):
|
||||
|
||||
@@ -18,6 +18,7 @@ import traceback
|
||||
from typing import Any, Mapping
|
||||
|
||||
from .errors import TaskCenterError
|
||||
from .path_access import internal_path
|
||||
from .retention import rotate_text_log
|
||||
|
||||
|
||||
@@ -155,11 +156,11 @@ def append_task_event(
|
||||
encoded = json.dumps(event, ensure_ascii=False, separators=(",", ":"), allow_nan=False) + "\n"
|
||||
try:
|
||||
rotate_text_log(
|
||||
path,
|
||||
internal_path(path),
|
||||
max_bytes=_MAX_EVENT_LOG_BYTES,
|
||||
backup_count=_EVENT_BACKUP_COUNT,
|
||||
)
|
||||
with path.open("a", encoding="utf-8", newline="\n") as handle:
|
||||
with internal_path(path).open("a", encoding="utf-8", newline="\n") as handle:
|
||||
handle.write(encoded)
|
||||
handle.flush()
|
||||
os.fsync(handle.fileno())
|
||||
@@ -187,7 +188,7 @@ def append_task_event(
|
||||
|
||||
def _event_file_stamp(path):
|
||||
try:
|
||||
info = path.stat()
|
||||
info = internal_path(path).stat()
|
||||
return info.st_dev, info.st_ino, info.st_size, info.st_mtime_ns, info.st_ctime_ns
|
||||
except OSError:
|
||||
return None
|
||||
@@ -230,15 +231,15 @@ def _task_directory(context: LoggingContext, task_id: str) -> Path:
|
||||
if not task_id or Path(task_id).name != task_id or task_id in {".", ".."}:
|
||||
raise TaskCenterError("task_id", "task event requires a safe task identifier")
|
||||
path = context.root / "tasks" / task_id
|
||||
if not path.is_dir():
|
||||
path.mkdir(parents=True, exist_ok=True)
|
||||
if not internal_path(path).is_dir():
|
||||
internal_path(path).mkdir(parents=True, exist_ok=True)
|
||||
return path
|
||||
|
||||
|
||||
def _next_event_sequence(path: Path) -> int:
|
||||
try:
|
||||
for candidate in (path, path.with_name(f"{path.name}.1")):
|
||||
if not candidate.exists():
|
||||
if not internal_path(candidate).exists():
|
||||
continue
|
||||
lines = _tail_utf8_lines(candidate, 1)
|
||||
if lines:
|
||||
@@ -252,7 +253,7 @@ def _next_event_sequence(path: Path) -> int:
|
||||
def _tail_utf8_lines(path: Path, limit: int) -> tuple[str, ...]:
|
||||
if limit < 1:
|
||||
return ()
|
||||
with Path(path).open("rb") as handle:
|
||||
with internal_path(Path(path)).open("rb") as handle:
|
||||
handle.seek(0, os.SEEK_END)
|
||||
cursor = handle.tell()
|
||||
chunks = []
|
||||
|
||||
@@ -20,6 +20,7 @@ from typing import Protocol
|
||||
from uuid import uuid4
|
||||
|
||||
from .errors import TaskCenterError
|
||||
from .path_access import internal_path
|
||||
from .models import ProjectRecord, ProjectStatus, RuleRecord
|
||||
from .retention import maintain_quick_run_storage, rotate_text_log
|
||||
from .worker_runtime import copy_worker_script
|
||||
@@ -112,22 +113,22 @@ class QuickRunPreparer:
|
||||
self._validate_fields(selected_projects, enabled_rules)
|
||||
_validate_target_scope(selected_projects, enabled_rules, sheet_targets)
|
||||
run_token = _safe_run_token(self._run_token_factory())
|
||||
maintain_quick_run_storage(self._data_root)
|
||||
maintain_quick_run_storage(_io_path(self._data_root))
|
||||
|
||||
root = self._data_root / "quick-run"
|
||||
script_path = root / "QuickPartReplace.vbs"
|
||||
command_path = root / "command.tsv"
|
||||
status_path = root / "status.tsv"
|
||||
log_path = root / "quick-part-replace.log"
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
_io_path(root).mkdir(parents=True, exist_ok=True)
|
||||
_assert_no_pending_status(status_path, log_path)
|
||||
copy_worker_script(source, script_path)
|
||||
if sheet_targets is not None:
|
||||
manifest_path = root / "sheets.tsv"
|
||||
manifest_path.write_text(_sheet_manifest_text(selected_projects, sheet_targets), encoding="utf-8", newline="")
|
||||
_io_path(manifest_path).write_text(_sheet_manifest_text(selected_projects, sheet_targets), encoding="utf-8", newline="")
|
||||
else:
|
||||
(root / "sheets.tsv").unlink(missing_ok=True)
|
||||
command_path.write_text(
|
||||
(_io_path(root / "sheets.tsv")).unlink(missing_ok=True)
|
||||
_io_path(command_path).write_text(
|
||||
_command_text(
|
||||
task_id,
|
||||
run_token,
|
||||
@@ -144,7 +145,7 @@ class QuickRunPreparer:
|
||||
discovery_matches,
|
||||
discovery_failures,
|
||||
)
|
||||
status_path.write_text(
|
||||
_io_path(status_path).write_text(
|
||||
initial_status,
|
||||
encoding="utf-8",
|
||||
newline="\n",
|
||||
@@ -157,7 +158,7 @@ class QuickRunPreparer:
|
||||
root = 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():
|
||||
if not _io_path(command_path).is_file() or not _io_path(status_path).is_file():
|
||||
return None
|
||||
commands = _read_commands(command_path)
|
||||
if {command_task_id for command_task_id, *_ in commands} != {task_id}:
|
||||
@@ -220,7 +221,7 @@ class QuickRunPreparer:
|
||||
if discovery_matches is not None:
|
||||
discovery_matches[project_key] = {_MISSING_PROJECT_SHEET: frozenset()}
|
||||
except TaskCenterError:
|
||||
if project.path.exists():
|
||||
if _io_path(project.path).exists():
|
||||
raise
|
||||
project_key = _path_key(project.path)
|
||||
targets = (_MISSING_PROJECT_SHEET,)
|
||||
@@ -277,7 +278,7 @@ 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()
|
||||
command_lines = _io_path(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', 'target_cell'} & set(command_lines[0].split('\t')) else {})
|
||||
@@ -334,7 +335,7 @@ class QuickRunPreparer:
|
||||
) -> QuickRunStepResult:
|
||||
"""Prepare or resume a queue, then execute one replacement rule end to end."""
|
||||
uncertain_path = self._data_root / "quick-run" / "uncertain.flag"
|
||||
if uncertain_path.exists():
|
||||
if _io_path(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")
|
||||
if self._process_runner is _run_process and not batch_mode:
|
||||
from .single_step import prepare_private_single_step
|
||||
@@ -342,7 +343,7 @@ class QuickRunPreparer:
|
||||
**({'runtime': runtime} if runtime is not None else {}))
|
||||
batch_mode = True
|
||||
current_root = self._data_root / "quick-run"
|
||||
if batch_session is None and 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 (_io_path(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()):
|
||||
@@ -406,9 +407,9 @@ class QuickRunPreparer:
|
||||
if batch_mode:
|
||||
if batch_session is not None:
|
||||
current_command_stamp = _write_current_command(batch_session, selected_command)
|
||||
batch_request.write_text(selected_command[1], encoding="ascii")
|
||||
_io_path(batch_request).write_text(selected_command[1], encoding="ascii")
|
||||
else:
|
||||
batch_request.unlink(missing_ok=True)
|
||||
_io_path(batch_request).unlink(missing_ok=True)
|
||||
from .worker_monitor import WorkerMonitorError
|
||||
|
||||
self.invalidate_discovery(Path(selected_command[2]))
|
||||
@@ -540,7 +541,7 @@ class QuickRunPreparer:
|
||||
raise TaskCenterError("quick_run_execution", f"unexpected quick-run state: {state}")
|
||||
if batch_mode and state == "saved_ok":
|
||||
try:
|
||||
handoff.command_path.with_name("current-state.tsv").unlink(missing_ok=True)
|
||||
_io_path(handoff.command_path.with_name("current-state.tsv")).unlink(missing_ok=True)
|
||||
except OSError as error:
|
||||
_append_log(
|
||||
handoff.log_path,
|
||||
@@ -612,7 +613,7 @@ class QuickRunPreparer:
|
||||
root = 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():
|
||||
if not _io_path(command_path).is_file() or not _io_path(status_path).is_file():
|
||||
return None
|
||||
try:
|
||||
commands = _read_commands(command_path)
|
||||
@@ -634,7 +635,7 @@ class QuickRunPreparer:
|
||||
_archive_obsolete_handoff(self._data_root, root)
|
||||
return None
|
||||
if _queue_value_mode(command_path) != value_mode:
|
||||
if statuses or any(root.glob("snapshot-*")) or _queue_has_mutation_evidence(root):
|
||||
if statuses or any(_io_path(root).glob("snapshot-*")) or _queue_has_mutation_evidence(root):
|
||||
raise TaskCenterError("quick_run_pending", "recorded Value policy differs; reconcile the old queue before creating a new task")
|
||||
_archive_obsolete_handoff(self._data_root, root)
|
||||
return None
|
||||
@@ -772,7 +773,7 @@ class QuickRunPreparer:
|
||||
return self._data_root
|
||||
|
||||
def _required_script_source(self) -> Path:
|
||||
if not self._script_source.is_file():
|
||||
if not _io_path(self._script_source).is_file():
|
||||
raise TaskCenterError("quick_run_script_missing", "QuickPartReplace.vbs runtime resource is missing")
|
||||
return self._script_source
|
||||
|
||||
@@ -1074,10 +1075,10 @@ def _assert_no_pending_status(status_path: Path, log_path: Path) -> None:
|
||||
|
||||
|
||||
def _read_status(status_path: Path) -> tuple[tuple[str, str], ...]:
|
||||
if not status_path.exists():
|
||||
if not _io_path(status_path).exists():
|
||||
return ()
|
||||
try:
|
||||
lines = status_path.read_text(encoding="utf-8-sig").splitlines()
|
||||
lines = _io_path(status_path).read_text(encoding="utf-8-sig").splitlines()
|
||||
except (OSError, UnicodeError) as error:
|
||||
raise TaskCenterError("quick_run_status", "cannot read quick-run status") from error
|
||||
if not lines or lines[0].split("\t") != ["job_id", "state", "code", "message"]:
|
||||
@@ -1098,17 +1099,17 @@ def _read_status(status_path: Path) -> tuple[tuple[str, str], ...]:
|
||||
|
||||
|
||||
def _append_log(log_path: Path, entry: str, *, check_rotation: bool = True) -> None:
|
||||
if not log_path.parent.is_dir():
|
||||
log_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
if not _io_path(log_path.parent).is_dir():
|
||||
_io_path(log_path.parent).mkdir(parents=True, exist_ok=True)
|
||||
if check_rotation:
|
||||
rotate_text_log(log_path)
|
||||
with log_path.open("a", encoding="utf-8", newline="\n") as handle:
|
||||
rotate_text_log(_io_path(log_path))
|
||||
with _io_path(log_path).open("a", encoding="utf-8", newline="\n") as handle:
|
||||
handle.write(entry + "\n")
|
||||
|
||||
|
||||
def _write_uncertain_flag(path: Path, reason: str = "manual_reconciliation_required") -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with path.open("w", encoding="utf-8", newline="\n") as handle:
|
||||
_io_path(path.parent).mkdir(parents=True, exist_ok=True)
|
||||
with _io_path(path).open("w", encoding="utf-8", newline="\n") as handle:
|
||||
handle.write(f"reason={_log_text(reason)}; manual reconciliation required\n")
|
||||
handle.flush()
|
||||
os.fsync(handle.fileno())
|
||||
@@ -1120,14 +1121,14 @@ def _states_are_complete(statuses: tuple[tuple[str, str, str, str], ...]) -> boo
|
||||
|
||||
|
||||
def _queue_has_mutation_evidence(root: Path) -> bool:
|
||||
if (root / "uncertain.flag").exists():
|
||||
if (_io_path(root / "uncertain.flag")).exists():
|
||||
return True
|
||||
for report_path in root.glob("snapshot-*.tsv.native.json"):
|
||||
for report_path in _io_path(root).glob("snapshot-*.tsv.native.json"):
|
||||
rollback_marker = Path(str(report_path)[:-len(".json")] + ".rolled-back")
|
||||
if rollback_marker.is_file():
|
||||
if _io_path(rollback_marker).is_file():
|
||||
continue
|
||||
try:
|
||||
report = json.loads(report_path.read_text(encoding="utf-8"))
|
||||
report = json.loads(_io_path(report_path).read_text(encoding="utf-8"))
|
||||
except (OSError, UnicodeError, json.JSONDecodeError):
|
||||
return True
|
||||
if report.get("ok") is True or report.get("stage") in {"native_replace_started", "native_replace_applied", "pin_promotion_started", "native_replace_verified"}:
|
||||
@@ -1140,12 +1141,12 @@ def _rollback_marker_verified(root: Path, job_id: str) -> bool:
|
||||
snapshot = root / f"snapshot-{job_id}.tsv"
|
||||
report_path = root / f"snapshot-{job_id}.tsv.native.json"
|
||||
try:
|
||||
report = json.loads(report_path.read_text(encoding="utf-8"))
|
||||
report = json.loads(_io_path(report_path).read_text(encoding="utf-8"))
|
||||
return (
|
||||
snapshot.is_file()
|
||||
_io_path(snapshot).is_file()
|
||||
and isinstance(report, dict)
|
||||
and report.get("stage") in {"native_replace_started", "native_replace_applied", "pin_promotion_started", "native_replace_verified"}
|
||||
and marker.read_text(encoding="utf-8-sig").strip() == "native replacement rollback verified"
|
||||
and _io_path(marker).read_text(encoding="utf-8-sig").strip() == "native replacement rollback verified"
|
||||
)
|
||||
except (OSError, UnicodeError, json.JSONDecodeError):
|
||||
return False
|
||||
@@ -1156,7 +1157,7 @@ def _recover_pre_mutation_hard_failures(
|
||||
commands: tuple[tuple[str, str, str, str, str], ...],
|
||||
statuses: tuple[tuple[str, str, str, str], ...],
|
||||
) -> tuple[tuple[str, str, str, str], ...]:
|
||||
if (root / "uncertain.flag").exists():
|
||||
if (_io_path(root / "uncertain.flag")).exists():
|
||||
return statuses
|
||||
command_ids = {job_id for _, job_id, *_ in commands}
|
||||
final_states = {job_id: state for job_id, state, _, _ in statuses}
|
||||
@@ -1176,7 +1177,7 @@ def _recover_pre_mutation_hard_failures(
|
||||
try:
|
||||
safe_job_id = _safe_run_token(job_id)
|
||||
report_path = root / f"snapshot-{safe_job_id}.tsv.native.json"
|
||||
report = json.loads(report_path.read_text(encoding="utf-8"))
|
||||
report = json.loads(_io_path(report_path).read_text(encoding="utf-8"))
|
||||
except (TaskCenterError, OSError, UnicodeError, json.JSONDecodeError):
|
||||
continue
|
||||
if (
|
||||
@@ -1204,26 +1205,26 @@ def _write_status_details(path: Path, statuses: tuple[tuple[str, str, str, str],
|
||||
text = "job_id\tstate\tcode\tmessage\r\n"
|
||||
text += "".join("\t".join(_encode_vbs_field(field) for field in entry) + "\r\n" for entry in statuses)
|
||||
try:
|
||||
temporary.write_text(text, encoding="utf-8", newline="")
|
||||
os.replace(temporary, path)
|
||||
_io_path(temporary).write_text(text, encoding="utf-8", newline="")
|
||||
os.replace(_io_path(temporary), _io_path(path))
|
||||
except OSError as error:
|
||||
temporary.unlink(missing_ok=True)
|
||||
_io_path(temporary).unlink(missing_ok=True)
|
||||
raise TaskCenterError("quick_run_status", "cannot recover pre-mutation quick-run status") from error
|
||||
|
||||
|
||||
def _archive_obsolete_handoff(data_root: Path, root: Path) -> Path:
|
||||
timestamp = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S-%f")
|
||||
destination = data_root / "quick-run-history" / f"obsolete-{timestamp}-{uuid4().hex[:8]}"
|
||||
destination.mkdir(parents=True, exist_ok=False)
|
||||
for entry in tuple(root.iterdir()):
|
||||
shutil.move(str(entry), destination / entry.name)
|
||||
_io_path(destination).mkdir(parents=True, exist_ok=False)
|
||||
for entry in tuple(_io_path(root).iterdir()):
|
||||
shutil.move(str(_io_path(entry)), _io_path(destination / entry.name))
|
||||
_append_log(destination / "quick-part-replace.log", "quick_run_obsolete_queue_archived")
|
||||
return destination
|
||||
|
||||
|
||||
def _read_commands(path: Path) -> tuple[tuple[str, str, str, str, str], ...]:
|
||||
try:
|
||||
lines = path.read_text(encoding="utf-8-sig").splitlines()
|
||||
lines = _io_path(path).read_text(encoding="utf-8-sig").splitlines()
|
||||
except (OSError, UnicodeError) as error:
|
||||
raise TaskCenterError("quick_run_command", "cannot read quick-run command") from error
|
||||
if not lines:
|
||||
@@ -1248,7 +1249,7 @@ def _read_commands(path: Path) -> tuple[tuple[str, str, str, str, str], ...]:
|
||||
|
||||
def _read_command_sheet_targets(path: Path) -> dict[str, tuple[str, str]] | None:
|
||||
try:
|
||||
lines = path.read_text(encoding="utf-8-sig").splitlines()
|
||||
lines = _io_path(path).read_text(encoding="utf-8-sig").splitlines()
|
||||
header = lines[0].split("\t")
|
||||
names = ("job_id", "schematic_name", "sheet_number")
|
||||
present = tuple(name in header for name in names[1:])
|
||||
@@ -1278,7 +1279,7 @@ def _read_sheet_manifest(
|
||||
expected_projects: tuple[ProjectRecord, ...] | None = None,
|
||||
) -> dict[str, tuple[tuple[str, str], ...]]:
|
||||
try:
|
||||
lines = path.read_text(encoding="utf-8-sig").splitlines()
|
||||
lines = _io_path(path).read_text(encoding="utf-8-sig").splitlines()
|
||||
if not lines or lines[0].split("\t") != ["project_path", "schematic_name", "sheet_number"]:
|
||||
raise ValueError("invalid manifest header")
|
||||
result: dict[str, list[tuple[str, str]]] = {}
|
||||
@@ -1319,7 +1320,7 @@ def _read_discovery_inventory(
|
||||
sheets: tuple[tuple[str, str], ...],
|
||||
) -> dict[tuple[str, str], frozenset[str]]:
|
||||
try:
|
||||
lines = path.read_text(encoding="utf-8-sig").splitlines()
|
||||
lines = _io_path(path).read_text(encoding="utf-8-sig").splitlines()
|
||||
if not lines or lines[0].split("\t") != ["project_path", "schematic_name", "sheet_number", "old_part"]:
|
||||
raise ValueError("invalid inventory header")
|
||||
expected_project = _path_key(project_path)
|
||||
@@ -1389,7 +1390,7 @@ def _initial_discovery_status(
|
||||
return rows[0] + "\r\n"
|
||||
commands = _read_commands(command_path)
|
||||
sheets = _read_command_sheet_targets(command_path)
|
||||
targeted = "target_scope" in command_path.read_text(encoding="utf-8-sig").splitlines()[0].split("\t")
|
||||
targeted = "target_scope" in _io_path(command_path).read_text(encoding="utf-8-sig").splitlines()[0].split("\t")
|
||||
if sheets is None:
|
||||
raise TaskCenterError("quick_run_sheet_discovery", "discovery inventory requires page-addressed commands")
|
||||
possible_by_sheet: dict[tuple[str, str, str], set[str]] = {}
|
||||
@@ -1435,12 +1436,12 @@ def _queue_matches_inputs(
|
||||
expected_cells = {str(getattr(rule, "target_cell", "")) for rule in rules}
|
||||
if actual_cells != expected_cells:
|
||||
return False
|
||||
if "target_scope" in command_path.read_text(encoding="utf-8-sig").splitlines()[0].split("\t"):
|
||||
if "target_scope" in _io_path(command_path).read_text(encoding="utf-8-sig").splitlines()[0].split("\t"):
|
||||
sheets = _read_command_sheet_targets(command_path)
|
||||
manifest = _read_sheet_manifest(command_path.with_name("sheets.tsv"), projects) if sheets is not None else None
|
||||
expected = _command_text("expected", "expected", projects, rules, base_mode,
|
||||
sheet_targets=manifest).splitlines()
|
||||
actual = command_path.read_text(encoding="utf-8-sig").splitlines()
|
||||
actual = _io_path(command_path).read_text(encoding="utf-8-sig").splitlines()
|
||||
return (expected[0] == actual[0] and len(expected) == len(actual) and
|
||||
all(expected_row.split("\t")[2:] == actual_row.split("\t")[2:]
|
||||
for expected_row, actual_row in zip(expected[1:], actual[1:])))
|
||||
@@ -1476,10 +1477,10 @@ def _queue_matches_inputs(
|
||||
|
||||
|
||||
def _read_status_details(path: Path) -> tuple[tuple[str, str, str, str], ...]:
|
||||
if not path.exists():
|
||||
if not _io_path(path).exists():
|
||||
return ()
|
||||
try:
|
||||
lines = path.read_text(encoding="utf-8-sig").splitlines()
|
||||
lines = _io_path(path).read_text(encoding="utf-8-sig").splitlines()
|
||||
except (OSError, UnicodeError) as error:
|
||||
raise TaskCenterError("quick_run_status", "cannot read quick-run status") from error
|
||||
if not lines or lines[0].split("\t") != ["job_id", "state", "code", "message"]:
|
||||
@@ -1502,7 +1503,7 @@ def _open_status_for_read(path: Path):
|
||||
deadline = time.monotonic() + 1.0
|
||||
while True:
|
||||
try:
|
||||
return path.open('rb')
|
||||
return _io_path(path).open('rb')
|
||||
except PermissionError:
|
||||
if time.monotonic() >= deadline:
|
||||
raise
|
||||
@@ -1544,7 +1545,7 @@ def _read_appended_status_details(
|
||||
|
||||
def _required_stat(path: Path, code: str, message: str) -> os.stat_result:
|
||||
try:
|
||||
return path.stat()
|
||||
return _io_path(path).stat()
|
||||
except OSError as error:
|
||||
raise TaskCenterError(code, message) from error
|
||||
|
||||
@@ -1593,7 +1594,7 @@ def _write_current_command(
|
||||
state = session.latest.get(job_id)
|
||||
state_path = path.with_name("current-state.tsv")
|
||||
if state is None:
|
||||
state_path.unlink(missing_ok=True)
|
||||
_io_path(state_path).unlink(missing_ok=True)
|
||||
else:
|
||||
_write_atomic_queue_text(state_path,
|
||||
"job_id\tstate\tcode\tmessage\r\n" + "\t".join(
|
||||
@@ -1637,7 +1638,7 @@ def _write_current_command(
|
||||
)
|
||||
if session.next_index == 0 or (previous_state is not None and previous_state[0] != "no_match"):
|
||||
try:
|
||||
state_path.unlink(missing_ok=True)
|
||||
_io_path(state_path).unlink(missing_ok=True)
|
||||
except OSError as error:
|
||||
raise TaskCenterError("quick_run_status", "cannot clear the previous batch state") from error
|
||||
else:
|
||||
@@ -1657,21 +1658,21 @@ def _write_current_command(
|
||||
def _write_atomic_queue_text(path: Path, text: str, code: str, message: str) -> None:
|
||||
temporary = path.with_name(f".{path.name}.{uuid4().hex}.tmp")
|
||||
try:
|
||||
with temporary.open("w", encoding="utf-8", newline="") as handle:
|
||||
with _io_path(temporary).open("w", encoding="utf-8", newline="") as handle:
|
||||
handle.write(text)
|
||||
handle.flush()
|
||||
os.fsync(handle.fileno())
|
||||
deadline = time.monotonic() + 1.0
|
||||
while True:
|
||||
try:
|
||||
os.replace(temporary, path)
|
||||
os.replace(_io_path(temporary), _io_path(path))
|
||||
break
|
||||
except PermissionError:
|
||||
if time.monotonic() >= deadline:
|
||||
raise
|
||||
time.sleep(.02)
|
||||
except OSError as error:
|
||||
temporary.unlink(missing_ok=True)
|
||||
_io_path(temporary).unlink(missing_ok=True)
|
||||
raise TaskCenterError(code, message) from error
|
||||
|
||||
|
||||
@@ -1752,7 +1753,7 @@ def _resolve_cscript(windows_root: Path | None = None, is_64_bit: bool | None =
|
||||
if is_64_bit is None:
|
||||
is_64_bit = sys.maxsize > 2**32 or bool(os.environ.get("PROCESSOR_ARCHITEW6432"))
|
||||
candidate = windows / ("SysWOW64" if is_64_bit else "System32") / "cscript.exe"
|
||||
if candidate.is_file():
|
||||
if _io_path(candidate).is_file():
|
||||
return candidate
|
||||
raise TaskCenterError("quick_run_cscript", "Windows Script Host cscript.exe was not found")
|
||||
|
||||
@@ -1818,7 +1819,7 @@ def _value_mode_matches_option(recorded_mode: str, enabled: bool) -> bool:
|
||||
|
||||
def _queue_value_mode(path: Path) -> str:
|
||||
try:
|
||||
lines = path.read_text(encoding="utf-8-sig").splitlines()
|
||||
lines = _io_path(path).read_text(encoding="utf-8-sig").splitlines()
|
||||
header = lines[0].split("\t")
|
||||
if "value_mode" not in header:
|
||||
return "legacy_part_label"
|
||||
@@ -1836,7 +1837,7 @@ def _queue_value_mode(path: Path) -> str:
|
||||
|
||||
def _read_command_cells(path: Path) -> dict[str, str]:
|
||||
try:
|
||||
lines = path.read_text(encoding="utf-8-sig").splitlines()
|
||||
lines = _io_path(path).read_text(encoding="utf-8-sig").splitlines()
|
||||
header = lines[0].split("\t")
|
||||
if "target_cell" not in header:
|
||||
return {}
|
||||
@@ -1861,7 +1862,7 @@ def _read_command_cells(path: Path) -> dict[str, str]:
|
||||
|
||||
def _read_command_options(path: Path) -> dict[str, tuple[str, str, bool, str]]:
|
||||
try:
|
||||
lines = path.read_text(encoding="utf-8-sig").splitlines()
|
||||
lines = _io_path(path).read_text(encoding="utf-8-sig").splitlines()
|
||||
if not lines:
|
||||
raise ValueError("empty queue")
|
||||
header = lines[0].split("\t")
|
||||
@@ -1977,3 +1978,9 @@ def _validate_target_scope(projects, rules, sheet_targets) -> None:
|
||||
for target in rule.targets:
|
||||
if (_path_key(target.project_path), target.schematic_name, target.sheet_number) not in available:
|
||||
raise TaskCenterError("target_identity", "selected target sheet is missing from discovery")
|
||||
|
||||
|
||||
def _io_path(path):
|
||||
# Snapshot parsers also accept an immutable cached reader. Preserve that
|
||||
# protocol; converting it to Path would bypass the coherent read snapshot.
|
||||
return internal_path(path) if isinstance(path, (str, os.PathLike)) else path
|
||||
@@ -4,6 +4,7 @@ from dataclasses import dataclass, replace
|
||||
import json
|
||||
from pathlib import Path
|
||||
from .errors import TaskCenterError
|
||||
from .path_access import canonical_path, internal_path
|
||||
from .quick_run_protocol import QuickRunProgress
|
||||
|
||||
|
||||
@@ -19,9 +20,9 @@ def failed_native_result_uncertain(root, commands, statuses, *, files=None):
|
||||
continue
|
||||
path = root / f'snapshot-{job}.tsv.native.json'
|
||||
try:
|
||||
report = json.loads(files.read(path) if files is not None else path.read_text(encoding='utf-8-sig'))
|
||||
report = json.loads(files.read(path) if files is not None else internal_path(path).read_text(encoding='utf-8-sig'))
|
||||
except (OSError, UnicodeError, json.JSONDecodeError):
|
||||
if job in awaiting or path.exists():
|
||||
if job in awaiting or internal_path(path).exists():
|
||||
return True
|
||||
continue
|
||||
if not isinstance(report, dict):
|
||||
@@ -56,7 +57,7 @@ class _ReadFiles:
|
||||
def stamp(path):
|
||||
self.checkpoint()
|
||||
try:
|
||||
stat = path.stat()
|
||||
stat = internal_path(path).stat()
|
||||
return (stat.st_dev, stat.st_ino, stat.st_size, stat.st_mtime_ns, stat.st_ctime_ns)
|
||||
except OSError:
|
||||
return None
|
||||
@@ -64,7 +65,7 @@ class _ReadFiles:
|
||||
try:
|
||||
# Include sidecar evidence used by hard-failure recovery as well as
|
||||
# command/status and flags; creation/removal changes the root stamp.
|
||||
entries = tuple(root.iterdir())
|
||||
entries = tuple(internal_path(root).iterdir())
|
||||
except OSError:
|
||||
entries = ()
|
||||
result = {path.name: stamp(path) for path in entries}
|
||||
@@ -85,7 +86,7 @@ class _ReadFiles:
|
||||
self.checkpoint()
|
||||
if path not in self.texts:
|
||||
chunks = []
|
||||
with path.open('r', encoding='utf-8-sig') as source:
|
||||
with internal_path(path).open('r', encoding='utf-8-sig') as source:
|
||||
while True:
|
||||
self.checkpoint()
|
||||
chunk = source.read(65536)
|
||||
@@ -110,7 +111,7 @@ class _CachedPath:
|
||||
|
||||
def exists(self):
|
||||
self.files.checkpoint()
|
||||
return self.path.exists()
|
||||
return internal_path(self.path).exists()
|
||||
|
||||
|
||||
def read_snapshot(preparer, task_id, projects, rules, *, copy_part_number_to_value=False,
|
||||
@@ -148,12 +149,13 @@ def _read_snapshot_once(preparer, task_id, projects, rules, *, copy_part_number_
|
||||
def candidates():
|
||||
yield current
|
||||
files.checkpoint()
|
||||
yield from sorted((path for path in history.glob('obsolete-*') if path.is_dir()), reverse=True)
|
||||
yield from sorted((canonical_path(path) for path in internal_path(history).glob('obsolete-*')
|
||||
if internal_path(path).is_dir()), reverse=True)
|
||||
for candidate in candidates():
|
||||
files.checkpoint()
|
||||
files.track_root(candidate)
|
||||
command = candidate / 'command.tsv'
|
||||
if not command.is_file() or not (candidate / 'status.tsv').is_file():
|
||||
if not internal_path(command).is_file() or not (internal_path(candidate / 'status.tsv')).is_file():
|
||||
continue
|
||||
try:
|
||||
parsed = api._read_commands(files.path(command))
|
||||
@@ -168,7 +170,7 @@ def _read_snapshot_once(preparer, task_id, projects, rules, *, copy_part_number_
|
||||
if root is None:
|
||||
files.checkpoint()
|
||||
return QuickRunSnapshot(progress, False, None, False, 'selection')
|
||||
interrupted = root == current and (root / 'uncertain.flag').is_file()
|
||||
interrupted = root == current and (internal_path(root / 'uncertain.flag')).is_file()
|
||||
phase = 'selection'
|
||||
try:
|
||||
details = api._read_status_details(files.path(root / 'status.tsv'))
|
||||
|
||||
@@ -2,9 +2,11 @@
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
|
||||
from .path_access import internal_path
|
||||
|
||||
|
||||
def copy_worker_script(source: Path, destination: Path) -> None:
|
||||
source, destination = Path(source), Path(destination)
|
||||
source, destination = internal_path(source), internal_path(destination)
|
||||
if source.resolve() == destination.resolve():
|
||||
return
|
||||
shutil.copyfile(source, destination)
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
from pathlib import Path
|
||||
from dx_productivity.trial_task_center.path_access import strip_extended_prefix
|
||||
import pytest
|
||||
from dx_productivity.trial_task_center.models import ProjectRecord, ProjectStatus, RuleRecord
|
||||
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
|
||||
@@ -21,7 +22,7 @@ def test_snapshot_reads_each_file_once_and_uses_same_status(tmp_path, monkeypatc
|
||||
opens = []
|
||||
original = Path.open
|
||||
def tracked(path, *args, **kwargs):
|
||||
if path.parent == handoff.command_path.parent:
|
||||
if Path(strip_extended_prefix(path)).parent == handoff.command_path.parent:
|
||||
opens.append(path.name)
|
||||
return original(path, *args, **kwargs)
|
||||
monkeypatch.setattr(Path, 'open', tracked)
|
||||
@@ -48,7 +49,7 @@ def test_snapshot_cancellation_stops_before_next_file_and_never_writes(tmp_path,
|
||||
def tracked(path, *args, **kwargs):
|
||||
opened.append(path.name)
|
||||
result = original(path, *args, **kwargs)
|
||||
if path == handoff.command_path:
|
||||
if Path(strip_extended_prefix(path)) == handoff.command_path:
|
||||
control.cancelled = True
|
||||
return result
|
||||
monkeypatch.setattr(Path, 'open', tracked)
|
||||
@@ -91,7 +92,7 @@ def test_snapshot_retries_when_uncertain_flag_is_created_during_status_read(tmp_
|
||||
injected = False
|
||||
def racing_open(path, *args, **kwargs):
|
||||
nonlocal injected
|
||||
if path == handoff.status_path and args and args[0] == 'r' and not injected:
|
||||
if Path(strip_extended_prefix(path)) == handoff.status_path and args and args[0] == 'r' and not injected:
|
||||
injected = True
|
||||
(path.parent / 'uncertain.flag').write_text('uncertain', encoding='utf-8')
|
||||
return original(path, *args, **kwargs)
|
||||
@@ -108,7 +109,7 @@ def test_snapshot_retries_command_and_status_as_one_generation(tmp_path, monkeyp
|
||||
injected = False
|
||||
def racing_open(path, *args, **kwargs):
|
||||
nonlocal injected
|
||||
if path == handoff.status_path and args and args[0] == 'r' and not injected:
|
||||
if Path(strip_extended_prefix(path)) == handoff.status_path and args and args[0] == 'r' and not injected:
|
||||
injected = True
|
||||
handoff.command_path.write_text(command.replace(job, 'new-generation'), encoding='utf-8')
|
||||
handoff.status_path.write_text('job_id\tstate\tcode\tmessage\nnew-generation\tno_match\t\tno match\n', encoding='utf-8')
|
||||
@@ -126,7 +127,7 @@ def test_snapshot_continuous_changes_block_continuation_after_bounded_retries(tm
|
||||
reads = 0
|
||||
def racing_open(path, *args, **kwargs):
|
||||
nonlocal reads
|
||||
if path == handoff.status_path and args and args[0] == 'r':
|
||||
if Path(strip_extended_prefix(path)) == handoff.status_path and args and args[0] == 'r':
|
||||
reads += 1
|
||||
(path.parent / 'changing.txt').write_text('x' * reads, encoding='utf-8')
|
||||
return original(path, *args, **kwargs)
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from dx_productivity.trial_task_center.path_access import internal_path
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def deep_root(tmp_path, monkeypatch):
|
||||
if os.name != 'nt':
|
||||
pytest.skip('real Windows long-path regression')
|
||||
root = tmp_path / ('design-' + 'x' * 100) / ('revision-' + 'y' * 100)
|
||||
assert len(str(root)) > 260
|
||||
# Exercise real Windows files while reproducing a host with MAX_PATH-bound
|
||||
# nonextended access, regardless of this developer machine's policy.
|
||||
originals = {name: getattr(Path, name) for name in ('mkdir', 'open', 'stat')}
|
||||
for name, original in originals.items():
|
||||
def strict(path, *args, _original=original, **kwargs):
|
||||
if len(str(path)) >= 260 and not str(path).startswith(chr(92) * 2 + '?'):
|
||||
raise OSError(206, 'legacy MAX_PATH access')
|
||||
return _original(path, *args, **kwargs)
|
||||
monkeypatch.setattr(Path, name, strict)
|
||||
return root
|
||||
|
||||
|
||||
def test_deep_task_event_keeps_public_root_and_rotates_readable_events(deep_root, monkeypatch):
|
||||
from dx_productivity.trial_task_center import logging_setup
|
||||
context = logging_setup.configure_logging(deep_root)
|
||||
monkeypatch.setattr(logging_setup, '_MAX_EVENT_LOG_BYTES', 1)
|
||||
try:
|
||||
for operation in ('first', 'second', 'third'):
|
||||
logging_setup.append_task_event(context, level='INFO', task_id='task', operation=operation)
|
||||
path = deep_root / 'tasks/task/events.jsonl'
|
||||
assert context.root == deep_root
|
||||
assert context.application_log_path == deep_root / 'logs/application.log'
|
||||
assert json.loads(internal_path(path).read_text(encoding='utf-8'))['sequence'] == 3
|
||||
assert json.loads(internal_path(path.with_name('events.jsonl.1')).read_text(encoding='utf-8'))['sequence'] == 2
|
||||
finally:
|
||||
for handler in tuple(context.logger.handlers):
|
||||
handler.close()
|
||||
context.logger.removeHandler(handler)
|
||||
|
||||
|
||||
def test_deep_quick_run_prepare_publish_read_archive_keeps_canonical_results(deep_root, tmp_path):
|
||||
from dx_productivity.trial_task_center import quick_run
|
||||
from dx_productivity.trial_task_center.models import ProjectRecord, ProjectStatus, RuleRecord
|
||||
source = tmp_path / 'worker.vbs'
|
||||
source.write_text('runtime', encoding='utf-8')
|
||||
adapter = source.with_name('NativeSnapshotReader.vbs')
|
||||
adapter.write_text('adapter', encoding='utf-8')
|
||||
project = tmp_path / 'board.prj'
|
||||
project.touch()
|
||||
record = ProjectRecord('project', 'task', 'board', project, tmp_path, True, True, ProjectStatus.PENDING, 0)
|
||||
rule = RuleRecord('rule', 'task', 0, 'OLD', 'NEW', True)
|
||||
preparer = quick_run.QuickRunPreparer(deep_root, script_source=source, run_token_factory=lambda: 'run')
|
||||
handoff = preparer.prepare('task', (record,), (rule,))
|
||||
assert preparer.data_root == deep_root
|
||||
assert handoff.command_path == deep_root / 'quick-run/command.tsv'
|
||||
assert internal_path(handoff.script_path).read_text(encoding='utf-8') == 'runtime\nadapter'
|
||||
assert quick_run._read_commands(handoff.command_path)[0][2] == str(project)
|
||||
assert preparer.read_snapshot('task', (record,), (rule,)).evidence_path == deep_root / 'quick-run'
|
||||
statuses = (('run_0', 'no_match', '', 'done'),)
|
||||
quick_run._write_status_details(handoff.status_path, statuses)
|
||||
assert quick_run._read_status_details(handoff.status_path) == statuses
|
||||
quick_run._write_atomic_queue_text(handoff.command_path.parent / 'current-state.tsv', 'published', 'test', 'test')
|
||||
quick_run._write_uncertain_flag(handoff.command_path.parent / 'uncertain.flag')
|
||||
assert quick_run._queue_has_mutation_evidence(handoff.command_path.parent)
|
||||
archive = preparer.archive_current_handoff('task')
|
||||
assert archive.parent == deep_root / 'quick-run-history'
|
||||
assert quick_run._read_commands(archive / 'command.tsv')[0][2] == str(project)
|
||||
assert quick_run._read_status_details(archive / 'status.tsv') == statuses
|
||||
|
||||
assert preparer.read_snapshot('task', (record,), (rule,)).evidence_path == archive
|
||||
|
||||
def test_deep_native_recovery_keeps_canonical_proof_and_release_logs(deep_root):
|
||||
import hashlib
|
||||
from dx_productivity.trial_task_center.batch_runtime import BatchCadRuntime
|
||||
from test_batch_runtime import Desktop
|
||||
Desktop.created = []
|
||||
Desktop.fail_release = False
|
||||
project = deep_root / 'source/board.prj'
|
||||
database = project.with_name('icdb.dat')
|
||||
internal_path(project.parent).mkdir(parents=True)
|
||||
internal_path(project).write_bytes(b'project')
|
||||
internal_path(database).write_bytes(b'database')
|
||||
evidence = deep_root / 'quick-run-history/native-read'
|
||||
internal_path(evidence).mkdir(parents=True)
|
||||
with BatchCadRuntime(deep_root, 'bom_import', desktop_factory=Desktop) as owner:
|
||||
with owner.native_scope(evidence) as scope:
|
||||
pass
|
||||
proof = {'version': 1, 'native_read_only': True, 'workers_closed': True,
|
||||
'binding': scope.identity, 'project_path': str(project), 'evidence_root': str(evidence),
|
||||
'source_hashes': {str(path): hashlib.sha256(internal_path(path).read_bytes()).hexdigest()
|
||||
for path in (project, database)}}
|
||||
internal_path(evidence / 'native-retry-proof.json').write_text(json.dumps(proof), encoding='utf-8')
|
||||
assert owner.recover_native_failure(project, evidence, 'timeout')
|
||||
assert not owner.recover_native_failure(project, evidence, 'second timeout')
|
||||
assert all(desktop.released for desktop in Desktop.created)
|
||||
assert not owner.record.get('release_log_errors')
|
||||
release = owner.path.with_name('resource-release.log')
|
||||
assert 'resource-release' in str(release)
|
||||
assert 'released' in internal_path(release).read_text(encoding='utf-8')
|
||||
@@ -39,7 +39,9 @@ def test_existing_log_directories_avoid_mkdir_and_recreate_after_removal(tmp_pat
|
||||
directory=tmp_path/'tasks/task';directory.mkdir(parents=True)
|
||||
original=Path.mkdir;calls=[]
|
||||
def mkdir(path,*args,**kwargs):
|
||||
if path==directory:calls.append(path)
|
||||
from dx_productivity.trial_task_center.path_access import strip_extended_prefix
|
||||
canonical = Path(strip_extended_prefix(path))
|
||||
if canonical==directory:calls.append(canonical)
|
||||
return original(path,*args,**kwargs)
|
||||
monkeypatch.setattr(Path,'mkdir',mkdir)
|
||||
assert logging_setup._task_directory(context,'task')==directory
|
||||
|
||||
Reference in new issue
Block a user