"""Resumable HTTP acquisition with disk reserve, hashes and atomic progress snapshots. This module never extracts archives, evaluates remote code or initializes CUDA. Dataset payloads remain separate from licensed/validated training caches. """ from __future__ import annotations from concurrent.futures import ThreadPoolExecutor, as_completed import hashlib import json import os from pathlib import Path import shutil import threading import time import requests class AccessBlocked(RuntimeError): pass class DiskBudget(RuntimeError): pass class FileTooLarge(ValueError): pass def _comparable_path(path: Path) -> Path: """Normalize Windows namespace aliases after resolving symlinks/junctions. Non-strict realpath can retain the extended prefix when a parent directory appears concurrently. Compare both spellings consistently; do not skip the resolved-path containment check. """ if os.name == "nt": value = str(path) if value.startswith("\\\\?\\UNC\\"): return Path("\\\\" + value[8:]) if value.startswith("\\\\?\\") and len(value) >= 7 and value[5:7] == ":\\": return Path(value[4:]) return path def exception_summary(exc: Exception, limit: int = 180) -> str: lines = str(exc).splitlines() return type(exc).__name__ + ": " + (lines[0][:limit] if lines else "no additional detail") class Downloads: def __init__(self, root: str | Path, max_gib: float = 70, reserve_gib: float = 25): self.root = Path(root).resolve() self.root.mkdir(parents=True, exist_ok=True) self.maximum, self.reserve = int(max_gib * 2**30), int(reserve_gib * 2**30) self.lock = threading.RLock() self.last_save = 0.0 self.bytes = sum(p.stat().st_size for p in self.root.rglob("*") if p.is_file()) self.state = {"pid": os.getpid(), "started": time.time(), "training_started": False, "max_gib": max_gib, "reserve_gib": reserve_gib, "sources": {}} self.current: dict = {} def safe_path(self, rel: str) -> Path: p = (self.root / rel).resolve() if not _comparable_path(p).is_relative_to(_comparable_path(self.root)): raise ValueError("download path escapes acquisition directory") return p def save(self, force=False): with self.lock: if not force and time.time() - self.last_save < 3: return self.last_save = time.time() self.state |= {"updated": time.time(), "stored_bytes": self.bytes, "free_bytes": shutil.disk_usage(self.root).free, "current_files": dict(self.current)} tmp = self.root / "download_status.json.tmp" tmp.write_text(json.dumps(self.state, indent=2), encoding="utf-8") # Windows readers briefly deny replacement while their file handle # is open (for example, the live dashboard). Keep the last complete # snapshot visible and retry this atomic swap for a bounded period. for attempt in range(8): try: os.replace(tmp, self.root / "download_status.json") break except PermissionError: if attempt == 7: raise time.sleep(0.01 * 2**attempt) def event(self, source, status, **kwargs): with self.lock: old = self.state["sources"].setdefault(source, {}) old.update({"status": status, "updated": time.time(), **kwargs}) self.save(force=True) print(json.dumps({"source": source, "status": status, **kwargs}), flush=True) def _claim(self, amount): with self.lock: if self.bytes + amount > self.maximum: raise DiskBudget(f"{self.maximum / 2**30:g} GiB acquisition cap reached") if shutil.disk_usage(self.root).free - amount < self.reserve: raise DiskBudget("25 GiB free-space reserve reached") self.bytes += amount def _record(self, record): with self.lock: with (self.root / "files.jsonl").open("a", encoding="utf-8") as f: f.write(json.dumps(record) + "\n") def get(self, url: str, rel: str, expected_size: int | None = None, checksum: str | None = None, headers: dict | None = None, max_file_bytes: int = 12 * 2**30, retries: int = 3) -> Path: """Resume .part with validated Content-Range. HTTP credentials are never logged.""" path = self.safe_path(rel) path.parent.mkdir(parents=True, exist_ok=True) if path.exists(): if expected_size is not None and path.stat().st_size != expected_size: raise ValueError(f"existing size mismatch: {rel}") if checksum: alg, value = checksum.split(":", 1) if self.hash(path, alg) != value: raise ValueError(f"existing checksum mismatch: {rel}") return path part = path.with_name(path.name + ".part") for attempt in range(retries): try: offset = part.stat().st_size if part.exists() else 0 h = {**(headers or {}), "Accept-Encoding": "identity"} if offset: h["Range"] = f"bytes={offset}-" with requests.get(url, headers=h, stream=True, timeout=(25, 90)) as response: if response.status_code in (401, 403): raise AccessBlocked(f"access approval required for {rel} (HTTP {response.status_code})") response.raise_for_status() if offset and response.status_code != 206: # Server ignored range. Restart this owned partial file, accounting for the old bytes. with self.lock: self.bytes -= offset offset = 0 if response.status_code == 206 and not response.headers.get("Content-Range", "").startswith(f"bytes {offset}-"): raise ValueError("server returned a mismatched byte range") length = int(response.headers.get("Content-Length", "0")) if offset + length > max_file_bytes or (expected_size is not None and expected_size > max_file_bytes): raise FileTooLarge(f"file exceeds per-file limit: {rel}") if expected_size is not None and offset + length and length and expected_size != offset + length: raise ValueError(f"unexpected remote size for {rel}") with part.open("ab" if offset else "wb") as f: for chunk in response.iter_content(1024 * 1024): if not chunk: continue if f.tell() + len(chunk) > max_file_bytes: raise FileTooLarge("stream exceeded per-file limit") self._claim(len(chunk)) try: f.write(chunk) except Exception: with self.lock: self.bytes -= len(chunk) raise with self.lock: self.current[rel] = {"bytes": f.tell(), "expected": expected_size or offset + length or None} self.save() if expected_size is not None and part.stat().st_size != expected_size: raise ValueError(f"truncated file: {rel}") if length and part.stat().st_size != offset + length: raise ValueError(f"truncated HTTP body: {rel}") sha = self.hash(part) if checksum: alg, value = checksum.split(":", 1) actual = sha if alg == "sha256" else self.hash(part, alg) if actual != value: raise ValueError(f"checksum mismatch: {rel}; partial retained for inspection") os.replace(part, path) self._record({"path": rel, "bytes": path.stat().st_size, "sha256": sha, "source_url": url, "publisher_checksum": checksum, "completed": time.time()}) with self.lock: self.current.pop(rel, None) self.save(force=True) return path except (AccessBlocked, DiskBudget, FileTooLarge): raise except Exception: if attempt + 1 == retries: raise time.sleep(min(2**attempt, 8)) raise AssertionError("unreachable") @staticmethod def hash(path, alg="sha256"): h = hashlib.new(alg) with Path(path).open("rb") as f: for chunk in iter(lambda: f.read(4 * 1024 * 1024), b""): h.update(chunk) return h.hexdigest() def batch(self, jobs: list[dict], workers=3): errors = [] with ThreadPoolExecutor(workers) as pool: futures = {pool.submit(self.get, **job): job["rel"] for job in jobs} for future in as_completed(futures): try: future.result() except Exception as e: errors.append({"path": futures[future], "error": exception_summary(e)}) if isinstance(e, DiskBudget): for f in futures: f.cancel() return errors