|
| 1 | +"""Filesystem and process-I/O telemetry for opaque model downloads.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import os |
| 6 | +import shutil |
| 7 | +import time |
| 8 | +from dataclasses import dataclass |
| 9 | +from pathlib import Path |
| 10 | +from typing import Callable, Iterable, TypedDict |
| 11 | + |
| 12 | + |
| 13 | +@dataclass(frozen=True) |
| 14 | +class _FileState: |
| 15 | + allocated_bytes: int |
| 16 | + size_bytes: int |
| 17 | + modified_ns: int |
| 18 | + |
| 19 | + |
| 20 | +class TelemetrySample(TypedDict): |
| 21 | + downloaded_bytes: int |
| 22 | + total_bytes: int |
| 23 | + downloaded_files: int |
| 24 | + total_files: int |
| 25 | + current_files: list[str] |
| 26 | + bytes_per_second: float |
| 27 | + seconds_since_activity: float |
| 28 | + elapsed_seconds: float |
| 29 | + free_bytes: int |
| 30 | + stalled: bool |
| 31 | + |
| 32 | + |
| 33 | +def _allocated_bytes(stat: os.stat_result) -> int: |
| 34 | + blocks = getattr(stat, "st_blocks", None) |
| 35 | + if isinstance(blocks, int): |
| 36 | + return max(0, blocks * 512) |
| 37 | + return max(0, stat.st_size) |
| 38 | + |
| 39 | + |
| 40 | +def _read_process_write_bytes(pid: int) -> int | None: |
| 41 | + try: |
| 42 | + text = Path(f"/proc/{pid}/io").read_text(encoding="utf-8") |
| 43 | + except (OSError, UnicodeError): |
| 44 | + return None |
| 45 | + for line in text.splitlines(): |
| 46 | + key, separator, value = line.partition(":") |
| 47 | + if separator and key.strip() == "write_bytes": |
| 48 | + try: |
| 49 | + return max(0, int(value.strip())) |
| 50 | + except ValueError: |
| 51 | + return None |
| 52 | + return None |
| 53 | + |
| 54 | + |
| 55 | +class DownloadTelemetry: |
| 56 | + """Measure download activity without intercepting downloader functions.""" |
| 57 | + |
| 58 | + def __init__( |
| 59 | + self, |
| 60 | + roots: Iterable[str | os.PathLike[str]], |
| 61 | + *, |
| 62 | + pid: int, |
| 63 | + stall_seconds: float = 90.0, |
| 64 | + clock: Callable[[], float] = time.monotonic, |
| 65 | + ) -> None: |
| 66 | + if stall_seconds <= 0: |
| 67 | + raise ValueError("stall_seconds must be positive") |
| 68 | + self.roots = tuple(Path(root).resolve() for root in roots) |
| 69 | + if not self.roots: |
| 70 | + raise ValueError("at least one telemetry root is required") |
| 71 | + self.pid = pid |
| 72 | + self.stall_seconds = stall_seconds |
| 73 | + self._clock = clock |
| 74 | + self._files = self._snapshot_files() |
| 75 | + self._baseline_files = dict(self._files) |
| 76 | + self._baseline_process_bytes = _read_process_write_bytes(pid) |
| 77 | + self._last_process_bytes = self._baseline_process_bytes |
| 78 | + self._started_at = self._clock() |
| 79 | + self._sampled_at = self._started_at |
| 80 | + self._last_activity_at = self._started_at |
| 81 | + self._downloaded_bytes = 0 |
| 82 | + |
| 83 | + def _snapshot_files(self) -> dict[Path, _FileState]: |
| 84 | + files: dict[Path, _FileState] = {} |
| 85 | + for root in self.roots: |
| 86 | + if not root.exists(): |
| 87 | + continue |
| 88 | + stack = [root] |
| 89 | + while stack: |
| 90 | + directory = stack.pop() |
| 91 | + try: |
| 92 | + entries = list(os.scandir(directory)) |
| 93 | + except OSError: |
| 94 | + continue |
| 95 | + for entry in entries: |
| 96 | + try: |
| 97 | + if entry.is_dir(follow_symlinks=False): |
| 98 | + stack.append(Path(entry.path)) |
| 99 | + elif entry.is_file(follow_symlinks=False): |
| 100 | + stat = entry.stat(follow_symlinks=False) |
| 101 | + files[Path(entry.path)] = _FileState( |
| 102 | + allocated_bytes=_allocated_bytes(stat), |
| 103 | + size_bytes=max(0, stat.st_size), |
| 104 | + modified_ns=max(0, stat.st_mtime_ns), |
| 105 | + ) |
| 106 | + except OSError: |
| 107 | + continue |
| 108 | + return files |
| 109 | + |
| 110 | + def _display_path(self, path: Path) -> str: |
| 111 | + for root in self.roots: |
| 112 | + try: |
| 113 | + return str(path.relative_to(root)) |
| 114 | + except ValueError: |
| 115 | + continue |
| 116 | + return path.name |
| 117 | + |
| 118 | + def _free_bytes(self) -> int: |
| 119 | + values: list[int] = [] |
| 120 | + for root in self.roots: |
| 121 | + probe = root |
| 122 | + while not probe.exists() and probe != probe.parent: |
| 123 | + probe = probe.parent |
| 124 | + try: |
| 125 | + values.append(shutil.disk_usage(probe).free) |
| 126 | + except OSError: |
| 127 | + continue |
| 128 | + return min(values) if values else 0 |
| 129 | + |
| 130 | + def sample(self) -> TelemetrySample: |
| 131 | + """Return one monotonic activity sample in manager-compatible fields.""" |
| 132 | + now = self._clock() |
| 133 | + files = self._snapshot_files() |
| 134 | + changed: list[Path] = [] |
| 135 | + for path, state in files.items(): |
| 136 | + previous = self._files.get(path) |
| 137 | + if previous is None or state != previous: |
| 138 | + changed.append(path) |
| 139 | + |
| 140 | + filesystem_delta = sum( |
| 141 | + max(0, state.allocated_bytes - self._baseline_files.get(path, _FileState(0, 0, 0)).allocated_bytes) |
| 142 | + for path, state in files.items() |
| 143 | + ) |
| 144 | + process_bytes = _read_process_write_bytes(self.pid) |
| 145 | + process_delta = 0 |
| 146 | + if process_bytes is not None and self._baseline_process_bytes is not None: |
| 147 | + process_delta = max(0, process_bytes - self._baseline_process_bytes) |
| 148 | + |
| 149 | + measured = max(filesystem_delta, process_delta) |
| 150 | + previous_downloaded = self._downloaded_bytes |
| 151 | + self._downloaded_bytes = max(self._downloaded_bytes, measured) |
| 152 | + process_moved = ( |
| 153 | + process_bytes is not None |
| 154 | + and self._last_process_bytes is not None |
| 155 | + and process_bytes > self._last_process_bytes |
| 156 | + ) |
| 157 | + if changed or process_moved or self._downloaded_bytes > previous_downloaded: |
| 158 | + self._last_activity_at = now |
| 159 | + |
| 160 | + elapsed = max(0.0, now - self._sampled_at) |
| 161 | + bytes_per_second = ( |
| 162 | + max(0, self._downloaded_bytes - previous_downloaded) / elapsed |
| 163 | + if elapsed > 0 |
| 164 | + else 0.0 |
| 165 | + ) |
| 166 | + quiet = max(0.0, now - self._last_activity_at) |
| 167 | + active_files = sorted(self._display_path(path) for path in changed)[:20] |
| 168 | + self._files = files |
| 169 | + self._last_process_bytes = process_bytes |
| 170 | + self._sampled_at = now |
| 171 | + |
| 172 | + return { |
| 173 | + "downloaded_bytes": self._downloaded_bytes, |
| 174 | + "total_bytes": 0, |
| 175 | + "downloaded_files": 0, |
| 176 | + "total_files": 0, |
| 177 | + "current_files": active_files, |
| 178 | + "bytes_per_second": round(bytes_per_second, 2), |
| 179 | + "seconds_since_activity": round(quiet, 2), |
| 180 | + "elapsed_seconds": round(max(0.0, now - self._started_at), 2), |
| 181 | + "free_bytes": self._free_bytes(), |
| 182 | + "stalled": quiet >= self.stall_seconds, |
| 183 | + } |
0 commit comments