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)
|
||||
|
||||
Reference in new issue
Block a user