diff --git a/CHANGELOG.md b/CHANGELOG.md index 1394f95..5e8ea17 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -623,6 +623,15 @@ project uses [semantic versioning][semver]. exactly, because there the byte is the useful fact; a run of them is bounded by the first and the last, because there it is not. +- **Progress lines when stderr is not a terminal.** A background job, CI run + or redirected log used to print nothing until the final summary, so a + six-hour `offloader report` was indistinguishable from a hung one. Off a TTY, + `offload`, `report` and `verify` now write plain newline-terminated lines + (percent of job bytes, files done/total, file name, throughput and ETA): one + when a file starts, one every 30 s (including partway through a single large + file, via a new `on_bytes` callback on `hash_file`), and one on completion. The single-line + bar on a terminal is unchanged and `--quiet` still silences both. + ### Fixed Found by fuzzing the edges: `tests/test_fuzz_edges.py` for what a card can diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a60b5ed..012ecb4 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -37,7 +37,7 @@ pip install -e ".[dev]" `ffmpeg` and `ffprobe` on `PATH` are optional — the suite runs without them. ```sh -pytest # 916 tests, about 20s +pytest # 1308 tests, about 20s pytest --fuzz # property tests at 3000 examples each, about 3 min ruff check src tests pytest --cov=offloader --cov-report=term-missing diff --git a/README.md b/README.md index 69126c6..e82a905 100644 --- a/README.md +++ b/README.md @@ -635,13 +635,13 @@ Full verification only when every present destination was hashed. ```sh pip install -e ".[dev]" -pytest # 916 tests, ~20s +pytest # 1308 tests, ~20s pytest --fuzz # same suite, 3000 examples per property (~3 min) ruff check src tests pytest --cov=offloader --cov-report=term-missing ``` -916 tests at 89% line coverage. They cover formatting against the reference's +1308 tests at 88% line coverage. They cover formatting against the reference's exact strings, checksum vectors and streaming equivalence, copy/verify behaviour including simulated destination corruption, pause/resume/cancel concurrency, retry discrimination, BRAW container parsing, ffprobe parsing, diff --git a/src/offloader/cli.py b/src/offloader/cli.py index cc12f2d..faa795b 100644 --- a/src/offloader/cli.py +++ b/src/offloader/cli.py @@ -39,25 +39,46 @@ EXIT_UNRESOLVED = EXIT_INCOMPLETE +#: Seconds between periodic progress lines when stderr is not a terminal. +LOG_INTERVAL = 30.0 +#: Minimum seconds between "file started" lines, so a card of thousands of +#: small clips cannot flood a log. +LOG_START_GAP = 1.0 + + class _Progress: - """Single-line progress on stderr; silent when not a TTY.""" + """Progress on stderr: a single redrawn line on a TTY, plain lines otherwise. + + A background job or CI run has no terminal to redraw, and a six-hour run + that logs nothing until its summary is indistinguishable from a hung one. + So off a TTY it writes newline-terminated lines, throttled to stay readable. + `--quiet` silences both. + """ def __init__(self, enabled: bool) -> None: - self.enabled = enabled and sys.stderr.isatty() + self.enabled = enabled + self.tty = sys.stderr.isatty() self._last = 0.0 self._width = 0 + self._started = time.monotonic() + self._last_start = -LOG_START_GAP + self._last_log = self._started + self._key: tuple[int, str] | None = None + self._logged_final = False def __call__(self, event: engine.ProgressEvent) -> None: if not self.enabled: return now = time.monotonic() final = event.job_bytes_done >= event.job_bytes_total + if not self.tty: + self._log(event, now, final) + return if now - self._last < 0.1 and not final: return self._last = now - pct = (event.job_bytes_done / event.job_bytes_total * 100 - if event.job_bytes_total else 100.0) + pct = self._percent(event) line = (f" [{pct:5.1f}%] {event.stage:<6} " f"{event.file_index + 1}/{event.file_total} {event.file_name}") line = line[:110] @@ -66,8 +87,40 @@ def __call__(self, event: engine.ProgressEvent) -> None: sys.stderr.write("\r" + line + " " * pad) sys.stderr.flush() + @staticmethod + def _percent(event: engine.ProgressEvent) -> float: + return (event.job_bytes_done / event.job_bytes_total * 100 + if event.job_bytes_total else 100.0) + + def _log(self, event: engine.ProgressEvent, now: float, final: bool) -> None: + key = (event.file_index, event.stage) + new_file = key != self._key + self._key = key + due = now - self._last_log >= LOG_INTERVAL + started = new_file and now - self._last_start >= LOG_START_GAP + finished = final and not self._logged_final + if not (due or started or finished): + return + if new_file: + self._last_start = now + self._last_log = now + self._logged_final = self._logged_final or final + + pct = self._percent(event) + parts = [f"[{pct:5.1f}%] {event.stage} " + f"{event.file_index + 1}/{event.file_total} {event.file_name}"] + elapsed = now - self._started + if event.job_bytes_done and elapsed > 0: + rate = event.job_bytes_done / elapsed + parts.append(f"{format_size(int(rate))}/s") + remaining = event.job_bytes_total - event.job_bytes_done + if remaining > 0: + parts.append(f"ETA {format_elapsed(remaining / rate)}") + sys.stderr.write(" ".join(parts) + "\n") + sys.stderr.flush() + def done(self) -> None: - if self.enabled and self._width: + if self.enabled and self.tty and self._width: sys.stderr.write("\r" + " " * self._width + "\r") sys.stderr.flush() self._width = 0 @@ -629,26 +682,59 @@ def cmd_verify(args: argparse.Namespace) -> int: print(f"error: no .mhl manifest found under {target}", file=sys.stderr) return 2 - show = not args.quiet and sys.stderr.isatty() + show = not args.quiet + tty = sys.stderr.isatty() + last_log = time.monotonic() + last_start = -LOG_START_GAP + started_index = -1 def progress(index: int, total: int, path: Path) -> None: - if show: + if show and tty: sys.stderr.write('\r' + f" [{index + 1}/{total}] {path.name[:70]:<70}") sys.stderr.flush() + def log_bytes(index: int, total: int, path: Path, done: int, size: int) -> None: + """Off a TTY: a line as each file starts and one per LOG_INTERVAL after. + + Percent counts files completed plus the share of this one read so far, + and stops short of 100 until the last hash has returned (the manifest's + own completion line below says so). + """ + nonlocal last_log, last_start, started_index + if not show or tty: + return + now = time.monotonic() + new_file = index != started_index + started_index = index + due = now - last_log >= LOG_INTERVAL + if not (due or (new_file and now - last_start >= LOG_START_GAP)): + return + if new_file: + last_start = now + last_log = now + share = done / size if size else 0.0 + pct = min((index + share) / total * 100, 99.9) if total else 0.0 + sys.stderr.write(f"[{pct:5.1f}%] verify {index + 1}/{total} {path.name}\n") + sys.stderr.flush() + worst = 0 reports = [] for manifest in manifests: try: - reports.append(verify_mod.verify_manifest( - manifest, progress=progress, bypass_cache=not args.allow_cache, - confine_to=confine_to)) + report = verify_mod.verify_manifest( + manifest, progress=progress, bytes_progress=log_bytes, + bypass_cache=not args.allow_cache, confine_to=confine_to) + reports.append(report) except Exception as exc: print(f"error: could not read {manifest}: {exc}", file=sys.stderr) worst = max(worst, 2) continue - if show: + if show and tty: sys.stderr.write('\r' + " " * 90 + '\r') + elif show and report.verdicts: + sys.stderr.write(f"[100.0%] verify {len(report.verdicts)}/" + f"{len(report.verdicts)} {manifest.name} done\n") + sys.stderr.flush() # Every manifest is checked before any is reported, so a rerun's manifest # can answer the entries an earlier failed run could not hash. Only that diff --git a/src/offloader/engine.py b/src/offloader/engine.py index f2d2757..a24cd0e 100644 --- a/src/offloader/engine.py +++ b/src/offloader/engine.py @@ -1696,9 +1696,15 @@ def copy_once(_src=source, _partials=partials, _idx=index, # the job before promotion. JobCancelled is not an # OSError, so retry_mod.call lets it propagate. dst_sum, verify_attempts = retry_mod.call( - lambda p=partial: hash_file( + lambda p=partial, _i=index, _s=source, _z=stat.st_size: + hash_file( p, options.algorithm, - checkpoint=control.checkpoint if control else None), + checkpoint=control.checkpoint if control else None, + on_bytes=lambda n: emit(ProgressEvent( + _i, len(files), _s.name, "verify", + n, _z, + counters.job_bytes_done, + counters.job_bytes_total))), options.retry, sleep=_sleeper(control), ) @@ -2097,7 +2103,12 @@ def rescan(source_root: Path, destination_roots: Sequence[Path], 0, stat.st_size, done, total)) if algorithm.factory is not None: try: - entry.checksum = hash_file(source, options.algorithm) + entry.checksum = hash_file( + source, options.algorithm, + on_bytes=lambda n, _i=index, _s=source, _z=stat.st_size, _d=done: + progress(ProgressEvent(_i, len(files), _s.name, "verify", + n, _z, _d + n, total)) + if progress else None) except OSError: entry.checksum = None done += stat.st_size @@ -2162,6 +2173,12 @@ def rescan(source_root: Path, destination_roots: Sequence[Path], f"{source.name}: metadata could not be read ({exc})") job.files.append(entry) + if progress and files: + # The last per-file event fires before that file is hashed, so say + # outright that the job is complete. + progress(ProgressEvent(len(files) - 1, len(files), files[-1].name, "verify", + stat.st_size, stat.st_size, total, total)) + # Claim a verification level only for work this call did. Anything that # was not read back (no hash algorithm, or the source standing in as its # own destination) leaves the job at NONE. diff --git a/src/offloader/hashers.py b/src/offloader/hashers.py index c082b12..0709f9e 100644 --- a/src/offloader/hashers.py +++ b/src/offloader/hashers.py @@ -134,12 +134,16 @@ def new_hasher(key: str) -> Hasher: return get_algorithm(key).new() or _NullHasher() -def hash_file(path: Path, key: str, chunk_size: int = 8 << 20, *, +def hash_file(path: Path, key: str, chunk_size: int = 8 << 20, + on_bytes: Callable[[int], None] | None = None, *, checkpoint: Callable[[], None] | None = None) -> str: """Hash a file off disk. Used by full verification to re-read a destination, and by the `report` and `verify` commands to reconstruct or re-check checksums without copying. + `on_bytes`, if given, is called with the running byte count after each + chunk, so a caller can show progress inside one very large file. + `checkpoint`, when given, is called before every chunk read. The engine passes `JobControl.checkpoint` so a long reread blocks on pause and raises on cancel; whatever it raises propagates and the file is left unhashed. @@ -153,6 +157,7 @@ def hash_file(path: Path, key: str, chunk_size: int = 8 << 20, *, raise ValueError(f"chunk_size must be positive, got {chunk_size}") hasher = new_hasher(key) + read = 0 with open_binary(path, "rb") as handle: while True: if checkpoint is not None: @@ -161,6 +166,9 @@ def hash_file(path: Path, key: str, chunk_size: int = 8 << 20, *, if not chunk: break hasher.update(chunk) + read += len(chunk) + if on_bytes: + on_bytes(read) return hasher.hexdigest() diff --git a/src/offloader/verify.py b/src/offloader/verify.py index 3ce5537..822773d 100644 --- a/src/offloader/verify.py +++ b/src/offloader/verify.py @@ -372,6 +372,7 @@ def verify_manifest( manifest: Path, *, progress: Callable[[int, int, Path], None] | None = None, + bytes_progress: Callable[[int, int, Path, int, int], None] | None = None, bypass_cache: bool = True, find_unlisted: bool = True, check_directories: bool = True, @@ -382,6 +383,9 @@ def verify_manifest( `bypass_cache` evicts each file before reading it, so a freshly written tree is read off the device rather than out of memory. + `progress` fires as each entry starts; `bytes_progress` (index, total, path, + bytes read, file size) fires after each chunk read within the entry. + `check_directories` recomputes an ASC MHL manifest's directory hashes from the files the manifest lists, mirroring the writer, whose directory hashes and root hash cover only the job's own files. Files the manifest does not @@ -535,7 +539,11 @@ def _evict(path: Path) -> None: actual_size = longpath.stat(path).st_size if bypass_cache: _evict(path) - actual = hash_file(path, algorithm_key) + actual = hash_file( + path, algorithm_key, + on_bytes=(lambda n, _i=index, _p=path, _z=actual_size: + bytes_progress(_i, len(entries), _p, n, _z)) + if bytes_progress else None) except OSError as exc: note(entry, None) report.verdicts.append( diff --git a/tests/test_cli.py b/tests/test_cli.py index 238e130..fb54da5 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -111,13 +111,176 @@ def test_multiple_destinations(source_tree: Path, tmp_path: Path): # ------------------------------------------------------------------ progress -def test_progress_is_silent_when_stderr_is_not_a_tty(capsys): - """Piped output must stay clean for logs and CI.""" +class _PipedStderr: + """A stderr that is not a terminal, capturing what is written.""" + + def __init__(self) -> None: + self.written: list[str] = [] + + @staticmethod + def isatty(): + return False + + def write(self, text): + self.written.append(text) + + @staticmethod + def flush(): + pass + + @property + def text(self) -> str: + return "".join(self.written) + + +def _event(index=0, total=3, name="clip.mov", stage="copy", done=5, size=10): + return cli.engine.ProgressEvent(index, total, name, stage, 0, 10, done, size) + + +def test_progress_writes_plain_lines_when_stderr_is_not_a_tty(monkeypatch): + """A background job must leave a trail in its log, never a redrawn line.""" + err = _PipedStderr() + monkeypatch.setattr(cli.sys, "stderr", err) + clock = iter([100.0, 105.0]) + monkeypatch.setattr(cli.time, "monotonic", lambda: next(clock)) + progress = cli._Progress(enabled=True) + progress(_event(0, done=5, size=20)) + progress.done() + assert err.text.endswith("\n") + assert "\r" not in err.text + line = err.text.splitlines()[0] + assert "25.0%" in line and "1/3" in line and "clip.mov" in line + assert "/s" in line and "ETA" in line + + +def test_progress_lines_are_throttled_off_a_tty(monkeypatch): + err = _PipedStderr() + monkeypatch.setattr(cli.sys, "stderr", err) + now = [1000.0] + monkeypatch.setattr(cli.time, "monotonic", lambda: now[0]) progress = cli._Progress(enabled=True) - assert not progress.enabled - progress(cli.engine.ProgressEvent(0, 1, "clip.mov", "copy", 0, 10, 5, 10)) + + progress(_event(0, done=1, size=100)) # file start: logged + progress(_event(0, done=2, size=100)) # same file, too soon: dropped + now[0] += 0.2 + progress(_event(1, done=3, size=100)) # new file inside the gap: dropped + assert len(err.text.splitlines()) == 1 + + now[0] += cli.LOG_INTERVAL + progress(_event(1, done=4, size=100)) # periodic line + assert len(err.text.splitlines()) == 2 + + now[0] += 2 + progress(_event(2, done=5, size=100)) # next file start + assert len(err.text.splitlines()) == 3 + + progress(_event(2, done=100, size=100)) # completion, once + progress(_event(2, done=100, size=100)) + assert len(err.text.splitlines()) == 4 + assert "100.0%" in err.text.splitlines()[-1] + + +def test_quiet_progress_is_silent_off_a_tty(monkeypatch): + err = _PipedStderr() + monkeypatch.setattr(cli.sys, "stderr", err) + progress = cli._Progress(enabled=False) + progress(_event(done=10, size=10)) progress.done() - assert capsys.readouterr().err == "" + assert err.text == "" + + +class _SlowHandle: + """Four 10-byte reads, each costing 20 s on the fake clock, and a hook that + sees whatever has been logged so far at the moment each read happens.""" + + def __init__(self, clock, on_read): + self._clock, self._on_read, self._left = clock, on_read, 4 + + def __enter__(self): + return self + + def __exit__(self, *exc): + return False + + def read(self, _n): + self._on_read() + self._clock[0] += 20.0 + if self._left: + self._left -= 1 + return b"x" * 10 + return b"" + + +def _slow_reads(monkeypatch, err, on_read=lambda: None): + clock = [1000.0] + monkeypatch.setattr(cli.sys, "stderr", err) + monkeypatch.setattr(cli.time, "monotonic", lambda: clock[0]) + monkeypatch.setattr(cli.longpath, "open_binary", + lambda *a, **k: _SlowHandle(clock, on_read)) + + +def test_report_logs_a_periodic_line_while_one_file_is_still_hashing( + tmp_path: Path, monkeypatch): + """A 37 GB clip must not leave the log silent for the whole read.""" + source = tmp_path / "card" + source.mkdir() + (source / "only.mov").write_bytes(b"x" * 40) + err = _PipedStderr() + _slow_reads(monkeypatch, err) + seen_mid_file: list[str] = [] + + real = cli.engine.hash_file + + def spy(path, key, *a, **k): + digest = real(path, key, *a, **k) + seen_mid_file.append(err.text) # before rescan returns + return digest + + monkeypatch.setattr(cli.engine, "hash_file", spy) + assert cli.main(["report", "--source", str(source), "--name", "A001", + "--no-probe", "--report", "csv"]) == 0 + mid = seen_mid_file[0].splitlines() + # One line when the file starts, then at least one periodic line before + # the hash finished, each showing progress within the file. + assert len(mid) >= 2 + assert any("%" in line and "ETA" in line for line in mid[1:]) + + +def test_report_logs_a_completion_line(source_tree: Path, capsys): + cli.main(["report", "--source", str(source_tree), "--name", "A001", + "--no-probe", "--report", "csv"]) + lines = capsys.readouterr().err.splitlines() + assert lines and lines[-1].startswith("[100.0%]") + + +def test_verify_does_not_claim_100_percent_before_the_last_hash_returns( + source_tree: Path, tmp_path: Path, monkeypatch, capsys): + destination = tmp_path / "d1" + cli.main(["offload", "--source", str(source_tree), "--dest", str(destination), + "--name", "A001", "--verify", "full", "--report", "mhl", + "--no-probe", "--quiet"]) + capsys.readouterr() + err = _PipedStderr() + snapshots: list[str] = [] + _slow_reads(monkeypatch, err, on_read=lambda: snapshots.append(err.text)) + cli.main(["verify", str(destination)]) + assert snapshots and all("100.0%" not in text for text in snapshots) + assert "[100.0%]" in err.text + + +def test_report_command_logs_progress_off_a_tty_and_quiet_silences_it( + source_tree: Path, tmp_path: Path, monkeypatch, capsys): + # capsys replaces stderr with a non-TTY object, the case under test. + code = cli.main(["report", "--source", str(source_tree), + "--name", "A001", "--no-probe"]) + assert code == 0 + err = capsys.readouterr().err + assert "%]" in err and err.endswith("\n") and "\r" not in err + + code = cli.main(["report", "--source", str(source_tree), + "--name", "A001", "--no-probe", "--quiet"]) + assert code == 0 + assert "%]" not in capsys.readouterr().err def test_progress_renders_a_throttled_single_line(monkeypatch): @@ -221,6 +384,22 @@ def test_verify_passes_on_a_clean_tree(source_tree: Path, tmp_path: Path, capsys assert "safe to erase" in out +def test_verify_logs_plain_lines_off_a_tty_and_quiet_silences_them( + source_tree: Path, tmp_path: Path, capsys): + destination = tmp_path / "d1" + cli.main(["offload", "--source", str(source_tree), "--dest", str(destination), + "--name", "A001", "--verify", "full", "--report", "mhl", + "--no-probe", "--quiet"]) + capsys.readouterr() + + assert cli.main(["verify", str(destination)]) == 0 + err = capsys.readouterr().err + assert "verify 1/" in err and err.endswith("\n") and "\r" not in err + + assert cli.main(["verify", str(destination), "--quiet"]) == 0 + assert "verify 1/" not in capsys.readouterr().err + + def test_verify_fails_on_a_flipped_bit(source_tree: Path, tmp_path: Path, capsys): destination = tmp_path / "d1" cli.main(["offload", "--source", str(source_tree), "--dest", str(destination), diff --git a/tests/test_control.py b/tests/test_control.py index c6baa97..3557a18 100644 --- a/tests/test_control.py +++ b/tests/test_control.py @@ -706,7 +706,9 @@ def test_cancel_during_the_second_destination_reread_records_the_missing_copy( verifies: list[str] = [] def progress(event: engine.ProgressEvent) -> None: - if event.stage == "verify": + # A reread announces itself with a zero-byte event, then reports + # bytes as it goes: count rereads, not their progress lines. + if event.stage == "verify" and event.bytes_done == 0: verifies.append(event.file_name) if len(verifies) == 2: control.cancel() @@ -780,7 +782,9 @@ def test_a_cancelled_destination_never_verifies_from_its_manifests( verifies: list[str] = [] def progress(event: engine.ProgressEvent) -> None: - if event.stage == "verify": + # A reread announces itself with a zero-byte event, then reports + # bytes as it goes: count rereads, not their progress lines. + if event.stage == "verify" and event.bytes_done == 0: verifies.append(event.file_name) if len(verifies) == 2: control.cancel()